Compare commits

..

26 Commits

Author SHA1 Message Date
180c35f83e just return the keys instead of all the processors in maps_utils,py 2026-08-14 03:06:06 +05:30
e1b40d2c77 Fix comment in maps_pass.py 2026-08-14 03:04:28 +05:30
fd2412e733 Tests: Declare xdp_test_1 as a verifier-level expected failure
It generates IR and compiles, and the CO-RE relocations against struct xdp_md
resolve correctly, so it must keep passing levels 1 and 2. The kernel rejects
it: the 'data + 34 < data_end' guard is emitted as a signed compare over values
round-tripped through the stack, so the verifier never narrows the packet range
and the later iph.saddr read fails with

    invalid access to packet, off=26 size=4, R1(id=0,off=26,r=0)
    R1 offset is outside of the packet

Direct packet access needs bounds checks in a form the verifier can follow.
strict = True, so this flags up if that ever lands.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:07:32 +05:30
d66b468f39 Tests: Promote if.py to passing_tests
It generates IR, compiles, and now passes the kernel verifier, so it is no
longer a failing test. It sat in failing_tests/ with no test_config.toml entry,
which meant the framework already required it to pass at every level -- the
directory was merely misleading.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:07:32 +05:30
79c8a1e194 Core: Reject an unknown map type instead of silently emitting a hash map
process_bpf_map logged a warning and fell back to process_hash_map for any map
type it did not recognise. That turns a typo into an object file that compiles
cleanly, carries the wrong BPF_MAP_TYPE, skips the intended map type's
parameter validation entirely, and is only rejected once it reaches the kernel
-- as tests/passing_tests/ringbuf.py was, with 'failed to create: -EINVAL'.

A warning was not enough to surface it either: the test framework only fails a
test on logging.ERROR records.

Raise instead, naming the registered map types so the fix is obvious:

    ValueError: Unknown map type 'RingBuf' returned by 'm'.
    Known map types: HashMap, PerfEventArray, RingBuffer

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:07:32 +05:30
ecb2774694 Tests: Declare the ringbuf map with its real type and a legal size
The map was declared as RingBuf, which is not an exported name -- the class is
RingBuffer. maps_pass has no processor registered under RingBuf, so it fell
through to the 'unknown map type, defaulting to HashMap' path and was emitted
as BPF_MAP_TYPE_HASH with no key or value size. The kernel rejected it:

    libbpf: map 'mymap': found type = 1.
    libbpf: map 'mymap': failed to create: -EINVAL

Nothing caught this earlier because the test framework compiles the file's AST
and never imports it, so the bogus 'from pythonbpf.maps import RingBuf' never
raised ImportError.

Using the real name also subjects the map to process_ringbuf_map's validation,
which max_entries=1024 does not survive: a ringbuf needs a power of two at
least as large as the page size. Raised to 4096. libbpf now reports
type = 27 with max_entries = 4096.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:07:32 +05:30
a7e2bc39ef Tests: Add a verifier level to the expected-failure tiers
test_config.toml could only declare a failure at the "ir" or "llc" level, and
test_verifier.py dropped every declared-xfail case from the level-3 run
outright. A program that generates IR and compiles cleanly but that the kernel
verifier rejects therefore had no way to be declared: it was silently treated
as must-pass at all three levels.

Levels now form an ordered pipeline (ir < llc < verifier) and a declared level
marks that level and every later one xfail, which is what the old
ir-implies-llc special case was expressing. Level 3 runs every test file and
reports declared failures as expected ones rather than skipping them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:07:23 +05:30
edefe626d0 Tests: Use a real program section in return, var_rval and if
These three declared @section("sometag1"), which is not a section name libbpf
can map to a program type:

    libbpf: failed to guess program type from ELF section 'sometag1'

so they were rejected before the kernel verifier ever saw them. They generate
IR and compile fine; only the section was wrong. Switch to
tracepoint/syscalls/sys_enter_execve, matching the other tracepoint tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:07:23 +05:30
f796338245 Tests: Silence deprecation warnings in test-cov and test-verifier
c2de7da added -W ignore::DeprecationWarning to the 'test' target only, so
'make test-cov' and 'make test-verifier' still drown in warnings from the
generated vmlinux.py.

