QuickCheck++ 事前条件

ソート関数の適用結果として、先頭要素がリストの最小値であるかどうかのテストを考えます。

#include <vector>
#include <algorithm>
#include <quickcheck/quickcheck.hh>

typedef std::vector<int> Vector;

struct prop_sorted_minimum : public quickcheck::Property<Vector> {
    bool holdsFor(const Vector& xs)
    {
        Vector ys = xs;
        std::sort(ys.begin(), ys.end());
        return ys.front() == *std::min_element(xs.begin(), xs.end());
    }
};

int main()
{
    prop_sorted_minimum().check();
}

このコードでは、ランダムに生成されたテストデータが空のvectorだった場合にクラッシュします。


QuickCheck++では、条件を満たしたテストデータを作成する機能が提供されています。
quickcheck::Propertyを継承したテストクラスで、accepts()関数を定義します。

#include <vector>
#include <algorithm>
#include <quickcheck/quickcheck.hh>

typedef std::vector<int> Vector;

struct prop_sorted_minimum : public quickcheck::Property<Vector> {
    bool accepts(const Vector& xs)
    {
        return !xs.empty();
    }

    bool holdsFor(const Vector& xs)
    {
        Vector ys = xs;
        std::sort(ys.begin(), ys.end());
        return ys.front() == *std::min_element(xs.begin(), xs.end());
    }
};

int main()
{
    prop_sorted_minimum().check();
}
OK, passed 100 tests.


テストデータの詳細を出力すると、空のvectorが生成されていないことが確認できます。

Test 0:
  0: [1732365957, 410726649]
Test 1:
  0: [1116964137, 1395238485]
Test 2:
  0: [380448094, 544162018, 1773589359, 302916640]
Test 3:
  0: [1044675724, 1494659631, 2115304491]
Test 4:
  0: [1831131723, 1791219081]
Test 5:
  0: [1190366698, 1891754373, 2137456335, 2128346553, 1335992134]
Test 6:
  0: [920874443, 855205367, 843605141]
Test 7:
  0: [723605063]
Test 8:
  0: [1391306206, 2024993127, 842490996]
Test 9:
  0: [423899791, 1031043821, 1499050678, 266346439, 586958334, 94702417]
...