【问题标题】:Running pytest with cython - how to compile cython modules in pytest?使用 cython 运行 pytest - 如何在 pytest 中编译 cython 模块?
【发布时间】:2018-01-19 06:21:27
【问题描述】:

我有一个项目组织如下:

project
├── project
│   ├── module1
│   │   ├── api.py
│   │   ├── _cpython_foo.py
│   │   └── _cython_foo.pyx
│   └── module2
├── setup.py
└── tests
    └── module1
        ├── test_cython_foo.py
        └── test_cpython_foo.py

api.py 导入 cythonized 扩展的地方:

 """api.py""""
 from _cython_foo import cython_fun

我的安装脚本正确地构建了.pyx 源,并且我能够在安装的包中使用cython_fun

import project.module1.api as module1
module1.cython_fun()    # OK

但是,pytest 抱怨它无法导入 cython 模块,因为在我调用 setup 之前编译的二进制文件还没有到位。

project/module1/api.py:2: in <module>
    from _cython_foo import cython_fun
E   ImportError: No module named _cython_foo

在 pytest 所依赖的项目目录中留下一堆预编译的二进制文件似乎是一种不好的风格,那么有没有一种传统的方法可以让 pytest 临时构建 cython 模块仅用于我的单元测试?

【问题讨论】:

  • 您可以安装pytest-runner 并调用python setup.py pytest,或者在virtualenv 中以可编辑模式安装包并从那里运行测试(python setup.py develop 甚至更好,pip install --editable project/)。
  • @hoefling 啊,pytest-runner 似乎可以满足我的需求。如果你能把你的回复写成一个简短的正式答案,我会接受。

标签: python testing cython pytest


【解决方案1】:

我知道将pytest 与 cythonized 扩展结合的两种方式:

  1. 不要直接通过pytest 调用测试;而是在安装脚本中使用就地测试命令。为此,请安装添加了pytest 命令的pytest-runner 插件:

    $ pip install pytest-runner
    

    现在您应该可以通过发出 pytest 来调用测试了

    $ python setup.py pytest
    

    然而,这种方法需要对命令行参数的传递方式进行一些更改:命令的挂件

    $ pytest --arg1 --arg2
    

    将会

    $ python setup.py pytest --addopts "--arg1 --arg2"
    
  2. 如果您想继续使用pytest 命令:在开发模式下安装项目(最好在 中)。

    (myenv) $ pip install --editable dir/
    

    其中dir/ 是包含setup.py 脚本的目录。现在扩展将被预构建,pytest 将能够解决它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2017-02-08
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多