Getting started with unit tests in Qt Creator and Catch

I have written about unit testing in Qt Creator on multiple occasions earlier. Since then, a new testing framework seems to have become a new leader in the field, and that is Catch. It is similar to UnitTest++ and Google’s gtest and brings the best of both worlds. It is header-only and appears to reduce the amount of code that must be written in comparison to the other two.

This is an adopted version my previous posts that shows how to use Catch in a Qt Creator project. It doesn’t any longer integrate the testing output into Qt Creator’s issue pane. Instead I’ve started to rely on Travis CI or Jenkins to run the tests and notify me about any newly introduced errors.

An example project using this code structure has been posted on Github by Filip Sund (thanks, Filip!) and further adapted by us with the move to Catch.

The structure of the project is as follows:

MyProject
├─ MyProject.pro
├─ defaults.pri
├─ app/
│  ├─ app.pro
│  └─ main.cpp
├─ src/
│  ├─ src.pro
│  └─ myclass.cpp
└─ tests/
   ├─ tests.pro
   └─ main.cpp

The main project file, MyProject.pro will now be based on a subdirs template, and may look like this:

TEMPLATE = subdirs
CONFIG+=ordered
SUBDIRS = \
    src \
    app \
    tests
app.depends = src
tests.depends = src

The app.depends and tests.depends statements makes sure that the src project is compiled before the application and tests. This is because the src directory contains the library that will be used by both the app and the tests.

CONFIG+=ordered is needed because depends doesn’t affect the order during make install.

defaults.pri

Each of the other .pro files will include defaults.pri to have all the headers available. defaults.pri contains the following:

INCLUDEPATH += $$PWD/src
SRC_DIR = $$PWD

If the library, main program and tests use common libraries, it is very useful to have the defaults.pri define these dependencies too.

./src

In the src folder, I have myclass.cpp, which is the class that I want to use and test. The src.pro needs to compile to a library, so that it may be used both by app and tests, and could look something like this:

include(../defaults.pri)
CONFIG -= qt

TARGET = myapp
TEMPLATE = lib

SOURCES += myclass.cpp
HEADERS += myclass.h

What this class does is not so interesting, it could be anything. A simple example could be this header file:

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass {
public:
    double addition(double a, double b);
};

#endif // MYCLASS_H

With this accompaning source file:

#include "myclass.h"

double MyClass::addition(double a, double b) {
    return a * b;
}

./app

I only have a main.cpp file in app, because the app is basically just something that uses everything in the src folder. It will depend on the shared compiled library from src, and app.pro would look something like this:

include(../defaults.pri)

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp

LIBS += -L../src -lmyapp

The main.cpp file could be a simple program that uses MyClass:

#include <myclass.h>
#include <iostream>

using namespace std;

int main()
{
    MyClass adder;
    cout << adder.addition(10, 20) << endl;
    return 0;
}

./tests

In the tests folder I have simply added a main.cpp which will run the tests. Then tests.pro has the following contents:

include(../defaults.pri)
TEMPLATE = app

CONFIG   += console
CONFIG   -= app_bundle
CONFIG   -= qt

SOURCES += main.cpp

LIBS += -L../src -lmyapp

Which now links to the myapp library in addition to the unit tests.

The main.cpp in tests file which could contain the following, if we were to use UnitTest++ as our testing library:

#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include <myclass.h>

TEST_CASE( "MyMath", "[mymath]" ) {
    SECTION("Addition") {
        MyClass my;
        REQUIRE(my.addition(3,4) == 7);
    }
}

This test will fail because my implementation of MyClass::addition is completely wrong:

class MyClass {
public:
    double addition(double a, double b) {
        return a * b;
    }
};

Note that I’m including MyClass by through <myclass.h> which is possible because of the INCLUDEPATH variable in defaults.pri.

This should help you define a project that compiles a library, as well as tests and an application using the library.

Why I won’t be starting my next project in Rust

I have been inspired to learn Rust and Julia lately. The idea was to use these promising languages in all of my new projects. I wanted to learn Rust because it is a safe and fast replacement for C++. I wanted to learn Julia because it is a language tailored for scientific use that might someday replace Python.

I quickly realized that I would be learning both for the wrong reason. I already know C++ and Python well, and should be starting important new projects in these languages.

