I have a unit tests class that is testing what is inside a txt file. I am using the tmpdir fixture with pytest. This is my current class:
from objects.TicketCounter import TicketCounter
from objects.ConfigReader import ConfigReader
import os
import pytest
class TestTicketCounter():
# @pytest.fixture(scope="module") #<---Could I use this instead of passing tmpdir each time?
# def my_filepath(self, tmpdir):
# return tmpdir.mkdir("sub").join("testCurrentTicketCount.txt")
def test_createNewTicketCountFile(self, tmpdir):
x = tmpdir.mkdir("sub").join("testCurrentTicketCount.txt") #<----Repeated
ticketCounter = TicketCounter(x)
assert os.path.getsize(x) > 0
def test_addOneTicketCounter(self, tmpdir):
x = tmpdir.mkdir("sub").join("testCurrentTicketCount.txt") #<----Repeated
ticketCounter = TicketCounter(x)
beforeCount = int(ticketCounter.readTicketCountFromFile())
ticketCounter.addOneTicketCounter()
afterCount = int(ticketCounter.readTicketCountFromFile())
assert beforeCount + 1 == afterCount
def test_readTicketCountFromFile(self, tmpdir):
x = tmpdir.mkdir("sub").join("testCurrentTicketCount.txt") #<----Repeated
ticketCounter = TicketCounter(x)
print(ticketCounter.readTicketCountFromFile())
assert int(ticketCounter.readTicketCountFromFile()) >= 0
I would like to get rid of the repeated code and pass in the same path each time with the fixture that I commented out, my_filepath. When I try to use the my_parser pytest fixture, I am getting an error, saying:
ScopeMismatch: You tried to access the 'function' scoped fixture 'tmpdir' with a 'module' scoped request object, involved factories
unit_tests\test_TicketCounter.py:12:
So you are not able to use tmpdir with a pytest fixture? Is it because tmpdir is a fixture? Any thoughts on how I could cut out the repeated code and use a function or fixture to pass the path?
As the error message says, tmpdir
is a function based fixture, e.g. it creates a new temp dir for each test, and deletes it after the test. Therefore you cannot use it in a module scoped fixture, that is instantiated only once after module load. If you could do that, your temp dir would be removed after the first test, and you would not be able to access it in the next test.
In your current code, the tmpdir
fixture is used as a function scoped fixture, so a new directory is created for each test - what is usually wanted. You can use your fixture without problems if you remove the module scope:
@pytest.fixture
def my_filepath(self, tmpdir):
return tmpdir.mkdir("sub").join("testCurrentTicketCount.txt")
If you want to use the same temp dir in each test for some reason, you cannot use the tmpdir
fixture. In this case you just can create your own tmp dir, for example:
import os
import tempfile
import shutil
@pytest.fixture(scope="module")
def my_filepath(self):
tmpdir = tempfile.mkdtemp()
subdir = os.path.join(tmpdir, "sub")
os.mkdir(subdir)
yield os.path.join(subdir, "testCurrentTicketCount.txt")
shutil.rmtree(tmpdir)