Arturo
Arturo

Reputation: 171

How to put a module in a test harness with pytest?

let's say that I have a file called boop.py

that reads:

import module_a
import sys

def boop(value):
    val = module_a.boop_it(value)
    # ...
    return val

My questions are:

Note that this is all legacy code, that already exists and has years of history

Upvotes: 0

Views: 668

Answers (1)

Dirk Herrmann
Dirk Herrmann

Reputation: 5939

To answer your second question "Is it necessary to isolate it entirely?": This depends. Even if you are doing unit-testing, you typically do not have to isolate your code from all dependencies. For example, you would not isolate your code from math.sin(). I would even say, the creation of test doubles should be avoided except there is a reason. In practice, however, often enough there is a reason.

Here are some criteria that can help you decide for your module_a whether the dependency is troubling you when unit-testing. They all relate to the properties of the depended-on-component ("DOC", in your case the module_a) including its transitive dependencies and on your testing goals:

  • Can you bring the DOC into all desired states / can you ensure that with the DOC you can actually execute all interesting test scenarios? If not, better isolate, so you can test your code in all desired ways.
  • Does calling the DOC cause any non-derministic behaviour (date/time, randomness, network connections)? Then better isolate your code to make the tests deterministic.
  • Does calling the DOC cause unacceptably long test execution? If so, isolate to ensure acceptable test execution times.
  • Has the DOC stability (maturity) issues that make the tests unreliable with respect to your component, or, even worse, is the DOC not even available yet (does not apply in your specific example)? If so, you better isolate (or even simply have to) just to get your tests executable and deliver trustworthy results about your own code.

But, even if the criteria above indicate that the dependency is troubling you: Keep in mind that some re-design of the code may be preferrable to creating test doubles. For example, separating computations from interactions by putting each into different functions can save you from some mocking: You test the computations with unit-testing and the interactions with integration-testing.

Upvotes: 1

Related Questions