One article that changed my mind was “Criticizing the Rust Language, and Why C/C++ Will Never Die” by Eax Melanhovich. Not all the points Melanhovich makes are longer valid. For instance, the speed of Rust has improved significantly over just the past months. However, he is right in that the number and quality of development tools for Rust is way lower than that of C++. And it is hard to argue with the number of vacant positions for  C++ programmers in comparison to those of Rust and Julia.

This does of course not say anything about the quality of these languages. For all I know, Rust may be (or become) a much safer, faster and elegant language than C++. But I understand that many of the benefits I would get from Rust are already available in the new C++11 and C++14 standards. And from using C++ in a modern way.

I found Rust attractive because of its promise of memory safety. It is designed in a way so that you won’t be able to shoot yourself in the foot as easily as you can in C++. However, I’m currently using pointers in C++ the old-fashioned way. I still work with raw pointers, new and delete when I should be using smart pointers. Sometimes I even use pointers when references and values would be the right choice.

I realize now that I need to start a project or two where I use only modern C++. That should hopefully teach me how to steer clear of those nagging segfaults sometime in the future. I’ll be reporting back here about my experiences and will make a list of some recommendations for others who are trying to do the same.

New project structure for projects in Qt Creator with unit tests

Note: This is a new version of an earlier post, with a revised project structure.

Note 2: See this post for the same project structure using the even better Catch testing framework.

This post assumes that you are using a C++ testing framework such as UnitTest++. See this earlier post for some information on installing UnitTest++ on Ubuntu.

To get the most out UnitTest++ it is a good idea to integrate its output into the Qt Creator IDE. The way I have set this up in Qt Creator is with subprojects. One for the main project, which again is split into the app itself and a library, and one for the tests. In addition, I have a helper project file, named defaults.pri. The structure of the project is like this:

MyProject
├─ MyProject.pro
├─ defaults.pri
├─ app/
│  ├─ app.pro
│  └─ main.cpp
├─ src/
│  ├─ src.pro
│  └─ myclass.cpp
└─ tests/
   ├─ tests.pro
   └─ main.cpp

An example project using this code structure has been posted on Github by Filip Sund. (Thanks to Filip for doing this!)

The main project file, MyProject.pro will now be based on a subdirs template, and may look like this:

TEMPLATE = subdirs
CONFIG+=ordered
SUBDIRS = \
    src \
    app \
    tests
app.depends = src
tests.depends = src

The app.depends and tests.depends statements makes sure that the src project is compiled before the application and tests, because the src directory contains the library that will be used by both the app and the tests.

(Thanks to Will for noting that this works better for parallel builds with make -j 8 than my previous version only using CONFIG+=ordered. We should keep CONFIG+=ordered in there still, though, because depends doesn’t affect the order when using make install).

defaults.pri

Each of the other .pro files will include defaults.pri to have all the headers available. defaults.pri contains the following:

INCLUDEPATH += $$PWD/src
SRC_DIR = $$PWD

If the library, main program and tests use common libraries, it is very useful to have the defaults.pri define these dependencies too.

./src

In the src folder, I have myclass.cpp, which is the class that I want to use and test. The src.pro needs to compile to a library, so that it may be used both by app and tests, and could look something like this:

include(../defaults.pri)
CONFIG -= qt

TARGET = myapp
TEMPLATE = lib

SOURCES += myclass.cpp
HEADERS += myclass.h

What this class does is not so interesting, it could be anything. A simple example could be this header file:

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass {
public:
    double addition(double a, double b);
};

#endif // MYCLASS_H

With this accompaning source file:

#include "myclass.h"

double MyClass::addition(double a, double b) {
    return a * b;
}

./app

I only have a main.cpp file in app, because the app is basically just something that uses everything in the src folder. It will depend on the shared compiled library from src, and app.pro would look something like this:

include(../defaults.pri)

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp

LIBS += -L../src -lmyapp

The main.cpp file could be a simple program that uses MyClass:

#include <myclass.h>
#include <iostream>

using namespace std;

int main()
{
    MyClass adder;
    cout << adder.addition(10, 20) << endl;
    return 0;
}

./tests

In the tests folder I have simply added a main.cpp which will run the tests. Then tests.pro has the following contents:

include(../defaults.pri)
TEMPLATE = app

CONFIG   += console
CONFIG   -= app_bundle
CONFIG   -= qt

