如何在py.test中跨测试累积状态 [英] How to accumulate state across tests in py.test

查看:33
本文介绍了如何在py.test中跨测试累积状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个与这些类似的项目和测试.

I currently have a project and tests similar to these.

class mylib:
    @classmethod
    def get_a(cls):
        return 'a'

    @classmethod
    def convert_a_to_b(cls, a):
        return 'b'

    @classmethod
    def works_with(cls, a, b):
        return True

class TestMyStuff(object):
    def test_first(self):
        self.a = mylib.get_a()

    def test_conversion(self):
        self.b = mylib.convert_a_to_b(self.a)

    def test_a_works_with_b(self):
        assert mylib.works_with(self.a, self.b)

使用 py.test 0.9.2,这些测试(或类似的)通过.使用更高版本的 py.test,test_conversion 和 test_a_works_with_b 失败,并显示TestMyStuff 没有属性 a".

With py.test 0.9.2, these tests (or similar ones) pass. With later versions of py.test, test_conversion and test_a_works_with_b fail with 'TestMyStuff has no attribute a'.

我猜这是因为在 py.test 的后续版本中,会为每个测试的方法创建一个单独的 TestMyStuff 实例.

I am guessing this is because with later builds of py.test, a separate instance of TestMyStuff is created for each method that is tested.

编写这些测试的正确方法是什么,以便可以为序列中的每个步骤给出结果,但可以(必须)使用先前(成功)测试的状态来执行后续测试?

What is the proper way to write these tests such that results can be given for each of the steps in the sequence, but the state from a previous (successful) test can (must) be used to perform subsequent tests?

推荐答案

良好的单元测试实践是避免跨测试积累状态.大多数单元测试框架不遗余力地防止您积累状态.原因是您希望每个测试都独立存在.这让您可以运行测试的任意子集,并确保您的系统在每次测试时都处于干净状态.

Good unit test practice is to avoid state accumulated across tests. Most unit test frameworks go to great lengths to prevent you from accumulating state. The reason is that you want each test to stand on its own. This lets you run arbitrary subsets of your tests, and ensures that your system is in a clean state for each test.

这篇关于如何在py.test中跨测试累积状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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