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

半城伤御伤魂 提交于 2019-12-14 03:11:04

问题


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:

  • when I'm doing the tests for this, how can I make module_a be a dummy module? I understand I need to isolate the dependencies. I just don't understand the mechanics of it

  • Is it necessary to isolate it entirely? If I don't, will it come to bite me?

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


回答1:


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.



来源:https://stackoverflow.com/questions/54564969/how-to-put-a-module-in-a-test-harness-with-pytest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!