samedi 30 mai 2020

How to test member-wise equality operator?

I have a structure of three members { xx, xy, yy } and an overloaded == operator that member-wise tests if corresponding members of left-hand and right-hand expressions are either equal within some precision, or are both NaNs. Quite trivial.

For my test case, I wanted to target a typo situation, where I mistakingly compare wrong members. Maybe, I compare xx from left-hand expression with xy from right-hand expression. Maybe, I forgot to compare yy at all.

Since I'm using C++20, I don't know if it's even possible to construct a compile-time proof of correctness of == operator (and if I even should). Trying to solve this in usual manner, I find myself enumerating all possible permutations:

EXPECT_EQ(C{1, 2, 3}, C{1, 2, 3});
EXPECT_NE(C{1, 2, 3}, C{1, 3, 2});
EXPECT_NE(C{1, 2, 3}, C{2, 1, 3});
EXPECT_NE(C{1, 2, 3}, C{2, 3, 1});
EXPECT_NE(C{1, 2, 3}, C{3, 1, 2});
EXPECT_NE(C{1, 2, 3}, C{3, 2, 1});
EXPECT_NE(C{1, 2, 3}, C{1, 2, nan});
EXPECT_NE(C{1, 2, 3}, C{1, nan, 3});
EXPECT_NE(C{1, 2, 3}, C{nan, 2, 3});
// ...

EXPECT_NE(C{1, 3, 2}, C{1, 2, 3});
EXPECT_EQ(C{1, 3, 2}, C{1, 3, 2});
// ...

Such code is quite ugly, and if I replicate the same with nested loops:

for (T lxx = 1; lxx <= 3; lxx += 1) {
  for (T rxx = 1; rxx <= 3; rxx += 1) {
    for (T lxy = 1; lxy <= 3; lxy += 1) {
      for (T rxy = 1; rxy <= 3; rxy += 1) {
        // ...

it just seems that I am reimplementing equality operator in test, which misses the point of testing.

How do I do this correctly? Am I missing some edge cases maybe that would simplify it? How to scale such test if I have four members in a structure and don't want for test case code to explode?

Aucun commentaire:

Enregistrer un commentaire