Also correct the test-verifier note: the suite does not run pytest under sudo,
tests/framework/verifier.py shells out to 'sudo bpftool' itself.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:07:23 +05:30
c2de7dad96 Temporarily ignore deprecation warnings for vmlinux.py 2026-05-27 14:53:54 +05:30
d1bb0191c9 Merge pull request #84 from pythonbpf/testing-framework
Automated testing framework which will give us regression and coverage reports, meant to run in a GH Action and locally
2026-04-25 23:02:00 +05:30
01ddffb619 Tests: Enable vmlinux requirement for verifier tests 2026-04-25 22:47:44 +05:30
1670814261 Tests: Remove unnecessary context from test_config 2026-04-25 20:22:57 +05:30
3c977fb240 Tests: Remove tomli from pyproject.toml 2026-04-25 20:15:22 +05:30
9103e44711 Tests: Remove unnecessary stuff from README 2026-04-25 20:13:17 +05:30
35b492054c Tests: Remove unnecessary _all_cases from conftest 2026-04-25 20:10:27 +05:30
48fa8aec3f Tests: USe namedtuple to pass verifier output for asserts 2026-04-25 18:54:25 +05:30
145e930389 Tests: Fix prefix set naming in test collector 2026-04-25 18:21:42 +05:30
5ec86be7dd Tests: Use full import path in test collector 2026-04-25 18:07:40 +05:30
56db0d3738 Tests: Remove unnecessary version check from test collector 2026-04-25 17:59:59 +05:30
1d555ddd47 Tests: Add tests/README.md
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 19:35:08 +05:30
ee444447b9 Tests: Add tests/__init__.py and pythonpath config
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 19:34:47 +05:30
da57911122 Tests: Add automated testing framework with coverage support
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-30 19:33:43 +05:30
0498885f71 Merge pull request #82 from pythonbpf/compilation-context
PythonBPF: Add Compilation Context to allow parallel compilation of multiple jobs
2026-03-29 10:02:10 +02:00
b7f917c3c2 Merge pull request #83 from pythonbpf/dependabot/github_actions/actions-985357984d
build(deps): bump the actions group with 2 updates
2026-03-07 14:11:31 +05:30
b025ae7158 build(deps): bump the actions group with 2 updates
Bumps the actions group with 2 updates: [actions/upload-artifact](https://github.com/actions/upload-artifact) and [actions/download-artifact](https://github.com/actions/download-artifact).


Updates `actions/upload-artifact` from 6 to 7
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v6...v7)

Updates `actions/download-artifact` from 7 to 8
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v7...v8)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 11:45:33 +00:00
21 changed files with 575 additions and 15 deletions

View File

@ -33,7 +33,7 @@ jobs:
python -m build
- name: Upload distributions
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: release-dists
path: dist/
@ -59,7 +59,7 @@ jobs:
steps:
- name: Retrieve release distributions
uses: actions/download-artifact@v7
uses: actions/download-artifact@v8
with:
name: release-dists
path: dist/

View File

