Skip to content

Instantly share code, notes, and snippets.

@jonocodes
Created June 1, 2023 03:26
Show Gist options
  • Save jonocodes/8b6c2bc2ecde47bf96c9064b631d486c to your computer and use it in GitHub Desktop.
Save jonocodes/8b6c2bc2ecde47bf96c9064b631d486c to your computer and use it in GitHub Desktop.
Python matcher idea

I often find myself needing to write tests against incomplete data. This is particularly useful when using generators like FactoryBoy or Model Bakery that create random fake values.

I have often looked around for a way to easily test partial data matching for complex responses. But never found anything.

So I am making a python library for loosely matching things in python for use in testing.

It is kind of used like this:

list_1 = ['x', 'y', 5]
list_matcher = ['x', MatchType(String | None), 5]

assert Matcher.matches(list_1, list_matcher)

dict_1 = {'x': 1,
          'y': 2,
          'z': {
            'foo': ['a', 'b', 'c'],
            'bar': [20, None, '8888'] }}
			  
dict_matcher = {'x': 1,
                'y': MatchFunc(lambda var: var>0 and var<=10),
                'z': {
                  'foo': MatchType(List[String]),
                  'bar': MatchType(Any) }}

assert Matcher.matches(dict_1, dict_matcher)

@dataclass
class Car:
    make: str
    model: str
    year: int

obj_1 = Car('Prius', 'V', 2014)
obj_matcher = Car('Prius', 'V', MatchType(Integer))

assert Matcher.matches(obj_1, obj_matcher)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment