【问题标题】:Is pytest tmpdir only associated with function parameters?pytest tmpdir 是否仅与函数参数相关联?
【发布时间】:2018-09-20 21:26:35
【问题描述】:

有没有办法使用 pytest fixture tmrdir 编写类的测试方法?在文档中,它指定它可以与函数一起使用。 https://docs.pytest.org/en/latest/tmpdir.html

如果有一种方法可以为类中的测试方法传递 tmpdir 参数,您能否分享一个示例?

我尝试了以下方法,但出现错误,例如: "

test_method() 只接受 2 个参数(给定 1 个)"

我的代码:

import pytest

class class_test(TestCase):

    def test_method(self,tmpdir):
        # code

请帮忙。

【问题讨论】:

  • 您不能在unittest 测试类中将fixture 作为测试参数传递,只能在测试函数中传递。查看Using autouse fixtures and accessing other fixtures 以获取通过自动使用在unittest 测试类中应用fixture 的示例,它恰好是tmpdir 用法。
  • 感谢您的回复@hoefling。我按原样使用了来自docs.pytest.org/en/latest/… 的第一个sn-p 中的代码。即使在那之后,它似乎也不起作用。我还能错过什么?

标签: python pytest


【解决方案1】:

如文档 here 中所述,您必须在 initdir 函数中添加 tmpdir 参数。 这样 initdir 夹具函数将用于类的所有方法

例子:

import unittest
import pytest

   class Test_Temp(unittest.TestCase):
      @pytest.fixture(autouse=True)
      def initdir(self, tmpdir):
          tmpdir.chdir()  # change to pytest-provided temporary directory
          tmpdir.join("samplefile.ini").write("# testdata")

      def test_file content(self):
          with open('samplefile.ini', 'r') as f:
             assert f.read() == '# testdata'   //True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2012-06-14
    • 1970-01-01
    • 2012-04-25
    相关资源
    最近更新 更多