@ -1,10 +1,23 @@
install:
pip install -e .
uv pip install -e ".[test]"
clean:
rm -rf build dist *.egg-info
rm -rf examples/*.ll examples/*.o
rm -rf htmlcov .coverage
test:
pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier"
test-cov:
pytest tests/ -W ignore::DeprecationWarning -v --tb=short -m "not verifier" \
--cov=pythonbpf --cov-report=term-missing --cov-report=html
test-verifier:
@echo "NOTE: verifier tests shell out to 'sudo bpftool'; run 'sudo -v' first so"
@echo " the timestamp does not lapse mid-run. bpftool must be installed."
pytest tests/test_verifier.py -W ignore::DeprecationWarning -v --tb=short -m verifier
all: clean install
.PHONY: all clean
.PHONY: all clean install test test-cov test-verifier

View File

@ -41,7 +41,29 @@ docs = [
"sphinx-rtd-theme>=2.0",
"sphinx-copybutton",
]
test = [
"pytest>=8.0",
"pytest-cov>=5.0",
]
[tool.setuptools.packages.find]
where = ["."]
include = ["pythonbpf*"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
python_files = ["test_*.py"]
markers = [
"verifier: requires sudo/root for kernel verifier tests (not run by default)",
"vmlinux: requires vmlinux.py for current kernel",
]
log_cli = false
[tool.coverage.run]
source = ["pythonbpf"]
omit = ["*/vmlinux*", "*/__pycache__/*"]
[tool.coverage.report]
show_missing = true
skip_covered = false

View File

@ -175,10 +175,15 @@ def process_bpf_map(func_node, compilation_context):
if isinstance(rval, ast.Call) and isinstance(rval.func, ast.Name):
handler = MapProcessorRegistry.get_processor(rval.func.id)
if handler:
return handler(map_name, rval, compilation_context)
else:
logger.warning(f"Unknown map type {rval.func.id}, defaulting to HashMap")
return process_hash_map(map_name, rval, compilation_context)
if handler is None:
# Raise an exception and fail the build because the
# map carried the wrong type. A misspelled map type
# is a program error.
known = ", ".join(sorted(MapProcessorRegistry.known_types()))
raise ValueError(
f"Unknown map type '{rval.func.id}' returned by '{map_name}'. "
f"Known map types: {known}"
)
return handler(map_name, rval, compilation_context)
else:
raise ValueError("Function under @map must return a map")

View File

@ -33,3 +33,8 @@ class MapProcessorRegistry:
def get_processor(cls, map_type_name):
"""Get the processor function for a map type"""
return cls._processors.get(map_type_name)
@classmethod
def known_types(cls):
"""Names of every registered map type, for error messages"""
return list(cls._processors.keys())

108
tests/README.md Normal file
View File

@ -0,0 +1,108 @@
# PythonBPF Test Suite
## Quick start
```bash
# Activate the venv and install test deps (once)
source .venv/bin/activate
uv pip install -e ".[test]"
# Run the full suite (IR + LLC levels, no sudo required)
make test
# Run with coverage report
make test-cov
```
## Test levels
Tests are split into three levels, each in a separate file:
| Level | File | What it checks | Needs sudo? |
|---|---|---|---|
| 1 — IR generation | `test_ir_generation.py` | `compile_to_ir()` completes without exception or `logging.ERROR` | No |
| 2 — LLC compilation | `test_llc_compilation.py` | Level 1 + `llc` produces a non-empty `.o` file | No |
| 3 — Kernel verifier | `test_verifier.py` | `bpftool prog load -d` exits 0 | Yes |
Levels 1 and 2 run together with `make test`. Level 3 is opt-in:
```bash
make test-verifier # requires bpftool and sudo
```
## Running a single test
Tests are parametrized by file path. Use `-k` to filter:
```bash
# By file name
pytest tests/ -v -k "and.py" -m "not verifier"
# By category
pytest tests/ -v -k "conditionals" -m "not verifier"
# One specific level only
pytest tests/test_ir_generation.py -v -k "hash_map.py"
```
## Coverage report
```bash
make test-cov
```
- **Terminal**: shows per-file coverage with missing lines after the test run.
- **HTML**: written to `htmlcov/index.html` — open in a browser for line-by-line detail.
```bash
xdg-open htmlcov/index.html
```
`htmlcov/` and `.coverage` are excluded from git (listed in `.gitignore` if not already).
## Expected failures (`test_config.toml`)
Known-broken tests are declared in `tests/test_config.toml`:
```toml
[xfail]
"failing_tests/my_test.py" = {reason = "...", level = "ir"}
```
- `level = "ir"` — fails during IR generation.
- `level = "llc"` — IR generates fine but `llc` rejects it.
- `level = "verifier"` — IR and `llc` both succeed, but the kernel verifier rejects the object.
A failure at one level implies failure at every later one, so the declared level marks
that level **and all later ones** xfail. An `"ir"` entry is xfail at all three levels; a
`"verifier"` entry is xfail at level 3 only and must still pass levels 1 and 2.
Every test file runs at every level, including the ones declared here — level 3 does not
skip declared failures, it reports them as expected ones.
All xfails use `strict = True`: if a test starts **passing** it shows up as **XPASS** and is treated as a test failure. This is intentional — it means the bug was fixed and the test should be promoted to `passing_tests/`.
## Adding a new test
1. Create a `.py` file in `tests/passing_tests/<category>/` with the usual `@bpf` decorators and a `compile()` call at the bottom.
2. Run `make test` — the file is discovered and tested automatically at all levels.
3. If the test is expected to fail, add it to `tests/test_config.toml` instead of `passing_tests/`.
## Directory structure
```
tests/
├── README.md ← you are here
├── conftest.py ← pytest config: discovery, xfail/skip injection, fixtures
├── test_config.toml ← expected-failure list
├── test_ir_generation.py ← Level 1
├── test_llc_compilation.py ← Level 2
├── test_verifier.py ← Level 3 (opt-in, sudo)
├── framework/
│ ├── bpf_test_case.py ← BpfTestCase dataclass
│ ├── collector.py ← discovers test files, reads test_config.toml
│ ├── compiler.py ← wrappers around compile_to_ir() + _run_llc()
│ └── verifier.py ← bpftool subprocess wrapper
├── passing_tests/ ← programs that should compile and verify cleanly
└── failing_tests/ ← programs with known issues (declared in test_config.toml)
```

0
tests/__init__.py Normal file
View File

102
tests/conftest.py Normal file
View File

@ -0,0 +1,102 @@
"""
pytest configuration for the PythonBPF test suite.
Test discovery:
All .py files under tests/passing_tests/ and tests/failing_tests/ are
collected as parametrized BPF test cases.
Markers applied automatically from test_config.toml:
- xfail (strict=True): failing_tests/ entries that are expected to fail
- skip: vmlinux tests when vmlinux.py is not importable
Run the suite:
pytest tests/ -v -m "not verifier" # IR + LLC only (no sudo)
pytest tests/ -v --cov=pythonbpf # with coverage
pytest tests/test_verifier.py -m verifier # kernel verifier (sudo required)
"""
import logging
import pytest
from tests.framework.bpf_test_case import level_index
from tests.framework.collector import collect_all_test_files
# ── vmlinux availability ────────────────────────────────────────────────────
try:
import vmlinux # noqa: F401
VMLINUX_AVAILABLE = True
except ImportError:
VMLINUX_AVAILABLE = False
# ── pytest_generate_tests: parametrize on bpf_test_file ───────────────────
def pytest_generate_tests(metafunc):
if "bpf_test_file" in metafunc.fixturenames:
cases = collect_all_test_files()
metafunc.parametrize(
"bpf_test_file",
[c.path for c in cases],
ids=[c.rel_path for c in cases],
)
# ── pytest_collection_modifyitems: apply xfail / skip markers ─────────────
def pytest_collection_modifyitems(items):
case_map = {c.rel_path: c for c in collect_all_test_files()}
for item in items:
# Resolve the test case from the parametrize ID embedded in the node id.
# Node id format: tests/test_foo.py::test_bar[passing_tests/helpers/pid.py]
case = None
for bracket in (item.callspec.id,) if hasattr(item, "callspec") else ():
case = case_map.get(bracket)
break
if case is None:
continue
# vmlinux skip
if case.needs_vmlinux and not VMLINUX_AVAILABLE:
item.add_marker(
pytest.mark.skip(reason="vmlinux.py not available for current kernel")
)
continue
# xfail (strict: XPASS counts as a test failure, alerting us to fixed bugs)
if case.is_expected_fail:
# A failure at one level implies failure at every later one, so mark
# this item xfail whenever the declared level is at or before it:
# "ir" → IR, LLC and verifier
# "llc" → LLC and verifier (IR is expected to succeed)
# "verifier" → verifier only
if item.nodeid.startswith("tests/test_verifier.py"):
item_level = "verifier"
elif item.nodeid.startswith("tests/test_llc_compilation.py"):
item_level = "llc"
else:
item_level = "ir"
if level_index(case.xfail_level) <= level_index(item_level):
item.add_marker(
pytest.mark.xfail(
reason=case.xfail_reason,
strict=True,
raises=Exception,
)
)
# ── caplog level fixture: capture ERROR+ from pythonbpf ───────────────────
@pytest.fixture(autouse=True)
def set_log_level(caplog):
with caplog.at_level(logging.ERROR, logger="pythonbpf"):
yield

View File

View File

@ -0,0 +1,31 @@
from dataclasses import dataclass
from pathlib import Path
# The three test levels, in pipeline order. A test declared as failing at one
# level is also expected to fail at every later level: a program that cannot
# generate IR cannot reach llc, and one that llc rejects never reaches the
# kernel. Used by conftest to decide which items to mark xfail.
LEVELS = ("ir", "llc", "verifier")
def level_index(level: str) -> int:
"""Position of a level in the pipeline. Unknown levels sort first ("ir")."""
try:
return LEVELS.index(level)
except ValueError:
return 0
@dataclass
class BpfTestCase:
path: Path
rel_path: str
is_expected_fail: bool = False
xfail_reason: str = ""
xfail_level: str = "ir" # one of LEVELS
needs_vmlinux: bool = False
skip_reason: str = ""
@property
def test_id(self) -> str:
return self.rel_path.replace("/", "::")

View File

@ -0,0 +1,56 @@
from pathlib import Path
import tomllib
from tests.framework.bpf_test_case import BpfTestCase
TESTS_DIR = Path(__file__).parent.parent
CONFIG_FILE = TESTS_DIR / "test_config.toml"
VMLINUX_TEST_DIRS_PASSING = {"passing_tests/vmlinux"}
VMLINUX_TEST_DIRS_FAILING = {
"failing_tests/vmlinux",
"failing_tests/xdp",
}
def _is_vmlinux_test(rel_path: str) -> bool:
for prefix in VMLINUX_TEST_DIRS_PASSING | VMLINUX_TEST_DIRS_FAILING:
if rel_path.startswith(prefix):
return True
return False
def _load_config() -> dict:
if not CONFIG_FILE.exists():
return {}
with open(CONFIG_FILE, "rb") as f:
return tomllib.load(f)
def collect_all_test_files() -> list[BpfTestCase]:
config = _load_config()
xfail_map: dict = config.get("xfail", {})
cases = []
for subdir in ("passing_tests", "failing_tests"):
for py_file in sorted((TESTS_DIR / subdir).rglob("*.py")):
rel = str(py_file.relative_to(TESTS_DIR))
needs_vmlinux = _is_vmlinux_test(rel)
xfail_entry = xfail_map.get(rel)
is_expected_fail = xfail_entry is not None
xfail_reason = xfail_entry.get("reason", "") if xfail_entry else ""
xfail_level = xfail_entry.get("level", "ir") if xfail_entry else "ir"
cases.append(
BpfTestCase(
path=py_file,
rel_path=rel,
is_expected_fail=is_expected_fail,
xfail_reason=xfail_reason,
xfail_level=xfail_level,
needs_vmlinux=needs_vmlinux,
)
)
return cases

View File

@ -0,0 +1,23 @@
import logging
from pathlib import Path
from pythonbpf.codegen import compile_to_ir, _run_llc
def run_ir_generation(test_path: Path, output_ll: Path):
"""Run compile_to_ir on a BPF test file.
Returns the (output, structs_sym_tab, maps_sym_tab) tuple from compile_to_ir.
Raises on exception. Any logging.ERROR records captured by pytest caplog
indicate a compile failure even when no exception is raised.
"""
return compile_to_ir(str(test_path), str(output_ll), loglevel=logging.WARNING)
def run_llc(ll_path: Path, obj_path: Path) -> bool:
"""Compile a .ll file to a BPF .o using llc.
Raises subprocess.CalledProcessError on failure (llc uses check=True).
Returns True on success.
"""
return _run_llc(str(ll_path), str(obj_path))

View File

@ -0,0 +1,27 @@
import subprocess
import uuid
from collections import namedtuple
from pathlib import Path
def verify_object(obj_path: Path) -> tuple[bool, str]:
"""Run bpftool prog load -d to verify a BPF object file against the kernel verifier.
Pins the program temporarily at /sys/fs/bpf/bpf_prog_test_<uuid>, then removes it.
Returns (success, combined_output). Requires sudo / root.
"""
pin_path = f"/sys/fs/bpf/bpf_prog_test_{uuid.uuid4().hex[:8]}"
try:
result = subprocess.run(
["sudo", "bpftool", "prog", "load", "-d", str(obj_path), pin_path],
capture_output=True,
text=True,
timeout=30,
)
Output = namedtuple("Output", ["stdout", "stderr"])
output = Output(stdout=result.stdout, stderr=result.stderr)
return result.returncode == 0, output
except subprocess.TimeoutExpired:
return False, "bpftool timed out after 30s"
finally:
subprocess.run(["sudo", "rm", "-f", pin_path], check=False, capture_output=True)

View File

@ -3,7 +3,7 @@ from ctypes import c_void_p, c_int64
@bpf
@section("sometag1")
@section("tracepoint/syscalls/sys_enter_execve")
def sometag(ctx: c_void_p) -> c_int64:
if 3 + 2 == 5:
return c_int64(5)

View File

@ -3,7 +3,7 @@ from ctypes import c_void_p, c_int64
@bpf
@section("sometag1")
@section("tracepoint/syscalls/sys_enter_execve")
def sometag(ctx: c_void_p) -> c_int64:
return c_int64(1 - 1)

View File

@ -1,13 +1,13 @@
from pythonbpf import bpf, BPF, map, bpfglobal, section, compile, compile_to_ir
from pythonbpf.maps import RingBuf, HashMap
from pythonbpf.maps import RingBuffer, HashMap
from ctypes import c_int32, c_void_p
# Define a map
@bpf
@map
def mymap() -> RingBuf:
return RingBuf(max_entries=(1024))
def mymap() -> RingBuffer:
return RingBuffer(max_entries=4096)
@bpf

View File

@ -5,7 +5,7 @@ from ctypes import c_void_p, c_int64
@bpf
@section("sometag1")
@section("tracepoint/syscalls/sys_enter_execve")
def sometag(ctx: c_void_p) -> c_int64:
a = 1 - 1
return c_int64(a)

34
tests/test_config.toml Normal file
View File

@ -0,0 +1,34 @@
# test_config.toml
#
# [xfail] — tests expected to fail.
# key = path relative to tests/
# value = {reason = "...", level = "ir" | "llc" | "verifier"}
# level "ir" = fails during pythonbpf IR generation (exception or ERROR log)
# level "llc" = IR generates but llc rejects it
# level "verifier" = IR and llc both succeed, but the kernel verifier rejects it
#
# A failure at one level implies failure at every later one, so the declared
# level marks that level and all later ones xfail.
#
[xfail]
"failing_tests/conditionals/struct_ptr.py" = {reason = "Struct pointer used directly as boolean condition not supported", level = "ir"}
# Compiles cleanly; rejected by the kernel. The `data + 34 < data_end` guard is
# emitted as a signed compare over values round-tripped through the stack, so the
# verifier never narrows the packet range (it stays r=0) and the later
# `iph.saddr` read fails with "invalid access to packet, off=26 size=4" /
# "R1 offset is outside of the packet". Direct packet access needs bounds checks
# in a form the verifier can follow.
"failing_tests/xdp/xdp_test_1.py" = {reason = "XDP direct packet access: the data/data_end guard does not establish a packet range the verifier can use", level = "verifier"}
"failing_tests/license.py" = {reason = "Missing LICENSE global produces IR that llc rejects — should be caught earlier with a clear error message", level = "llc"}
"failing_tests/undeclared_values.py" = {reason = "Undeclared variable used in f-string — should raise SyntaxError (correct behaviour, test documents it)", level = "ir"}
"failing_tests/vmlinux/args_test.py" = {reason = "struct_trace_event_raw_sys_enter args field access not supported", level = "ir"}
"failing_tests/vmlinux/assignment_handling.py" = {reason = "Assigning vmlinux enum value (XDP_PASS) to a local variable not yet supported", level = "ir"}
"failing_tests/xdp_pass.py" = {reason = "XDP program using vmlinux structs (struct_xdp_md) and complex map/struct interaction not yet supported", level = "ir"}

View File

@ -0,0 +1,29 @@
"""
Level 1 — IR Generation tests.
For every BPF test file, calls compile_to_ir() and asserts:
1. No exception is raised by the pythonbpf compiler.
2. No logging.ERROR records are emitted during compilation.
3. A .ll file is produced.
Tests in failing_tests/ are marked xfail (strict=True) by conftest.py —
they must raise an exception or produce an ERROR log to pass the suite.
"""
import logging
from pathlib import Path
from tests.framework.compiler import run_ir_generation
def test_ir_generation(bpf_test_file: Path, tmp_path, caplog):
ll_path = tmp_path / "output.ll"
run_ir_generation(bpf_test_file, ll_path)
error_records = [r for r in caplog.records if r.levelno >= logging.ERROR]
assert not error_records, "IR generation produced ERROR log(s):\n" + "\n".join(
f" [{r.name}] {r.getMessage()}" for r in error_records
)
assert ll_path.exists(), "compile_to_ir() returned without writing a .ll file"

View File

@ -0,0 +1,32 @@
"""
Level 2 — LLC compilation tests.
For every BPF test file, runs the full compile_to_ir() + _run_llc() pipeline
and asserts a non-empty .o file is produced.
Tests in failing_tests/ are marked xfail (strict=True) by conftest.py.
"""
import logging
from pathlib import Path
from tests.framework.compiler import run_ir_generation, run_llc
def test_llc_compilation(bpf_test_file: Path, tmp_path, caplog):
ll_path = tmp_path / "output.ll"
obj_path = tmp_path / "output.o"
run_ir_generation(bpf_test_file, ll_path)
error_records = [r for r in caplog.records if r.levelno >= logging.ERROR]
assert not error_records, "IR generation produced ERROR log(s):\n" + "\n".join(
f" [{r.name}] {r.getMessage()}" for r in error_records
)
run_llc(ll_path, obj_path)
assert obj_path.exists() and obj_path.stat().st_size > 0, (
"llc did not produce a non-empty .o file"
)

73
tests/test_verifier.py Normal file
View File

@ -0,0 +1,73 @@
"""
Level 3 — Kernel verifier tests.
For every passing BPF test file, compiles to a .o and runs:
sudo bpftool prog load -d <file.o> /sys/fs/bpf/bpf_prog_test_<id>
These tests are opt-in: they require sudo and kernel access, and are gated
behind the `verifier` pytest mark. Run with:
pytest tests/test_verifier.py -m verifier -v
Note: uses the venv Python binary for any in-process calls, but bpftool
itself is invoked via subprocess with sudo. Ensure bpftool is installed
and the user can sudo.
"""
import logging
from pathlib import Path
import pytest
from tests.framework.collector import collect_all_test_files
from tests.framework.compiler import run_ir_generation, run_llc
from tests.framework.verifier import verify_object
def _verifier_test_files():
return [c.path for c in collect_all_test_files()]
def _verifier_test_ids():
return [c.rel_path for c in collect_all_test_files()]
def _get_rejection_reason(verifier_test_file: Path, output) -> str:
# Extract the reason for rejection from the verifier output
errstr = f"Verifier rejected {verifier_test_file.name}:\n"
errstr += "=" * 80 + "\n"
errstr += f"stdout:\n{output.stdout}\n"
errstr += "=" * 80 + "\n"
errstr += f"stderr:\n{output.stderr}\n"
errstr += "=" * 80 + "\n"
return errstr
# Every test file runs at this level, including the ones declared in
# test_config.toml. conftest marks those xfail, so an "ir"- or "llc"-level
# failure is still reported as an expected failure rather than being silently
# dropped from the level-3 run — and a "verifier"-level entry becomes possible
# at all.
@pytest.mark.verifier
@pytest.mark.parametrize(
"verifier_test_file",
_verifier_test_files(),
ids=_verifier_test_ids(),
)
def test_kernel_verifier(verifier_test_file: Path, tmp_path, caplog):
"""Compile the BPF test and verify it passes the kernel verifier."""
ll_path = tmp_path / "output.ll"
obj_path = tmp_path / "output.o"
run_ir_generation(verifier_test_file, ll_path)
error_records = [r for r in caplog.records if r.levelno >= logging.ERROR]
assert not error_records, "IR generation produced ERROR log(s):\n" + "\n".join(
f" [{r.name}] {r.getMessage()}" for r in error_records
)
run_llc(ll_path, obj_path)
assert obj_path.exists() and obj_path.stat().st_size > 0
ok, output = verify_object(obj_path)
assert ok, _get_rejection_reason(verifier_test_file, output)