Unittests in Krita

目录

What is a unit test is and why is it needed?

Wiki:

A unit test is a piece of code that automatically checks if your class or subsystem works correctly. The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits 1.

Comment:

In other words unit testing allows the developer to verify if his initial design decisions has been implemented correctly and all the corner-cases are handled correctly.

In Krita Project we use unit tests for several purposes. Not all of them work equally good, but all together they help developing a lot.

Debugging of new code

Wiki:

Unit testing finds problems early in the development cycle. This includes both bugs in the programmer’s implementation and flaws or missing parts of the specification for the unit. The process of writing a thorough set of tests forces the author to think through inputs, outputs, and error conditions, and thus more crisply define the unit’s desired behavior. The cost of finding a bug before coding begins or when the code is first written is considerably lower than the cost of detecting, identifying, and correcting the bug later; bugs may also cause problems for the end-users of the software 1.

Comment:

Krita is a big project and has numerous subsystems that communicate with each other in complicated ways. It makes debugging and testing new code in the application itself difficult. What is more, just compiling and running the entire application to check a one-line change in a small class is very time-consuming. So when writing a new subsystem we usually split it into smaller parts (classes) and test each of them individually. Testing a single class in isolation helps to catch all the corner-cases in the class public interface, e.g. “what happens if we pass 0 here instead of a valid pointer?” or “what if the index we just gave to this method is invalid?”

Changing/refactoring existing code

Wiki:

Unit testing allows the programmer to refactor code or upgrade system libraries at a later date, and make sure the module still works correctly (e.g., in regression testing). The procedure is to write test cases for all functions and methods so that whenever a change causes a fault, it can be quickly identified. Unit tests detect changes which may break a design contract 1.

Comment:

Imagine someone decides to refactor the code you wrote a year ago. How would he know whether his changes didn’t break anything in the internal class structure? Even if he/she asks you, how would you know if the changes to a year-old class, whose details are already forgotten, are valid?

Automated regression testing

Most of our unit tests are run nightly on the CI. You can see the results and coverage reports at https://build.kde.org/job/Extragear/job/krita/.

