Reputation: 530
I have a pytest script that has roughly 20 different test. Each test collects data and stores that data in specified file-paths. Each file-path is individually defined within each test. For example:
def test_1():
gfx = open('path/to/file_1')
do something
def test_2():
focus = open('path/to/file_2')
do something
def test_3():
data = open('path/to_1/file_3')
do something
The problem is, I am in the process of transferring these scripts to a new server. Obviously, this server now has different directories that do not match my old defined ones.
My question is, what is the most Pythonic way to introduce file-paths for pytest? Would it be best to have variables defined that are easily modified? Or is there a better way?
If more information or clarity is needed please let me know.
Upvotes: 1
Views: 587
Reputation: 71
It might be obvious, but in general to avoid such problems, tests should include the data that is needed for them. If the data (file) is big, perhaps you can create a minimal example for your test? That would be the cleanest solution.
If that is not possible, e.g. the minimal data (file) is still too big and is stored separately, so the exact location of the path could differ from machine to machine. I would use an environment variable, where the base path - as you already suggested in your comment - is set.
import os
try:
test_data_base_path = os.environ['test_data_base_path']
except KeyError:
print('Could not get environment variable "test_data_base_path". '
'This is needed for the tests!')
raise
def test_1():
gfx = open(os.path.join(test_data_base_path, 'subfolder', 'to', 'file_1'))
# do something
def test_2():
focus = open(os.path.join(test_data_base_path, 'subfolder', 'to', 'file_2'))
# do something
# ...
How to set the test_data_base_path
environment variable depends on how you run your tests. If you need it globally, you can do that via your OS. If you start your tests via an IDE, you can usually set them directly there.
Upvotes: 2