Skip to content

Commit

Permalink
Change random test shuffling technique
Browse files Browse the repository at this point in the history
Previously a random test ordering was obtained by applying std::shuffle
to the tests in declaration order.  This has two problems:

- It depends on the declaration order, so the order in which the tests
  will be run will be platform-specific.
- When trying to debug accidental inter-test dependencies, it is helpful
  to be able to find a minimal subset of tests which exhibits the issue.
  However, any change to the set of tests being run will completely
  change the test ordering, making it difficult or impossible to reduce
  the set of tests being run in any reasonably efficient manner.

Therefore, change the randomization approach to resolve both these
issues.

Generate a random value based on the user-provided RNG seed.  Convert
every test case to an integer by hashing a combination of that value
with the test name.  Sort the test cases by this integer.

The test names and RNG are platform-independent, so this should be
consistent across platforms.  Also, removing one test does not change
the integer value associated with the remaining tests, so they remain in
the same order.

To hash, use the FNV-1a hash, except with the basis being our randomly
selected value rather than the fixed basis set in the algorithm.  Cannot
use std::hash, because it is important that the result be
platform-independent.
  • Loading branch information
jbytheway committed Apr 10, 2020
1 parent d399a30 commit 293ad88
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion include/internal/catch_test_case_registry_impl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,34 @@
#include "catch_string_manip.h"
#include "catch_test_case_info.h"

#include <random>
#include <sstream>

namespace Catch {

struct CompareTestsUsingRandom {
explicit CompareTestsUsingRandom( Catch::SimplePcg32& rng ) {
std::uniform_int_distribution<uint64_t> dist;
basis = dist( rng );
}

uint64_t basis;

uint64_t fnv_1a_hash( std::string const& s ) const {
static constexpr uint64_t prime = 1099511628211;
uint64_t hash = basis;
for( const char c : s ) {
hash ^= c;
hash *= prime;
}
return hash;
}

bool operator()( TestCase const& l, TestCase const& r ) const {
return fnv_1a_hash( l.name ) < fnv_1a_hash( r.name );
}
};

std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {

std::vector<TestCase> sorted = unsortedTestCases;
Expand All @@ -29,7 +53,7 @@ namespace Catch {
break;
case RunTests::InRandomOrder:
seedRng( config );
std::shuffle( sorted.begin(), sorted.end(), rng() );
std::sort( sorted.begin(), sorted.end(), CompareTestsUsingRandom( rng() ) );
break;
case RunTests::InDeclarationOrder:
// already in declaration order
Expand Down

0 comments on commit 293ad88

Please sign in to comment.