Pytest: Hard-coded path - manually replace attribute
Because we are in Python, a dynamic language, we can access and replace the content of the data_file variable in the app module. This is sometimes called Monkey Patching. It works. Partially.
import app
def test_app_1():
app.data_file = 'test_1.json' # manually overwrite
res = app.do_something() # it is now test_1.json
...
def test_app_2():
res = app.do_something() # it is still test_1.json
...
We set the path in one of the test-functions, but it will be set in both.
pytest -v -s test_app_manually.py
test_1.json
.test_1.json
.
2 passed in 0.08s
Run test 1, we see the path we set:
pytest -v -s test_app_manually.py::test_app_1
test_1.json
.
1 passed in 0.07s
Run test 2, we see a the original path:
pytest -v -s test_app_manually.py::test_app_2
/corporate/fixed/path/data.json
.
1 passed in 0.07s