17 ms·
My Python testing style guide (2017)
- tcbasche 6y agoI've been looking for something like this for ages. I'm excited to try some of this stuff out, like spec'd Mocks. I'm curious if anyone else who has been drawn in by the allure of the Mock has some strategies to avoid the footguns associated with them? (Python specifically)
- animal_spirits 6y agoWhat footguns are you looking to avoid with mocks? I've been using them for about a year now and haven't run into much issues.
- AlexCoventry 6y agoIf the mock's model of the mocked-out component is inaccurate, it reduces the relevance of the test using the mock.
- deleted 6y ago[deleted]
- nerdponx 6y agoCheck out the talk by Edwin Jung, "Mocking and Patching pitfalls": https://www.youtube.com/watch?v=Ldlz4V-UCFw https://www.youtube.com/watch?v=Ldlz4V-UCFw
- UK-Al05 6y agoI've seen things like the mock returns null for an error. But the real thing throws an exception.
- globular-toast 6y agoJust don't use them unless you have to. The two main reasons to mock are for network requests and because something is too slow. Other than that, test things for real. Do not isolate parts of your code from other parts of your code by using mocks. If your code does side effects on your own machine, like writes to the file system, let it write to a temporary directory. I linked this excellent talk in another thread recently. I'll put it here again: https://www.youtube.com/watch?v=EZ05e7EMOLM https://www.youtube.com/watch?v=EZ05e7EMOLM
- scrollaway 6y agoIndeed. And if you're mocking eg. API calls in a client library, try to have tests for the real things as well. They don't have to be part of your normal test suite, they can run only if env vars are set with the API keys needed.
- tmarice 6y agoVCR.py (https://github.com/kevin1024/vcrpy https://github.com/kevin1024/vcrpy) is a great utility for mocking APIs. It will run each request once, save the responses to YAML files, and then replay the responses every time you re-run the tests. It's also very useful for caching API responses (e.g. you have a trial account with limited number of requests). Unfortunately, if used for testing, it will not cover the case when the original API changes its interface.
- mumblemumble 6y agoThat Ian Cooper talk is just fantastic. It's perhaps best contribution to the subject of TDD anyone has produced since Kent Beck popularized the idea in the first place.
- travisjungroth 6y agoI'd really recommend this video. I had seen it years ago and just came back to it. It's about changing your architecture, one of the effects of that being changing how you need/use mock. https://www.youtube.com/watch?v=DJtef410XaM&t https://www.youtube.com/watch?v=DJtef410XaM&t
- f00_ 6y agoassert on the call_count attribute of a mock instead of trying to use methods on it like .assert_called_once_with() "a mock’s job is to say, “You got it, boss” whenever anyone calls it. It will do real work, like raising an exception, when one of its convenience methods is called, like assert_called_once_with. But it won’t do real work when you call a method that only resembles a convenience method, such as assert_called_once (no _with!)." https://engineeringblog.yelp.com/2015/02/assert_called_once-threat-or-menace.html https://engineeringblog.yelp.com/2015/02/assert_called_once-...
- alasdairnicol 6y agoThis behaviour has changed in Python 3.5 [1], and it was also backported to the mock package. When unsafe=False (the default), accessing an attribute that begins with assert will raise an error. [1]: https://docs.python.org/3/library/unittest.mock.html#the-mock-class https://docs.python.org/3/library/unittest.mock.html#the-moc...
- f00_ 6y agodo you happen to know if this is true on mock==2.0?
- alasdairnicol 6y agoYes it looks as if that functionality is in 2.0, but the list of typos isn’t as extensive as in later versions. https://mock.readthedocs.io/en/latest/changelog.html#and-earlier https://mock.readthedocs.io/en/latest/changelog.html#and-ear...
- progval 6y ago> accessing an attribute that begins with assert Or any of the names in this surprising hardcoded list of typos https://github.com/python/cpython/blob/fdb9efce6ac211f973088eef508740c3fa2bd182/Lib/unittest/mock.py#L634 https://github.com/python/cpython/blob/fdb9efce6ac211f973088...
- psing 6y agoIf you're in the serverless space, a useful addendum: https://towardsdatascience.com/how-i-write-meaningful-tests-for-aws-lambda-functions-f009f0a9c587 https://towardsdatascience.com/how-i-write-meaningful-tests-...
- MrPowers 6y agoI've found pytest to encourage tests with really long method names, examples from the post: test_refresh_failure test_refresh_with_timeout These get even longer like test_refresh_with_timeout_when_username_is_not_found for example. pytest-describe allows for a much nicer testing syntax. There's a great comparison here: https://github.com/pytest-dev/pytest-describe#why-bother https://github.com/pytest-dev/pytest-describe#why-bother TL;DR, this is nicer: def describe_my_function(): def with_default_arguments(): def with_some_other_arguments(): This isn't as nice: def test_my_function_with_default_arguments(): def test_my_function_with_some_other_arguments():
- TuringNYC 6y agoI just saw the github readme for this project. How is the describe variant different from just grouping the tests together into a module called test_describe_my_function.py and then having smaller named functions inside?
- klenwell 6y agoThis grouping convention reminds me a lot of Better Specs from the Ruby world: https://www.betterspecs.org/ https://www.betterspecs.org/ With rspec, you use the describe and context keywords. At one level, yes, it's mainly syntactical sugar. As the test-writer, the two approaches may seem interchangeable. Where I find it really helps is when I'm not the test-writer but rather I'm reviewing another developer's tests, say in PR. I find this syntax and hierarchy produces a much more coherent test suite and makes it easier for me to twig different use cases and test quality generally.
- theptip 6y agoThe readme says: > With pytest, it's possible to organize tests in a similar way with classes. However, I think classes are awkward. I don't think the convention of using camel-case names for classes fit very well when testing functions in different cases. In addition, every test function must take a "self" argument that is never used. So there's no reason to do this, aside from aesthetics. I'd recommend against doing un-Pythonic stuff like this, it makes your code harder to pick up for new engineers.
- tjpnz 6y agoWhat are people using in terms of testing frameworks now?
- globular-toast 6y agoMost of the codebases I maintain use unittest, but pytest is much better and my preferred framework.
- teddyh 6y agounittest is in the standard library; this counts for a lot.
- globular-toast 6y agoI used to use unittest for this reason, but it's pretty silly. Having extra dependencies for the tests makes no difference for end users and these days it barely makes a difference to developers.
- codethief 6y ago> Having extra dependencies for the tests What do you mean, extra dependencies? The only difference between pytest and unittest in this regard is that tests using unittest declare their dependency explicitly, using an import[0]. Most pytest tests still implicitly require pytest as a dependency, though. (Think of fixtures etc. etc.) I actually like unittest's approach here – in my book, explicit is better than implicit.
- GlennS 6y agoI believe they mean that you need to install the pytest package, whereas unittest comes with Python.
- Rendello 6y agoThis is a good talk by the core developer Raymond Hettinger [1]. He prefers pytest too. I don't do any crazy testing, but I really like property-based testing with Hypothesis, which is also mentioned. This video isn't Python but it's a great intro to property-based testing [2]. 1. https://www.youtube.com/watch?v=ARKbfWk4Xyw https://www.youtube.com/watch?v=ARKbfWk4Xyw 2. https://www.youtube.com/watch?v=AfaNEebCDos https://www.youtube.com/watch?v=AfaNEebCDos
- sambalbadjak 6y agoI'd add to that, that test should be readable. personally I prefer to use: GIVEN, WHEN, THEN as comments in the tests. Also; it's ok not to be DRY while writing tests.
- mxz3000 6y agoThe given, when, then breakdown is interesting, though I've never seen language test utilities actually enforce that structure. Maybe an interesting potential experiment (regardless of language) ? I feel like your last point is especially important. Sooooo many times have I seen over-abstracted unit tests that are unreadable and are impossible to reason about, because somebody decided that they needed to be concise (which they don't). I'd much rather tests be excessively verbose and obvious/straightforward than over abstracted. It also avoids gigantic test helper functions that have a million flags depending on small variations in desired test behaviour...
- disgruntledphd2 6y agoAs always, there are tradeoffs. Personally, I work with some incredibly (100+line) long "unit" tests and they are a nightmare to work with. Especially when the logic is repeated across multiple tests, and it's incorrect (or needs to be changed). I really, really like shorter tests with longer names, but I'd imagine there are definitely pathologies at either end.
- mumblemumble 6y ago> it's ok not to be DRY Depending on context and implementation details, I'd say DRYing tests can be anywhere from indispensable to toxic. I'm fine with creating libraries of shared functionality that tests can use, especially when it helps readability. If you've got several tests with the same precondition, having them all call a function named "givenTheUserHasLoggedIn()" in order to do the setup is a nice readability win. And, since it's a function call, it's not too difficult to pick apart if a test's preconditions diverge from the others' at a later date. What I absolutely cannot stand is using inheritance to make tests DRY. If you've got an inheritance hierarchy for handling test setup, the cost of implementing a change to the test setup requirements is O(N) where N is the hierarchy depth, with constant factors on the order of, "Welp, there goes my afternoon."
- mumblemumble 6y agoPersonally, I've come to really dislike test names like "test_refresh_failure". They tell you what component is being tested, but not what kind of behavior is expected. Which can lead to a whole lot unnecessary confusion (or bugs) when you're trying to maintain a test whose implementation is difficult to understand, or if you're not sure it's asserting the right things. It also encourages tests that do too much. If the test is named "test_refresh", well, it says right there in the name that it's a test for any old generic refresh behavior. So why not just keep dumping assertions in there? I'm much more happy with names like, "test_displays_error_message_when_refresh_times_out". Right there, you know exactly what's being verified, because it's been written in plain English. Which means you can recognize a buggy test implementation when you see it, and you know what behavior you're supposed to be restoring if the test breaks, and you are prepared to recognize an erroneously passing test, and all sorts of useful things like that.
- jxub 6y agoI think that behave (https://behave.readthedocs.io/en/stable/ https://behave.readthedocs.io/en/stable/) is more useful for testing these more real-life usecases. I tend to have a `test_my_function` in pytest tests and the more integration and functionality-related testing in the behave tests.
- BurningFrog 6y agoWe don't need to put this much responsibility on test names. If there is more to explain, write a few words in a comment.
- exdsq 6y agoYou don’t see comments in a test report though — maybe have an optional description as part of the framework for more detail along with -v
- munchbunny 6y agoI think this is one of those conventions where your team agrees on one convention, and you just try to follow it consistently. If that's looking at the test in code to find descriptive comments, great. If that's long test names, cool. Just do the same thing consistently.
- returningfory2 6y agoThe author doesn't like pytest fixtures, but personally they're one of my favorite features of pytest. Here's an example use case: I have a test suite that tests my application's interactions with the DB. In my experience, the most tedious part of these kinds of tests is setting up the initial DB state. The initial DB state will generally consist of a few populated rows in a few different tables, many linked together through foreign keys. The initial DB state varies in each test. My approach is to create a pytest fixture for each row of data I want in a test. (I'm using SQLAlchemy, so a row is 1-1 with a populated SQLAlchemy model.) If the row requires another row to exist through a foreign key constraint, the fixture for the child row will depend on the fixture for the parent. This way, if you add the child test fixture to insert the child row, pytest will automatically insert the parent row first. The fixtures ultimately form a dependency tree. Finally in a test, creating initial DB state is simple: you just add fixtures corresponding to the rows you want to exist in the test. All dependencies will be created automatically behind the scenes by pytest using the fixtures graph. (In the end I have about ~40 fixtures which are used in ~240 tests.)
- epage 6y agoI'm mixed on fixtures. One one hand, I've been impressed with how they compose and have let me do some great things. For example, I had system tests that needed hardware identifiers. I had a `conftest.py` to add CLI args for them. I then made fixtures to wrap the lookup of these. In the fixture, I marked it as Skip if the arg was missing. This was then propagated to all of the tests, only running the ones the end-user had the hardware for. On the other hand, when I need to vary the data between tests and that data is an input to something that I'd like to abstract the creation of, fixtures break down and I have to instead use a function call.
- emptysea 6y agoOne thing I've encounter with pytest fixtures is they have a tendency to balloon in size. We started out with like 50 fixtures, but now we have a conftest.py file that has `institution_1`, ..., `institution_10`. My end conclusion is that fixtures are nice for some things, like managing mocks, and clearing the databases after tests, but for data it's better to write some functions to create stuff. So instead of `def test_something(institution_with_some_flag_b)` you'd write in your test body: def test_something() -> None: institution = create_institution(some_flag="b") Also another benefit is you can click into the function whereas fixtures you have to grep.
- michaericalribo 6y agoI'm curious how others test code that operates on large datasets—eg, transformations of a dataframe, parsing complicated responses, important implementations of analytics functions. I've previously used serialized data—JSON, or joblib if there are complex types (eg, numpy)—but these seem pretty brittle...