Verify a testing filename in Python using a certain schema

Viewed 24

I am building a testing framework and have outputs going into folder structures. I would like to verify if these outputs fit a certain schema at the point at which I generate the filename.

Example schema: test_<output_type>_<folder_type>_<int>.json

Example output: test_outputabc_success_0.json

The output_type and folder_type are strings, whilst the int can be any real number (however, in reality won't be larger than 1000.)

I have looked into and implemented things such as endswith('.json') and startswith('test_').

I could use replace() method to check different parts, which I will do if there is nothing better. I think I can use isdigit() as well to check the integer.

I am not very familiar with regex, but expect that could help.

Any ideas on a simple way to verify the entire string which doesn't involve checking these one-by-one? I am happy to create a dictionary or lists which include all possible acceptable sub-strings.

Thanks!

1 Answers

Regex would be the easiest choice:

import re
name = "test_outputabc_success_0.json"
result = re.fullmatch(r"test(_[^\W_]+){2}_\d+\.json", name)
if result:
  print("matching!")

Regex explanation:

  • test - starts with "test".
  • (_[^\W_]+){2} - two occurances ({2}) of 1 or more letters [^\W_]+ not including _ (underscore), preceding with an underscore. Basically _word_word.
  • _ - an underscore
  • \d+ - a sequence of 1 or more digits
  • \.json - ending with .json (the . is escaped).

You can even capture the output_type, folder_type and int like so:

import re
name = "test_outputabc_success_0.json"
result = re.fullmatch(
  r"test_(?P<output_type>[^\W_]+)_(?P<folder_type>[^\W_]+)_(?P<int>\d+)\.json", name)
if result:
    # Outputs {'output_type': 'outputabc', 'folder_type': 'success', 'int': '0'}
    print(result.groupdict())

Regex is extremely powerful!

Related