I have the following Python 2.7 simplified project structure:
project/
├── libs/
| └── zipfile.py
├── tests/
| ├── __init__.py
| └── test_hello.py
├── hello.py
└── main.py
I want this project to use the patched version of one of Python built-in modules (which in this example is zipfile
) located in libs
. Note that this is an external requirement, and I cannot change the project structure.
Below are the simplified implementation of each file:
libs/zipfile.py
def is_zipfile(filename):
return "Patched zipfile called"
tests/test_hello.py
from hello import hello
def test_hello():
assert hello() == "Patched zipfile called"
hello.py
import os
import sys
libs_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "libs"))
if libs_path not in sys.path:
sys.path.insert(1, libs_path)
import zipfile
def hello():
print(zipfile.__file__) # to check which zipfile module is imported
result = zipfile.is_zipfile("some_path")
return result
main.py
from hello import hello
def main():
print(hello())
if __name__ == "__main__":
main()
When running the program directly (python main.py
), I got the expected result:
/home/project/libs/zipfile.pyc
Patched zipfile called
However, when running pytest with project
as the working directory (pytest -s
), it failed:
/usr/lib/python2.7/zipfile.pyc
================================== FAILURES ===================================
_________________________________ test_hello __________________________________
def test_hello():
> assert hello() == "Patched zipfile called"
E assert False == 'Patched zipfile called'
E + where False = hello()
tests/test_hello.py:4: AssertionError
========================== 1 failed in 0.13 seconds ===========================
I've tried a couple solutions presented in this SO post, such as running python -m pytest
, but none has worked for me. Is there a way to successfully run this test in a non-hacky way?