【问题标题】:Is it a good practice to assign atributes to the tester class that will be used by other tests将属性分配给其他测试将使用的测试器类是否是一种好习惯
【发布时间】:2019-01-12 00:26:22
【问题描述】:

我正在使用 pytest 为我的 python 应用程序编写单元测试。

我正在测试的模块有许多方法,它们将按顺序调用,它们的返回值将用作其他方法的参数。简而言之,我所拥有的是这样的:

def foo_1():
    #load file and do stuff
    return bar_1

def foo_2(arg1):
    #do stuff with arg1
    return bar_2

def foo_3(arg1, arg2):
    #do stuff with arg1 and arg2
    return bar_3

x = foo_1()
y = foo_2(x)
z = foo_3(x,y)

相当基本的东西,这是我正在运行的测试:

import foo_app

class TestClass:

    def test_foo_1(self):
        self.x = foo_app.foo_1()

        #never mind the assertions
        assert 0 == self.x

    def test_foo_2(self):
        self.y = foo_app.foo_2(self.x)

        #never mind the assertions
        assert 1 == self.y

    def test_foo_3(self):
        self.z = foo_app.foo_3(self.x, self.y)

        #never mind the assertions
        assert 3 == self.z

但是,我想知道这是否是单元测试的好习惯,如果不是,那么处理这种我依赖以前方法的执行来达到我的结果的场景的最佳方法是什么?

【问题讨论】:

    标签: python unit-testing testing pytest


    【解决方案1】:

    您可以使用 yield 实现所需的行为。可用于维护执行顺序。

    def foo_1():
        #load file and do stuff
        return bar_1
    
    def foo_2(arg1):
        #do stuff with arg1
        return bar_2
    
    def foo_3(arg1, arg2):
        #do stuff with arg1 and arg2
        return bar_3
    def run():
        arg1 = foo_1()
        yield
        arg2 = foo_2(arg1)
        yield
        arg3 = foo_3(arg1,arg2)
        yield
    
    for steps in run():
        pass
    

    查看这个资源,他详细解释了它的工作原理。
    https://youtu.be/7lmCu8wz8ro?t=4635

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-09
      • 2012-03-01
      • 1970-01-01
      • 2012-09-12
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      相关资源
      最近更新 更多