Reputation: 126
I'm new to Pytest and would like to test a function that deletes files from a directory in one of two formats: PDF or JPG. Fortunately, I was able to test the function when passing the specified format, and it works great, but I'm not sure how to test it with both formats.
The following code shows how the function is tested to delete jpg files; if I want to test it on pdf files, I'll need to alter the extension variable in the exe function.
Is there anyone who can assist me in changing this?
@pytest.fixture()
def ext():
extention = 'jpg' # can be changed to pdf or jpg
return extension
def test_remove_files(ext):
remove_files(ext)
time.sleep(3)
assert len(image_in_folder_OS(ext)) == 0
So I need now two functions as shown below but how to modify the ext function so it can satisfy both functions with their formats?
def test_remove_files_pdf(ext):
remove_files(ext)
time.sleep(3)
assert len(image_in_folder_OS(ext)) == 0
def test_remove_files_jpg(ext):
remove_files(ext)
time.sleep(3)
assert len(image_in_folder_OS(ext)) == 0
Upvotes: 2
Views: 375
Reputation: 50864
You can use parametrized test, this will create two tests, each one with one extension as parameter
@pytest.mark.parametrize('ext', ['jpg', 'pdf'])
def test_remove_files(ext):
remove_files(ext)
time.sleep(3)
assert len(image_in_folder_OS(ext)) == 0
If you need to do something with extension before sending it to the test you can build a function and use it as parameters
def data_source():
for ext in ['jpg', 'pdf']:
# do something with ext
yield ext
@pytest.mark.parametrize('ext', data_source())
def test_remove_files(ext):
remove_files(ext)
time.sleep(3)
assert len(image_in_folder_OS(ext)) == 0
Upvotes: 1