Skip to content

No-Conditionals-In-Tests

Sourcery rule id: no-conditionals-in-tests

Description

Avoid conditionals in tests.

Match

def test_something():
    some_code()
    if nr < 42:
        verify_small_number(nr)
    else:
        verify_big_number(nr)

Explanation

Avoid complex code, like conditionals, in test functions.

Google's software engineering guidelines says: "Clear tests are trivially correct upon inspection" To reach that avoid complex code in tests: * loops * conditionals

Some ways to fix this:

  • Use parametrized tests to get rid of the loop.
  • Move the complex logic into helpers.
  • Move the complex part into pytest fixtures.

Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / Don't Put Logic in Tests