问题
The goal is to use the pytest unit test framework for a Python3 project that uses Cython. This is not a plug-and-play thing, because pytest by default is not able to import the Cython modules. Namely, I get the following error when importing from a Cython .pyx module, in my case named 'calculateScore':
package/mainmodule.py:5: in <module>
from calculateScore import some_functions
E ImportError: No module named 'calculateScore'
This problem occurs both when using the pytest-runner as well as the pytest-cython approach. Strangely enough, the code runs just fine as a python application when you're not trying to test it using pytest.
Changing the import style to import calculateScore or import package.calculateScore does not help.
回答1:
I have no idea why this is happening, but for me the easiest solution was to use the pytest-cython approach and change one or multiple things listed below in the package's setup.py file:
- when defining your
Extensionfor theext_modulesto include the Cython.pyxfiles, do not usedistutils.extension.Extensionbut rather usesetuptools.Extension
The reason why I manually create an Extension instead of using the Cython.Build.cythonize function, is not important here. But please note that for the pytest-runner approach:
- do not use the
cythonizefunction, but create the Extension manually
After writing this post I cannot even seem to reproduce the problem using pytest-cython anymore, which suggests that maybe something else is the cause of the problem. An additional thing you could try is to make sure that:
when manually creating an
Extensionfor your.pyxmodule, make sure the name of theExtensionis identical to the name of the module (so name it 'calculateScore' and not for instance 'package.calculateScore').delete the compiled
.sofile corresponding to your.pyxfile and then re-run.
来源:https://stackoverflow.com/questions/49068162/pytest-cannot-find-module-on-import-but-code-runs-just-fine