【问题标题】:How do I run a doctest from Cython?如何从 Cython 运行 doctest?
【发布时间】:2020-10-03 18:03:25
【问题描述】:

设置

  1. 假设我有一个脚本fib.py。里面有一些文档测试。

    def fib(n):
        """Return the nth number in the Fibonacci sequence.
    
        >>> fib(0)
        0.0
        >>> fib(1)
        1.0
        >>> fib(4)
        3.0
        >>> fib(7)
        13.0
        """
        a, b = 0.0, 1.0
        for i in range(n):
            a, b = a + b, a
        return a
    
    if __name__ == "__main__":
        import doctest
        doctest.testmod()
    

    一切正常,我可以确认测试正在运行 通过检查python3 fib.py -v 的输出。

  2. 好的,现在我要把它翻译成 Cython,而且我什至会删除 if __name__ == '__main__' 有条件的。 让我们调用我们的 Cython 文件fib.pyx

    #cython: language_level=3
    
    def fib(int n):
        """Return the nth number in the Fibonacci sequence.
    
        >>> fib(0)
        0.0
        >>> fib(1)
        1.0
        >>> fib(4)
        3.0
        >>> fib(7)
        13.0
        """
        cdef int i
        cdef double a=0.0, b=1.0
        for i in range(n):
            a, b = a + b, a
        return a
    
    import doctest
    doctest.testmod()
    
  3. 当然,我们需要编译我们的 Cython。对我来说是

    cython --embed fib.pyx
    gcc $(python-config --cflags) $(python-config --ldflags) fib.c
    

    这会产生a.out

  4. 如果我尝试 ./a.out -v 我会得到 . . .

    1 items had no tests:
        __main__
    0 tests in 1 items.
    0 passed and 0 failed.
    Test passed.
    

我的测试结果如何?

(可能)有用的链接。

【问题讨论】:

  • 你能依靠pytest 来运行文档测试吗?
  • 只要文档测试运行就可以。我尝试通过pip install pytest && pip install pytest-cython 安装它。根据帮助页面,我可以运行 pytest --doctest-cython 来运行所有 doctest,但它说要运行 0 个测试。

标签: python c cython doctest


【解决方案1】:

好的,这里有一些问题。 . .

首先我并没有正确编译。最终结果应该是 MacOs/Linux 系统上的 .so 文件和 linux 上的 .pyd 文件。

构建 Cython 模块

你可以通过写一个setup.py文件来快速编译

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize('fib.pyx'))

取决于您的操作系统和运行的 python 版本

python setup.py build_ext --inplace

会产生类似fib.cpython-37m-x86_64-linux-gnu.so的东西

更多信息请查看相关Cython docs

安装 pytest 模块

pip install pytest
pip install pytest-cython

运行测试

从您编译的 Cython 所在的目录运行。 . .

pytest --doctest-cython -v

-v 当然是verbose 并提供额外的输出。

pytest --help | grep cython我们可以看到这个命令在做什么。

cython:
  --doctest-cython      run doctests in all .so and .pyd modules
  --cython-ignore-import-errors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多