However, some of the unit tests are not stable enough to be run automatically and therefore are disabled. (They do straightforward QImage comparisons, so the test results can depend no only on version of the libraries installed, but also on build options and even type of CPU the tests are run on.) While the overall coverage is decent, this issue limits the ability of the unit test suite to catch regressions in several parts of the codebase. (More information on that in the respective Phabricator task: https://phabricator.kde.org/T11904.)

How to build and run tests?

Building the tests

To enable unit tests, build Krita with an additional cmake flag: -DBUILD_TESTING=ON.

  1. # example build command
  2. [email protected]:~/kritadev/build>cmake ../krita \
  3. -DCMAKE_INSTALL_PREFIX=$HOME/kritadev/install \
  4. -DCMAKE_BUILD_TYPE=Debug \
  5. -DKRITA_DEVS=ON \
  6. -DBUILD_TESTING=ON

参见

Once built, the tests are run from the the build directory. There you can either run the whole suite at once or you can run a single test (or even a single test with a single data row for data-driven tests).

Run all the tests

  1. # change to the build directory
  2. [email protected]:~/> cd kritadev/build
  3. # run the whole suite
  4. [email protected]:~/kritadev/build> make test

Run a single test

Every test class is built into a separate executable file. This executable file resides in the build directory tree. The relative path is the same as the path in source directory.

To run all tests in a single test class, run the executable:

  1. # running all tests in a test class
  2. [email protected]:~/kritadev/build>./libs/ui/tests/KisSpinBoxSplineUnitConverterTest

You can also run a single test method from the class or invoke the test method with a single test data row, if you have a data-driven test. Add the test method name (and optionally the test data row name) as an argument to the test class executable:

  1. # the syntax for running single tests:
  2. # [email protected]:~/kritadev/build>./test-class-executable "test method name":"data row name"
  3. # run a single method in a test class
  4. [email protected]:~/kritadev/build>./libs/ui/tests/KisSpinBoxSplineUnitConverterTest testCurveCalculationTwoWay
  5. # run a single method in a test class with the selected test data row
  6. [email protected]:~/kritadev/build>./libs/ui/tests/KisSpinBoxSplineUnitConverterTest testCurveCalculationTwoWay:"0.5 in (0, 10) = 5"

Environment variables for running tests

Prior to running the tests, you can set several environment variables to change the behavior of the tests.

  • Suppress safe assert dialogs:

    1. [email protected]:~/kritadev/build> export KRITA_NO_ASSERT_MSG=1
  • Set source directory for QImage-based test data

    1. [email protected]:~/kritadev/build> export KRITA_UNITTESTS_DATA_DIR=<directory>
  • Create reference images for QImage-based tests

    1. [email protected]:~/kritadev/build> export KRITA_WRITE_UNITTESTS=1

When to write a unit test?

Ideally a unit test should be written for any new class that implements some logic and provides any kind of public interface. It is especially true if this public interface is going to be used more that one client-class.

What should unit test include?

  • corner cases. E.g. what happens if we request merging of two layers, one of which has Inherit Alpha option enabled? What properties and composition mode the final layer should have? Answers to these questions should be given and tested in the unit test.

  • non-obvious design decisions. E.g. if a paint device has a non-transparent default pixel, then its `exactBounds()` returns the rect, not smaller that the size of the image, even though technically the device might be empty.

How to write a unittest?

Suppose you want to write a unittest for kritaimage library. You need to perform just a few steps:

  1. Add files for the test class into ./image/tests/ directory:

    kis_some_class_test.h

    1. #ifndef __KIS_SOME_CLASS_TEST_H
    2. #define __KIS_SOME_CLASS_TEST_H
    3. #include <QtTest/QtTest>
    4. class KisSomeClassTest : public QObject
    5. {
    6. Q_OBJECT
    7. private Q_SLOTS:
    8. void test();
    9. };
    10. #endif /* __KIS_SOME_CLASS_TEST_H */</syntaxhighlight>

    kis_some_class_test.cpp

    1. #include "kis_some_class_test.h"
    2. #include <QTest>
    3. void KisSomeClassTest::test()
    4. {
    5. }
    6. QTEST_MAIN(KisSomeClassTest, GUI)</syntaxhighlight>
  2. Modify ./image/tests/CMakeLists.txt to include your new test class:

    1. # ...
    2. ########### next target ###############
    3. set(kis_some_class_test_SRCS kis_some_class_test.cpp )
    4. ecm_add_tests(${kis_some_class_test_SRCS}
    5. NAME_PREFIX "libs-somelib-"
    6. LINK_LIBRARIES kritaimage Qt5::Test)
    7. # ...
  3. Write your test. You can use any macro commands provided by Qt (QVERIFY, QCOMPARE or QBENCHMARK).

    1. void KisSomeClassTest::test()
    2. {
    3. QString cat("cat");
    4. QString dog("dog");
    5. QVERIFY(cat != dog);
    6. QCOMPARE(cat, "cat");
    7. }
  4. Run your test by running an executable in ./image/test/ folder

Krita-specific testing utils

Fetching reference images

All the testing files/images are usually stored in the test’s data folder (e.g. ./krita/image/tests/data/). But there are some files which are used throughout all the unit tests. These files are stored in the global folder ./krita/sdk/tests/data/. If you want to access any file, just use TestUtil::fetchDataFileLazy. It first searches the file in the local test’s folder and if nothing is found checks the global folder.

Example:

  1. QImage refImage(TestUtil::fetchDataFileLazy("lena.png"));
  2. QVERIFY(!refImage.isNull());

Compare test result against a reference QImage

There are two helper functions to compare a given QImage against an image saved in the data folder.

  1. bool TestUtil::checkQImage(const QImage &image, const QString &testName,
  2. const QString &prefix, const QString &name,
  3. int fuzzy = 0, int fuzzyAlpha = -1, int maxNumFailingPixels = 0);
  4. bool TestUtil::checkQImageExternal(const QImage &image, const QString &testName,
  5. const QString &prefix, const QString &name,
  6. int fuzzy = 0, int fuzzyAlpha = -1, int maxNumFailingPixels = 0);

The functions search for a PNG file with path

  1. ./tests/data/<testName>/<prefix>/<prefix>_<name>.png
  2. # or without a subfolder
  3. ./tests/data/<testName>/<prefix>_<name>.png

The supplied QImage is compared against the saved PNG, and the result is returned to the caller. If the images do not coincide, two images are dumped into the current directory: one with actual result and another with what is expected.

The second version of the function is different. It searches the image in “an external repository”. The point is that PNG images occupy quite a lot of space and bloat the repository size. So we decided to put all the images that are big enough (>10KiB) into an external SVN repository. To configure an external test files repository on your computer, please do the following:

  1. Checkout the data repository:

    1. # create the tests data folder and enter it
    2. mkdir ~/testsdata
    3. cd ~/testsdata
    4. # checkout the extra repository
    5. svn checkout svn+ssh://[email protected]/home/kde/trunk/tests/kritatests
  2. Add environment variable pointing to your repository to your ~/.bashrc

    export KRITA_UNITTESTS_DATA_DIR= ~/testsdata/kritatests/unittests

  3. Use TestUtil::checkQImageExternal in your unittest and it will fetch data from the external source. If an external repository is not found then the test is considered “passed”.

QImageBasedTest for complex actions

Sometimes you need to test some complex actions like cropping or transforming the whole image. The main problem of such action is that it should work correctly with any kind of layer or mask, e.g. KisCloneLayer, KisGroupLayer or even KisSelectionMask. To facilitate such complex testing conditions, Krita provides a special class QImageBasedTest. It helps you to create a really complex image and check the contents of its layers. You can find the best example of its usage in KisProcessingsTest. Basically, to use this class, one should derive it’s own testing class from it, and call a set of callbacks, which do all the work. Let’s consider the code from KisProcessingsTest:

  1. // override QImageBasedTest class
  2. class BaseProcessingTest : public TestUtil::QImageBasedTest
  3. {
  4. public:
  5. BaseProcessingTest()
  6. : QImageBasedTest("processings")
  7. {
  8. }
  9. // The method is called by test cases. If the test fails, a set of PNG images
  10. // is saved into working directory
  11. void test(const QString &testname, KisProcessingVisitorSP visitor) {
  12. // create an image and regenerate its projection
  13. KisSurrogateUndoStore *undoStore = new KisSurrogateUndoStore();
  14. KisImageSP image = createImage(undoStore);
  15. image->initialRefreshGraph();
  16. // check if the image is correct before testing anything
  17. QVERIFY(checkLayersInitial(image));
  18. // do the action we are trying to test
  19. KisProcessingApplicator applicator(image, image->root(),
  20. KisProcessingApplicator::RECURSIVE);
  21. applicator.applyVisitor(visitor);
  22. applicator.end();
  23. image->waitForDone();
  24. // check the result, and dump images if something went wrong
  25. QVERIFY(checkLayers(image, testname));
  26. // Check if undo(!) works correctly
  27. undoStore->undo();
  28. image->waitForDone();
  29. if (!checkLayersInitial(image)) {
  30. qWarning() << "NOTE: undo is not completely identical "
  31. << "to the original image. Falling back to "
  32. <<"projection comparison";
  33. QVERIFY(checkLayersInitialRootOnly(image));
  34. }
  35. }
  36. };

MaskParent object

TestUtil::MaskParent is a simple class that, in its constructor, creates an RGB8 image with a single paint layer, which you can use for further testing. The image and the layer can be accessed as simple member variables.

Example:

  1. void KisMaskTest::testCreation()
  2. {
  3. // create an image and a simple layer
  4. TestUtil::MaskParent p;
  5. // create a mask and attach its selection to the created layer
  6. TestMaskSP mask = new TestMask;
  7. mask->initSelection(p.layer);
  8. QCOMPARE(mask->extent(), QRect(0,0,512,512));
  9. QCOMPARE(mask->exactBounds(), QRect(0,0,512,512));
  10. }

1(1,2,3)

https://en.wikipedia.org/wiki/Unit_testing