Unit Tests
PX4 provides a simple base Unittest-class. Each developer is encouraged to write unit tests in the process of adding a new feature to the PX4 framework.
Writing a Test
- Create a new .cpp file within tests with name test_[description].cpp.
 - Within test_[description].cpp include the base unittest-class 
<unit_test.h>and all files required to write a test for the new feature. - Within test_[description].cpp create a class 
[Description]Testthat inherits fromUnitTest. - Within 
[Description]Testclass declare the public methodvirtual bool run_tests(). - Within 
[Description]Testclass declare all private methods required to test the feature in question (test1(),test2(),...). - Within test_[description].cpp implement the 
run_tests()method where each test[1,2,...] will be run. - Within test_[description].cpp, implement the various tests.
 At the bottom within test_[description].cpp declare the test.
ut_declare_test_c(test_[description], [Description]Test)Here is a template:
#include <unit_test.h> #include "[new feature].h" ... class [Description]Test : public UnitTest { public: virtual bool run_tests(); private: bool test1(); bool test2(); ... }; bool [Desciption]Test::run_tests() { ut_run_test(test1) ut_run_test(test2) ... return (_tests_failed == 0); } bool [Desciption]Test::test1() { ut_[name of one of the unit test functions](... ut_[name of one of the unit test functions](... ... return true; } bool [Desciption]Test::test2() { ut_[name of one of the unit test functions](... ut_[name of one of the unit test functions](... ... return true; } ... ut_declare_test_c(test_[description], [Description]Test)Note that
ut_[name of one of the unit test functions]corresponds to one of the unittest functions defined within unit_test.h.Within tests_main.h define the new test:
extern int test_[description](int argc, char *argv[]);Within tests_main.c add description name, test function and option:
... } tests[] = { {... {"[description]", test_[description], OPTION}, ... }OPTIONcan beOPT_NOALLTEST,OPT_NOJIGTESTor0and is considered if within px4 shell one of the two commands are called:pxh> tests allor
pxh> tests jigIf a test has option
OPT_NOALLTEST, then that test will be excluded when callingtests all. The same is true forOPT_NOJITESTwhen commandtest jigis called. Option0means that the test is never excluded, which is what most developer want to use.Add the test
test_[desciption].cppto the CMakeLists.txt.
Testing on the local machine
The following command is sufficient to start a minimal new shell with the PX4 posix port running.
make posix_sitl_shell none
The shell can then be used to e.g. execute unit tests:
pxh> tests [description]
Alternatively it is also possible to run the complete unit-tests right from bash:
make tests
To see a full list of available tests write within px4 shell:
pxh> tests help