Are there any guidelines for writing test-friendly Python code?
What I believe:
Any other suggestions?
It often makes sense to write the test first and then write as much code as needed to allow the test to pass. Doing this moves towards a practice known as Test-Driven Development (TDD). Bluefruit uses a lot of TDD because it helps us to build the right product without waste and redundancies.
Good unit tests are well structured Arrange: Setup the prerequisites for your test. Create objects, prepare inputs and configure mocked interfaces. Act: Perform the actual work of the test, typically by calling a function. Assert: Verify that the unit under test did what you expected.
The best tip I can give you to write test friendly code is to write the tests first. Then write the production code (TDD). Uncle Bob devised three simple rules to write TDD:
- You are not allowed to write any production code unless it is to make a failing unit test pass.
- You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
- You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
Especially this quote should sink in:
If you think about this you will realize that you simply cannot write very much code at all without compiling and executing something. Indeed, this is really the point.
Also read "Writing Testable Code" from google's testing expert(are for java, but also apply to python for large parts). You should also download/read the complete PDF on that page. But a quick recap:
- Constructor does Real Work
- Digging into Collaborators
- Brittle Global State & Singletons
- Class Does Too Much
Write methods that don't rely on other models or resources - if they need to access them, they should be passed in to the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With