在 Cython 中创建 C 和 Pytest 之间的接口

问题描述 投票:0回答:0
  1. 所以我有 Cython 文件 [.pyx 和 .pxd]、一个 C 文件 [.c 和 .h] 和一个 pytest 文件。

我的 C 文件代表一个函数、一个结构以及 .h 和 .c 中的结构定义(对于某些结构)。

所以我的C文件:

  • 我有abc.h
struct Struct1
{

  uint32_t  V_enable_output;
  .. [ some more members which I'm not using]
  ..
}
  • 我有xyz.h
#include "abc.h"

void initialize(const volatile struct Struct_1 *config);
  • 我有一个测试.c
struct Struct2
{
 uint64_t V_enable_output_threshold;
.....
.....[some other members not being used]
}

static struct Struct2 state;

static const volatile struct Struct1 *cfg;

void initialize(const volatile struct Struct1 *const config)

{

cfg = config;

state.V_inp = 0u;

state.P_inp = 0ull;

state.P_out = 0ull;

state.V_enable_output_threshold = ((uint64_t) cfg->V_enable_output) << 32u;

}

我想为此编写一个cython接口并使用pytest对其进行测试:

所以我的与cython相关的文件如下:

  • h123.pxd
from libc.stdint cimport *
cdef extern from "abc.h":
    cdef struct Struct1:
         uint32_t V_enable_output
cdef extern from "xyz.h":
    cdef void initialize(Struct1 *config) 
  • C123.pyx
cimport h123
from libc.stdint cimport *

cdef struct Struct2:
        uint64_t V_disable_output_threshold

cdef class Class1:
    def __init__(self):
        pass
    
    def py_initialize(self, config):
        cdef h123.Struct1 config_struct
        config_struct.V_enable_output = config['V_enable_output']
        
        h123.initialize(&config_struct)

我想用 pytest 对这个函数进行单元测试,cython 文件正在构建和生成 .so,所以我继续使用 pytest:

  • test_C123.py
import pytest
import pyximport
import sys
sys.path.append('/software/module')

from C123 import Class1

access = Class1()

def test_py_initialize():
    config = {
        'V_enable_output': 2000000
    }

    assert access.py_initialize(config) is None

由于 C 中的函数不返回任何内容,所以我觉得用“无”断言测试,但我为此遇到了分段错误。

我想在 cython 文件中包含“state.V_enable_output_threshold”的值并在 pytest 中测试相同的值,关于它如何可能的任何建议?

我能够构建 cython,但是在用 pytests 测试它时,我遇到了分段错误,无法弄清楚出了什么问题。

python unit-testing pytest cython cythonize
© www.soinside.com 2019 - 2024. All rights reserved.