简体   繁体   中英

Is pytest tmpdir only associated with function parameters?

Is there a way to write test methods of a class using pytest fixture tmrdir? In the documentation, it specifies that it can be used with a function. https://docs.pytest.org/en/latest/tmpdir.html

If there is a way to pass tmpdir parameter for test methods in a class, could you please share an example?

I have tried the following thing, but I am getting an error such as: "

test_method() takes exactly 2 arguments (1 given)"

My code:

import pytest

class class_test(TestCase):

    def test_method(self,tmpdir):
        # code

Please help.

As written in the documentation here you have to add the tmpdir parameter on the initdir function. In this way the initdir fixture function will be used for all methods of the class

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM