Search code examples
pythonunit-testingebpfbpfbcc-bpf

How does one write Unit Tests for eBPF programs written in python via the BCC interface for eBPF?


I know this is a weird one, And I’m probably looking for help in a bleak topic since after days of scouring the net to no avail I decided to reach out to this community...

so I need to write unit tests for eBPF programs written in python with BCC

Any advice will be tremendously appreciated, even pointing me in the general direction of where i can further look for insights into solving the issue i am currently faced with

Here is a trivial example:

from bcc import BPF

# define BPF program
prog = """
int hello(void *ctx) {
    bpf_trace_printk("Hello, World!\\n");
    return 0;
}
"""

# load BPF program
b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="hello")

# header
print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "MESSAGE"))

# format output
while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except ValueError:
        continue
    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))

I need to unit test the C code and the python code independently to see that their both behaving as expected


Solution

  • You can unit test the Python logic in the usual way you would for Python. For the BPF part, there are two approaches:

    • You use another Python program to load and trigger the BPF program you have written. To trigger your program, you can use BPF_PROG_TEST_RUN or you can attach it as planned and trigger the attach point (e.g., call clone if the program is attached to the clone(2) syscall). Admittedly, this approach looks almost more like end-to-end tests than unit tests.
    • You split your BPF program into C functions in a header file. You write a C unit test that includes that header file and calls those functions with inputs to check. For that to work, you need to make sure that the C functions don't call anything BPF specific that could be compiled to a non-BPF backend. That can be a bit hard given maps and helpers.