The kernel as an integrated tesing framework. Here a brief explaination will be covered.
Testing can be enabled if TEST=True
env variable is set, this can be
done consistently through the config.sh
file generated by make config
.
If testing is enabled, the definition KERNEL_TEST
will be passed to
the compiler and available to the pre-processor.
Usually, unit tests are located in a separate file from the file where
the functions to be tested are implemented, usually this file terminates
with _test.c
. For example the file containing test cases for tty.c
is called tty_test.c
and is located in the same directory. This way,
the tests get compiled only if testing is enabled and without invading
the code with #ifdef
s.
Once a test file is created, It needs to be added to the build system.
This can be done simply by appending it in the make.config
file under
the variable TESTS_OBJS
:
TESTS_OBJS+=\
arch/i386/tty_test.o
The build system will take care of the rest.
The most basic unit test is the following:
#include <ktest.h>
KTEST(suite_name_here, test_name_here)
{
KTEST_END;
}
Some macros are available, for example KASSERT()
to do assertions.
You should know that if you want to flag a test as failed, It should
return an integer different that 0.
Another example:
#include <ktest.h>
KTEST(tty, terminal_setcolor)
{
// Setup
uint8_t terminal_color_old = terminal_color;
// Test 1
terminal_setcolor(VGA_COLOR_BLUE);
KASSERT(terminal_color == VGA_COLOR_BLUE);
// Test 2
terminal_setcolor(VGA_COLOR_GREEN);
KASSERT(terminal_color == VGA_COLOR_GREEN);
// Clenup
terminal_setcolor(terminal_color_old);
KTEST_END;
}
If thests are enabled in the build system, the final kernel will accept
the flag test
during boot. This will run all the tests and stop.
The output will be written to both teminal display and in COM1 serial
port, on qemu you can use the flag -serial stdio
to receive the
output in the terminal you are launghing qemu from, or you could
redirect the output over the network with -serial tcp::4444,server
.
A grub entry is already provided to test the kernel:
menuentry "test" {
multiboot /boot/myos.kernel test
}
How tests are registered is pretty cool, I suggest you to take a deeper look ;)