如何使用pytest将模块放入测试工具中? [英] How to put a module in a test harness with pytest?

查看:36
本文介绍了如何使用pytest将模块放入测试工具中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 boop.py

内容如下:

import module_a
import sys

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

我的问题是:

  • 当我为此做测试时,我怎样才能让 module_a 成为一个虚拟模块?我知道我需要隔离依赖项.我只是不明白它的机制

  • 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

推荐答案

回答你的第二个问题是否有必要完全隔离它?":这取决于.即使您正在进行单元测试,您通常也不必将您的代码与所有依赖项隔离.例如,您不会将代码与 math.sin() 隔离.我什至会说,除非有原因,否则应该避免创建测试替身.然而,在实践中,往往是有原因的.

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.

这里有一些标准可以帮助您决定 module_a 的依赖项是否在单元测试时困扰您.它们都与依赖组件(DOC",在您的情况下为 module_a)的属性有关,包括其传递依赖项和您的测试目标:

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:

  • 您能否将 DOC 带入所有所需的状态/您能否确保通过 DOC,您实际上可以执行所有有趣的测试场景?如果没有,请更好地隔离,以便您可以以所有所需的方式测试您的代码.
  • 调用 DOC 是否会导致任何非极端行为(日期/时间、随机性、网络连接)?然后更好地隔离您的代码,使测试具有确定性.
  • 调用 DOC 是否会导致不可接受的长时间测试执行?如果是,请隔离以确保可接受的测试执行时间.
  • 是否存在 DOC 稳定性(成熟度)问题导致测试对您的组件不可靠,或者更糟糕的是,DOC 是否尚不可用(不适用于您的特定示例)?如果是这样,您最好隔离(或者甚至只是必须),以便让您的测试可执行并提供有关您自己代码的可靠结果.

但是,即使上述标准表明依赖关系困扰着您:请记住,对代码进行一些重新设计可能比创建测试替身更可取.例如,通过将每个函数放入不同的函数来将计算与交互分开可以避免一些模拟:您使用单元测试测试计算,并使用集成测试测试交互.

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.

这篇关于如何使用pytest将模块放入测试工具中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