python12306抢票代码运行缺少模块,pytest在导入时找不到模块,但代码运行正常

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

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.

解决方案

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 Extension for the ext_modules to include the Cython .pyx files, do not use distutils.extension.Extension but rather use setuptools.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 cythonize function, 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 Extension for your .pyx module, make sure the name of the Extension is identical to the name of the module (so name it 'calculateScore' and not for instance 'package.calculateScore').

delete the compiled .so file corresponding to your .pyx file and then re-run.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值