SOURCES += main.cpp

LIBS += -lunittest++ -L../src -lmyapp

Which now links to the myapp library in addition to the unit tests.

The main.cpp in tests file which could contain the following, if we were to use UnitTest++ as our testing library:

#include <unittest++/UnitTest++.h>
#include <myclass.h>

TEST(MyMath) {
    MyClass my;
    CHECK(my.addition(3,4) == 7);
}

int main()
{
    return UnitTest::RunAllTests();
}

This test will fail because my implementation of MyClass::addition is completely wrong:

class MyClass {
public:
    double addition(double a, double b) {
        return a * b;
    }
};

Note that I’m including MyClass by through <myclass.h> which is possible because of the INCLUDEPATH variable in defaults.pri.

This is hopefully all you’ll need to define a project that compiles a library, as well as tests and an application using the library.

When variational Monte Carlo becomes visual

Today I was playing around with the output of the code from Jørgen’s thesis, and figured it would be fun to visualize the random walk in the variational Monte Carlo calculation.

For the interested, this is a visualization of a variational Monte Carlo calculation for the hydrogen molecule. The algorithm used is the Metropolis-Hastings algorithm. The two blue spheres represent the atomic nuclei, while the green spheres are the current electron configuration being sampled. The distance between the nuclei is about two times the distance for hydrogen in the ground state. The red spheres represent some of the history of the computation. If the complete history was included, the red spheres could have been interpreted as the electron density, but as you may notice, the history included is too short, so that the electron density fluctuates through the video. (Hint: Look at the density between the atoms – it varies between different times in the video.)

Introducing notes.txt

After discovering todo.txt, I realized that I needed something similar for notes. About a year ago I started working on a similar tool that would enable me to write

n a Cookie recipe

which would open up an editor where I could start writing down the fantastic cookie recipe I had in my head. I’m really no good at cookie recipes, but I tend to want to type down ideas or notes quickly when they are fresh in my mind. Opening up a text-document, saving it somewhere and typing away is usually no problem, but finding these spread out text files later is much more tedious.

So I figured I needed a way to organize this. There are several GUI apps that do this, but I really like the availability of the terminal. todo.txt really showed me how much more efficiently I managed to store and maintain my TODOs, and I wanted to do the same with my notes. This is where notes.txt comes in.

Creating notes

By typing

n a Cookie recipe

in a terminal, vim pops up at the end of a file named 2012-10-30.mkd (the current date) with the cursor ready at a point below a ready-made title:

I am then able to start typing away, and save the document when I’m done.

This makes me satisfied when it comes to typing down things easily.

Opening up an old topic

The next important step is to make it easy to find this cookie recipe at a later point. First I thought file names would do the trick, but I figured that making it easy to search for titles would be way better. If I now type

n e Cookie_recipe

in a terminal, the same document shows up with the cursor placed on the title:

This is of course also works with tab completion, so that if I type

n e Cookie

I may just press Tab to complete Cookie to Cookie_recipe.

Finding notes

If I want to list all my topics, I simply write

n ls

and a list of all topics show up.

If I remember that I wrote something about sugar, but don’t know in which note, I may type

n ls sugar

and note.txt will print out all topics where the word sugar is found somewhere in the text below:

As you see, the titles are listed as Cookie_recipe/Ingredients and Cookie_recipe/Recipe, allowing for you to access subtitles through

n e Cookie_recipe/Ingredients

If there are multiple instances of the same title, let’s say that we have two titles named Cookie_recipe, notes.txt will prompt you to select which topic you would like to open:

The current state of affairs

The application is not quite release-ready yet, but I’m hoping to make an Ubuntu package in a short-term future. In the meantime, you may find the source code for this at my Github account.

 

Nanoparticles game reviewed by Nanoparticles Blog

If you are interested in real-life nanoparticles and not just the game I made with the same name, you should check out Nanoparticles Blog. Run by Niko Bärsch, CEO of Particular GmbH, a company that is in fact making real nanoparticles and nanomaterials in the lab. The blog has a good update frequency with posts about whats going on in the world of nanoparticles. He’s writing about everything from nanoparticle production, health concerns and new applications for both particles and nanomaterials.

Lately, Niko even wrote about the Android version of my game on the blog, which of course makes good reason to link back to them. In addition to the joy of being updated about the subjects I’m studying.