为 Python C 扩展实施单元测试

Implementing unit tests for a Python C Extension

所以,我有一个 repo 来构建一个 python C 扩展,如下所示:

setup.py
demo.c
MANIFEST.in

C文件内容为:

#include <Python.h>

static PyObject* print_message(PyObject* self, PyObject* args)
{
    const char* str_arg;
    if(!PyArg_ParseTuple(args, "s", &str_arg)) {
        puts("Could not parse the python arg!");
        return NULL;
    }
#ifdef USE_PRINTER
    printf("printer %s\n", str_arg);
#else
    printf("msg %s\n", str_arg);
#endif
    // This can also be done with Py_RETURN_NONE
    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef myMethods[] = {
    { "print_message", print_message, METH_VARARGS, "Prints a called string" },
    { NULL, NULL, 0, NULL }
};

// Our Module Definition struct
static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,
    "DemoPackage",
    "A demo module for python c extensions",
    -1,
    myMethods
};

// Initializes our module using our above struct
PyMODINIT_FUNC PyInit_DemoPackage(void)
{
    return PyModule_Create(&myModule);
}

在我的 setup.py 中,我有以下代码:

from distutils.core import setup, Extension

module1 = Extension('DemoPackage',
                    define_macros = [('USE_PRINTER', '1')],
                    include_dirs = ['include'],
                    sources = ['src/demo.c'])

setup (name = 'DemoPackage',
       version = '1.0',
       description = 'This is a demo package',
       author = '<first> <last>',
       author_email = 'person@site.com',
       url = 'https://docs.python.org/extending/building',
       long_description = open('README.md').read(),
       ext_modules = [module1])

我的问题是,如果我可以使用以下命令构建和安装包:

$ python setup.py 构建 $ python setup.py 安装

如何在C扩展的场景中加入或编写单元测试?我正在寻找 运行 与 setup.py 结合的单元测试,类似于 cmake 的测试工作方式。

我是如何解决单元测试问题的 Python 用 C 编写的扩展模块代码是在 Python 中为 pytest but to then embed the Python interpreter in a separate C test runner which uses Check 编写单元测试以包装对pytest。这可能看起来有点傻(老实说对我来说确实如此),但由于 C 代码可能会泄漏内存并导致发出各种讨厌的信号,因此使用 Check 运行ner 运行s 将所有内容放在一个单独的地址 space 所以测试 运行ner 可以捕获任何信号并(希望)说出一些关于它们的有意义的东西而不是我只是看到 Python 解释器崩溃。我会说进行单元测试 C 扩展代码的方法是构建扩展 inplace,即使用 python3 setup.py build_ext --inplace 来放置共享对象(我在 Linux) 在与 demo.c 文件(或源文件夹)相同的目录中,然后您可以使用您想要的任何内容进行单元测试。我个人使用 make 并且我的测试构建目标 运行ner 依赖于成功构建的 C 扩展。

不幸的是,还没有人回答这个问题;我实际上希望有人能有更好的方法来解决这个确切的问题。如果您有兴趣做类似的事情,这里是检查测试 运行ner 的示例代码和相关的 Makefile 配方来构建 运行ner.

/* check/pytest_suite.h */

#ifndef PYTEST_SUITE_H
#define PYTEST_SUITE_H

#include <check.h>

Suite *pytest_suite();

#endif /* PYTEST_SUITE_H */
/* check/pytest_suite.c */

#define PY_SSIZE_T_CLEAN
#include "Python.h"

#include <stdio.h>
#include <check.h>
#include "pytest_suite.h"

START_TEST(print_stuff)
{
  // initialize interpreter, load pytest main and run (relies on pytest.ini)
  Py_Initialize();
  PyRun_SimpleString("from pytest import main\nmain()\n");
  // required finalization function; if something went wrong, exit immediately
  if (Py_FinalizeEx() < 0) {
    // __func__ only defined in C99+
    fprintf(stderr, "error: %s: Py_FinalizeEx error\n", __func__);
    exit(120);
  }
}
END_TEST

Suite *pytest_suite() {
  // create suite called pytest_suite + add test case named core
  Suite *suite = suite_create("pytest_suite");
  TCase *tc_core = tcase_create("core");
  // register case together with test func, add to suite, and return suite
  tcase_add_test(tc_core, print_stuff);
  suite_add_tcase(suite, tc_core);
  return suite;
}
/* check/runner.c */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <check.h>

#include "pytest_suite.h"

int main(int argc, char **argv) {
  // instantiate our test suite. note this does not have to be freed!
  Suite *suite = pytest_suite();
  // create our suite runner and run all tests (CK_ENV -> set CK_VERBOSITY and
  // if not set, default to CK_NORMAL, i.e. only show failed)
  SRunner *runner = srunner_create(suite);
  srunner_run_all(runner, CK_ENV);
  // get number of failed tests and free runner
  int n_failed = srunner_ntests_failed(runner);
  srunner_free(runner);
  // succeed/fail depending on value of number of failed cases
  return (n_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
# Makefile (GNU make)

CC             = gcc
PYTHON        ?= python3
# dependencies for test running code
CHECK_DEPS     = $(wildcard check/*.c)
# use python3-config to get python compiler and linker flags for use when
# linking python into external C code (our test runner)
PY_CFLAGS     ?= -fPIE $(shell python3-config --cflags)
# --embed is required on ubuntu or -lpythonx.y is omitted by --ldflags
PY_LDFLAGS    ?= $(shell python3-config --embed --ldflags)
# linker flags specifically for compiling the test runner (libcheck)
CHECK_LDFLAGS  = $(PY_LDFLAGS) -lcheck

# build C extension module inplace. change dependencies as needed.
inplace: demo.c
    @$(PYTHON) setup.py build_ext --inplace

# build test runner and run unit tests using check
check: $(CHECK_DEPS) inplace
    @$(CC) $(PY_CFLAGS) -o runner $(CHECK_DEPS) $(CHECK_LDFLAGS)
    @./runner

当然,要使其正常工作,您需要在系统上安装 Check 和 GNU Make。我正在使用 WSL Ubuntu 18.04; make 随发行版一起提供,我使用他们的 latest release 从头开始​​构建 Check。使用此设置,当我执行 make check 时,只要更新 demo.ctouched,就会调用 make inplace,并且构建我的测试 运行ner 并且 运行.

希望这至少能给你一些新想法。