Skip to content

Instantly share code, notes, and snippets.

@leaver2000
Last active September 13, 2023 20:59
Show Gist options
  • Save leaver2000/5d5fdc235672b42d49e6907634064dfa to your computer and use it in GitHub Desktop.
Save leaver2000/5d5fdc235672b42d49e6907634064dfa to your computer and use it in GitHub Desktop.
Cython project for test coverage
cdef int func_1():
return 1
cdef int func_any():
return 10
def cy_func(num:int) -> int:
if num == 1:
return func_1()
else:
return func_any()
def func_1():
return 1
def func_any():
return 10
def py_func(num: int) -> int:
if num == 1:
return func_1()
else:
return func_any()
[build-system]
requires = [
"setuptools>=58.2.0",
"wheel",
"Cython>=0.29.23",
"numpy>=1.23.4",
]
build-backend = "setuptools.build_meta"
[project]
name = "app"
version = "0.0.1"
description = "..."
readme = "README.md"
requires-python = ">=3.10"
[tool.coverage.run]
plugins = [
"Cython.Coverage"
]
omit = [
"*/__init__.py",
"tests/*",
]
source = [
"app",
]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"def __repr__",
"def _html_repr_",
"@(abc\\.)?abstractmethod",
]
[tool.pytest]
testpaths = "tests/"
python setup.py build_ext --inplace
coverage run -m pytest
coverage report -m
# tests/app_test.py .. [100%]
# ================== 2 passed in 0.02s ==================
# Name Stmts Miss Cover Missing
# --------------------------------------------
# app/_api.pyx 8 2 75% 5, 12
# app/core.py 8 0 100%
# --------------------------------------------
# TOTAL 16 2 88%
import os
from setuptools import Extension, setup
from Cython.Build import cythonize
os.environ["TEST"] = "TRUE"
TEST = bool(os.environ.get("TEST", False))
compiler_directives: dict[str, int | bool] = {"language_level": 3}
define_macros: list[tuple[str, str]] = [
("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")
]
if TEST:
# inorder to compile the cython code for test coverage
# we need to include the following compiler directives...
compiler_directives.update({"linetrace": True, "profile": True})
# and include the following trace macros
define_macros.extend([("CYTHON_TRACE", "1"), ("CYTHON_TRACE_NOGIL", "1")])
ext_modules = cythonize(
[
Extension("app._api", ["app/_api.pyx"], define_macros=define_macros),
],
compiler_directives=compiler_directives,
)
setup(
ext_modules=ext_modules,
)
from app.core import py_func
from app._api import cy_func
def test_cy():
assert cy_func(1) == 1
def test_py():
assert py_func(1) == 1
assert py_func(2) == 10
@insolor
Copy link

insolor commented Sep 4, 2023

Thanks!

@leaver2000
Copy link
Author

Thanks!

glad it could help. 🐍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment