首页 > 解决方案 > CYTHON:为 pyx 文件生成覆盖率

问题描述

我正在尝试为 cython 模块生成代码覆盖率报告,并面临问题。

我有一个简单的 C++ 代码:apple.h 和apple.cpp文件。cpp 文件很简单:

using namespace std;
namespace mango {
    apple::apple(int key) {
            _key = key;
    };
    int apple::execute()
    {
            return _key*_key;
    };
}

我在“ cyApple.pyx ”中为此编写了一个基本的 cython 代码:

# cython: linetrace=True
from libcpp.list cimport list as clist
from libcpp.string cimport string
from libc.stdlib cimport malloc

cdef extern from "apple.h" namespace "mango" :
    cdef cppclass apple:
            apple(int)
            int execute()
cdef class pyApple:
    cdef apple* aa
    def __init__(self, number):
            self.aa = new apple(number)

    def  getSquare(self):
            return self.aa.execute()

我的setup.py文件:

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

compiler_directives = {}
define_macros = []

compiler_directives['profile'] = True
compiler_directives['linetrace'] = True
define_macros.append(('CYTHON_TRACE', '1'))

setup(ext_modules = cythonize(Extension(
       "cyApple",
       sources=["cyApple.pyx", "apple.cpp"],
       define_macros=define_macros,
       language="c++",
  ), compiler_directives=compiler_directives))

这会生成一个适当的库cyApple.so。我还编写了一个简单的appletest.py文件来运行测试用例:

import cyApple, unittest
class APPLETests(unittest.TestCase):
    def test1(self):
            temp = 5
            apple1 = cyApple.pyApple(temp)
            self.assertEqual(25, apple1.getSquare())
suite = unittest.TestLoader().loadTestsFromTestCase(APPLETests)
unittest.TextTestRunner(verbosity=3).run(suite)

测试工作正常。 问题是我需要为我的 cyApple.pyx 文件获取代码覆盖率

当我运行“coverage report -m”时,我得到的只有我的测试文件而不是 pyx 文件的错误和覆盖率。

cyApple.pyx   NotPython: Couldn't parse '/home/final/cyApple.pyx' as Python source: 'invalid syntax' at line 2
Name           Stmts   Miss  Cover   Missing
--------------------------------------------
appletest.py       8      1    88%   9

我试图在网上查找并获得一些帮助,所以我添加了
.coveragerc文件,其内容为:

[run]
plugins = Cython.Coverage

在运行“ coverage run appletest.py ”时出现错误:

...
... 
...
ImportError: No module named Coverage

我想为我的 pyx 文件生成简单的代码覆盖率报告。我怎样才能以简单的方式做到这一点?

我重新安装了 Cython-0.28.3。现在在运行“coverage run appletest.py”时出现错误:

test1 (__main__.APPLETests) ... Segmentation fault (core dumped)

这是我的apple.h文件:

#include<iostream>
namespace mango {
class apple {
public:

    apple(int key);
    int execute();
private:
    int _key;
};
}

标签: code-coveragecython

解决方案


您必须更新 Cython。该文档指出:

从 Cython 0.23 开始,线跟踪(见上文)还支持使用 coverage.py 工具进行覆盖报告。


推荐阅读