问题
I have a simple python module (let's call it M1) which is standalone (the only import is to collections
), inside a package containing ugliness. Part of the ugliness is in the package's __init__.py
file. But M1 is nice and clean, and contains some test functions for use with py.test.
Now, I would like to test M1 and ignore all the ugliness. But py.test wants to run __init__.py
-- is there any way I can prevent this? I really can't fix the __init__.py
file at this time, and I want to keep my test functions contained right alongside the M1 module contents itself.
I've already read this SO question: `py.test` and `__init__.py` files which explains the issue but offers no solution.
my __init__.py
file looks something like this; it's just promoting items into package scope:
from .M1 import CleanThing1, CleanThing2
from .Evil1 import UglyThing1, UglyThing2
and the problem is that the Evil1 module requires some PYTHONPATH hackery to execute properly, and when I run
py.test mymodule/M1.py
it fails because of the Evil1 module. But I just want to test the M1 module right now.
回答1:
You can make the __init__.py
file aware of py.test as described here.
So basically create a mymodule/conftest.py
file with the following content
def pytest_configure(config):
import sys
sys._called_from_test = True
def pytest_unconfigure(config):
del sys._called_from_test
and in the __init__.py
file simply check if you are inside the py.test session like
import sys
if hasattr(sys, '_called_from_test'):
# called from within a test run
pass
else:
# failing imports
from .M1 import CleanThing1, CleanThing2
from .Evil1 import UglyThing1, UglyThing2
This way I could run py.test mymodule/M1.py
without the import errors.
The package structure now looks like (I hope that resembles your structure)
package
|
|- __init__.py
|- mymodule/
|- M1.py
|- conftest.py
回答2:
It's not py.test that wants to run __init.py__
, but the Python interpreter. The rule that __init__.py
is executed is part of the Python language definition, and any way around it will necessarily be a hack.
In this case, I suggest that you definte a stubbed Evil1
module of your own, and let M1
import that one instead.
来源:https://stackoverflow.com/questions/27747169/standalone-py-test-ignore-init-py-files