Skip to content

Commit

Permalink
Fix indeterministic logging tests
Browse files Browse the repository at this point in the history
Printing the content of hash-based containers doesn't lead always to the same string as their ordering is not fixed. Luckily the number of possible permutations is so small that we can enumerate all of them.

Fixes google#201.
  • Loading branch information
xhochy committed Apr 29, 2019
1 parent 0d0c254 commit 71baeac
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/stl_logging_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -100,29 +100,42 @@ static void TestSTLLogging() {

#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH
{
// hash_set doesn't have an ordering, so there are many options for the output.
vector<string> permutations{
"10 20 30", "10 30 20", "20 10 30", "20 30 10", "30 10 20", "30 20 10"
};
// Test a hashed simple associative container.
hash_set<int> hs;
hs.insert(10);
hs.insert(20);
hs.insert(30);
ostringstream ss;
ss << hs;
EXPECT_EQ(ss.str(), "10 20 30");
EXPECT_TRUE(std::find(std::begin(permutations), std::end(permutations), ss.str()) != std::end(permutations));
hash_set<int> copied_hs(hs);
CHECK_EQ(hs, copied_hs); // This must compile.
}
#endif

#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH
{
// hash_set doesn't have an ordering, so there are many options for the output.
vector<string> permutations{
"(10, ten) (20, twenty) (30, thirty)",
"(10, ten) (30, thirty) (20, twenty)",
"(20, twenty) (10, ten) (30, thirty)",
"(20, twenty) (30, thirty) (10, ten)",
"(30, thirty) (10, ten) (20, twenty)",
"(30, thirty) (20, twenty) (10, ten)"
};
// Test a hashed pair associative container.
hash_map<int, string> hm;
hm[10] = "ten";
hm[20] = "twenty";
hm[30] = "thirty";
ostringstream ss;
ss << hm;
EXPECT_EQ(ss.str(), "(10, ten) (20, twenty) (30, thirty)");
EXPECT_TRUE(std::find(std::begin(permutations), std::end(permutations), ss.str()) != std::end(permutations));
hash_map<int, string> copied_hm(hm);
CHECK_EQ(hm, copied_hm); // this must compile
}
Expand Down Expand Up @@ -162,6 +175,10 @@ static void TestSTLLogging() {

#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH
{
// hash_set doesn't have an ordering, so there are many options for the output.
vector<string> permutations{
"10 20 30", "10 30 20", "20 10 30", "20 30 10", "30 10 20", "30 20 10"
};
// Test a hashed simple associative container.
// Use a user defined hash function.
hash_set<int, user_hash> hs;
Expand All @@ -170,7 +187,7 @@ static void TestSTLLogging() {
hs.insert(30);
ostringstream ss;
ss << hs;
EXPECT_EQ(ss.str(), "10 20 30");
EXPECT_TRUE(std::find(std::begin(permutations), std::end(permutations), ss.str()) != std::end(permutations));
hash_set<int, user_hash> copied_hs(hs);
CHECK_EQ(hs, copied_hs); // This must compile.
}
Expand Down

0 comments on commit 71baeac

Please sign in to comment.