Unit testing + Mocking eBPF programs in python incl emulating kernel to user-space interactions

Question:

So I need to get some mocking+testing done on a very specific kind of python code: it is an eBPF(Berkely packet filter) program using python, which in essence runs a C program in kernel space through a python script via the BPF Compiler Collection BCC
eg code:

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 want to now write tests for the C and the Python code without the 2 interfering (I would even be satisfied with some basic python unit testing). Any & all possible approaches to the problem are welcome, or even a general direction to look for info on this kind of testing, really just looking to address the following concerns:
Can I easily mock the kernel interactions when testing the python code?
Can I emulate a message coming from the kernel to user-space?
Can I test a message that’s just larger or just smaller than the expected message size?

I tried looking into the topic for days, to no avail so even pointing me in the right direction would be greatly appreciated…

Asked By: Kian Reddy

||

Answers:

So it turns out there is no quick way to really get into the testing of the C code in a basic way like you would using pytest to test the python logic. However if you absolutely need solid testing done then browsing through here and making sense of how BCC does their version of "unit testing" may be of help…

Answered By: Kian Reddy