Moar test snippets!
So usually you’re not just testing a thing does a thing, you are also testing a thing does a thing and does another thing when another thing and fails nicely when no thing.
So you either create a bazillion very similar tests or you parameterise them somehow. Here’s two ways I like.
Paramatrize (omg spelling) is a pretty neat way to add multiple cases to one test. You just add the decorator to the test, pass the different variables through and voila, many tests using one test function.
- Easy to add to existing tests with very little rework
- Don’t need to include more packages
- Messy and hard to read
- Can’t label different cases
- Inflates your test file a gazillion times
- If you want to use the same case for different tests you have to C&P the decorator around
I recently found this little package and I loved it immediately. It allows me to write one nice test and separate out my test cases into their own files. I can be really specific with each case and manipulate the test data as much as I need to in order to set up the exact situations I need to replicate. It’s an awesome tool, read more about it here
Same example as above but this time using cases:
Test Code (in test_check_code_unique.py)
Test Cases (in cases_check_code_unique.py)
So this is a super simple example, so it may not be the best way to demonstrate how handy this is. In some more complex tests I have a big dict at the start of my
cases file that I pretend is the result from a db call, which I can copy and manipulate independently for each test case. Can you imagine a result being a list with like 100 elements? How much would that suck to read using paramatrize?
And most usefully, you can name the functions whatever you like, no one cares, because you can give them a nice human-readable
@case_name. You can also do some fun things with tags, but you can read about that yourself (I don’t use them much).
- Keeps your test functions and test data separate
- You can name and tag things
- Easy to create complex data for very specific situations
- You are relying on yet another little package to do things for you (is that really a con? I couldn’t think of much else!)