Files
python-bpf/tests
varunrmallya 40aad02d73 loops (#106)
* Core: Lower annotated assignment (x: c_int32 = 0)

The annotation types the slot, so `x: c_int32 = 0` is an i32 where the
literal alone would give an i64; the store goes through the same
handle_variable_assignment plain assignment uses. A bare `x: T` makes the
slot and binds nothing.

The already-bound and global-shadowing bookkeeping that Assign allocation did
inline moves into _bind_name, which both statements now call.

* Tests: Annotated assignment passes now

* Core: Lower if-branches in the function's return type

handle_if processed its branches without passing ret_type down, so a
return inside an if fell back to process_stmt's i64 default: a -> c_int32
function got `ret i64 7`, which llc rejects. The branches now go through
process_block, which threads ret_type and stops at a statement that ends
the block instead of emitting after its terminator.

* Core: Lower for-over-range and while loops, with break and continue

`for i in range(...)` steps a hidden induction counter, allocated in the
entry block next to the loop variable, and copies it into the variable each
iteration, so rebinding the variable in the body leaves the trip count alone
as in Python (and the loop stays visibly bounded for the verifier). The
counter is 64-bit, signed unless the bounds make C's arithmetic unsigned.
Bounds are evaluated once, before the loop; the step must be a nonzero
integer literal, because its sign picks the loop test.

`while` re-evaluates its test at the top of each iteration. `break` and
`continue` branch through a loop-target stack on the compilation context;
outside a loop they are a SyntaxError, as in Python. A loop's else-branch
runs on normal exit only. Anything but range() as the iterable is rejected
with NotImplementedError.

The allocation pass now descends into loop bodies and counts helper temps in
loop headers. Checked against clang -O2 on tests/c-form/loops.bpf.c: the
constant-bound cases fold to the same ret, and a helper-bounded loop gets the
same rotated loop.

* Tests: Loops pass now, plus the cases the lowering promises

- passing_tests/loops/: the seven range/while/break/continue/nested tests
  move over from failing_tests/, joined by rebinding the loop variable, a
  negative step, loop else-branches, and a helper-bounded loop over a
  @bpfglobal that survives -O2 as a real loop for the verifier.
- failing_tests/loops/: break outside a loop, and a non-literal range step.
- for_map_items stays xfail: map iteration needs its own design.
- c-form/loops.bpf.c: the clang reference the lowering was checked against.

* Tests: Indent the loop C reference with spaces

The remove-tabs pre-commit hook rejects tab indentation outside docs/ and
Makefiles, which failed the Format job.

* Core: Fix loop edge cases the lowering got wrong

- `pass` is accepted as a statement, the natural body of a loop run for its
  side effects.
- Falling off the end of a function returns 0 in the function's own return
  type. After `while True` that block is unreachable, but a c_int32 function
  still emitted `ret i64 0`, which llc rejected.
- A range() step other than 1 could wrap the counter past INT64_MAX or
  UINT64_MAX back inside the range and loop forever. The step block now ends
  the loop when the distance left to stop, exact as an unsigned number, is
  no longer than the step. That is a normal exit, so the else-branch runs.
  Steps of 1 cannot overshoot and keep the plain loop, so the helper-bounded
  loop the verifier walks is unchanged.
- A step of 2**64 or more no longer truncates to 0: it is a compile error,
  since it does not fit the counter. Steps from 2**63 up are emitted by
  their bits.
- The counter's signedness folds each bound into a signed 64-bit type rather
  than joining the bounds alone, so only a c_uint64 bound makes it unsigned:
  range(-1, n) over a c_uint32 n runs 4 times, as in C with an __s64 counter.

* Tests: Run loop programs on the host, plus adversarial loop cases

Levels 1 and 2 only prove a loop compiles; one can still run the wrong
number of times, or forever. test_loops_run.py JIT-compiles each
helper-free passing_tests/loops case on the host (framework/host_jit.py,
in a subprocess with a timeout) and checks its return value against what
CPython returns for the same body.

- passing_tests/loops/: pass bodies, `while True` exited by a return in a
  c_int32 function, step overflow past INT64_MAX, INT64_MIN and UINT64_MAX,
  a c_uint32 stop with a negative start, and loop variables that must stay
  one local (a nested same-name loop, a read after the loop).
- failing_tests/loops/range_step_too_wide.py: a 2**64 step is a compile error.
- reuse_loop_var_signedness.py is xfail in test_loops_run.py: every local
  gets one slot typed by its first binding, so a second loop's `i` inherits
  the first loop's unsigned type. `x = n_u64; x = -3` does the same, so the
  fix is general, not loop-specific.
2026-09-26 01:00:45 +05:30
..
2026-09-26 01:00:45 +05:30
2026-09-26 01:00:45 +05:30
2026-09-26 01:00:45 +05:30
x
2026-09-25 10:26:22 +05:30
2026-09-26 01:00:45 +05:30
2026-09-26 01:00:45 +05:30
2026-09-26 01:00:45 +05:30

PythonBPF Test Suite

Quick start

# 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:

make test-verifier   # requires bpftool and sudo

Running a single test

Tests are parametrized by file path. Use -k to filter:

# 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

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.
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:

[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/.

Kernel selftest equivalents

tests/kernel_selftest_equivalent/ contains PythonBPF versions of important kernel BPF selftests from bpf-next/tools/testing/selftests/bpf. Each file names its upstream original in a header comment.

The directory holds two kinds of test, and both are useful:

  • Ports that pass. A program PythonBPF can already express. These widen the range of program types under test — raw_tp, perf_event, tracepoint/sched/* and others that nothing else exercises.
  • Roadmap tests that fail. A program describing a feature PythonBPF should grow next. These must be listed as strict expected failures in tests/test_config.toml until the feature lands, at which point they turn up as XPASS and should be promoted.

What a passing port proves — and does not

A kernel selftest is two halves: the BPF program under progs/, and a userspace driver under prog_tests/ that loads it through a skeleton, triggers it and asserts on the result. Only the BPF half is ported, because this framework compiles and verifies programs but never runs them.

So a passing test here says PythonBPF emits a loadable, verifiable object for that program type and feature mix. It does not say the program behaves the way the kernel's version does. Treat it as a compiler assertion, not a semantic one.

Globals

The selftest corpus overwhelmingly reports results through global variables: the program writes a global and the driver reads it back. Ports keep that shape with @bpfglobal scalars, so a future userspace driver reads the same .bss/.data values the kernel's driver does. Anything a global cannot yet hold (arrays, structs, strings) is a roadmap test, not a workaround.

The one substitution still in use is WORKAROUND(atomics): upstream counters incremented with __sync_fetch_and_add are plain x += 1 here, tagged on the line so the sweep is mechanical once atomics land. PORTING-NOTES.md in that directory records every port, its rewrite if any, and why the rest of the corpus is out of reach; tools/selftest-audit.py regenerates that scoring.

Anything importing from vmlinux belongs in vmlinux/, which is registered in VMLINUX_TEST_DIRS_PASSING so it is skipped rather than failed where no vmlinux.py has been generated.

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)
└── kernel_selftest_equivalent/ ← ports of kernel selftests + feature roadmap tests