【问题标题】:Is there any way to use the same fixture multiple times in a function with pytest?有没有办法在 pytest 的函数中多次使用同一个夹具?
【发布时间】:2017-05-22 14:16:17
【问题描述】:

这样

@pytest.fixture
def myfixture():
   # creates a complex object

def test_compare(myfixture,myfixture):
   #compares

有没有办法知道我正在制作哪个灯具? 生成的对象不同

谢谢

【问题讨论】:

    标签: python python-2.7 pytest fixtures fixture


    【解决方案1】:

    您正在寻找工厂模式https://docs.pytest.org/en/latest/fixture.html#factories-as-fixtures

    这是关于夹具工厂优势的问题Why would a pytest factory as fixture be used over a factory function?

    回答你的问题

    @pytest.fixture
    def myfixture():
       def _make_fixture():
           # creates a complex object
       return _make_fixture
    
    def test_compare(myfixture):
        data1 = myfixture()
        data2 = myfixture()
        #compares
    

    【讨论】:

      【解决方案2】:

      为什么要比较夹具返回的对象?固定装置不应该如此。

      根据文档,

      测试夹具的目的是提供一个固定的基线,在该基线上测试可以可靠且重复地执行。

      如果要比较返回的对象,只需将其作为函数,而不是作为fixture.Like。

      def myfixture():
         # creates a complex object
      
      def test_compare():
         a=myfixture()
         b=myfixture()
         #compare a and b
      

      【讨论】:

        猜你喜欢
        • 2016-07-06
        • 1970-01-01
        • 1970-01-01
        • 2012-03-08
        • 2017-02-11
        • 1970-01-01
        • 1970-01-01
        • 2021-06-29
        • 1970-01-01
        相关资源
        最近更新 更多