Writing Tests

Written on

Software without tests is broken by design.

Software without tests makes it hard to improve existing code and developers of untested applications tend to become pretty paranoid. If an application has automated tests, you can safely make changes and instantly know if anything breaks.

—from Flask, Good practices

How Do I Start?

  1. Know the theory (testing levels, testing types, mocking)
  2. Think in terms of: “Cover highest risk” (e.g. main feature must work => acceptance, unit, security, performance … test?)
  3. Watch yourself: What would you (or do you) do to verify the code you’ve just written or modified?
  4. Refactor your tests:
    • Mock away external dependencies (code that isn’t part of your codebase)
    • Replace your slowest test with (several) faster tests
    • Reorganize your code to allow you to remove mocks

1. Acceptance Tests, Feature Tests (Behave)

Specify tests in Gherkin language, implement them in Python. Provides a “common language” for all project members, across all project levels.

2. Front-end Tests (Selenium)

Automate interactive browser testing, mimicking user interaction on live sites (and apps).

Tests using those frameworks can be run by any test runner (e.g. pytest, behave, etc.).

3. Unit Tests (Python)

Safeguard functional units (modules, packages, “backend”) against regression.

General Recommendations

Selenium

  1. Use page objects! – Write your tests against an API of your pages, not against the HTML. (why?)

Django

  1. Don’t mock the DB / your model! – Refactor your code, so most of the code doesn’t need to talk to the DB. (why?)
  2. Don’t use fixtures for test data! – Use model factories instead. (why?)
  3. Write less view code! – Testing views is hard. Use RequestFactory or write BDD tests. (why?)
  4. One action per test method, no multi-step tests! – A failing test method must tell you what’s broken. (why?)

See Also

External Resources

comments powered by Disqus