2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2011-2018, The GROMACS development team.
5 * Copyright (c) 2019,2020, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
38 * Implements classes and functions from refdata.h.
40 * \author Teemu Murtola <teemu.murtola@gmail.com>
41 * \ingroup module_testutils
54 #include <gtest/gtest.h>
56 #include "gromacs/options/basicoptions.h"
57 #include "gromacs/options/ioptionscontainer.h"
58 #include "gromacs/utility/any.h"
59 #include "gromacs/utility/exceptions.h"
60 #include "gromacs/utility/gmxassert.h"
61 #include "gromacs/utility/keyvaluetree.h"
62 #include "gromacs/utility/path.h"
63 #include "gromacs/utility/real.h"
64 #include "gromacs/utility/stringutil.h"
66 #include "testutils/refdata_checkers.h"
67 #include "testutils/refdata_impl.h"
68 #include "testutils/refdata_xml.h"
69 #include "testutils/testasserts.h"
70 #include "testutils/testexceptions.h"
71 #include "testutils/testfilemanager.h"
78 /********************************************************************
79 * TestReferenceData::Impl declaration
86 * Private implementation class for TestReferenceData.
88 * \ingroup module_testutils
90 class TestReferenceDataImpl
93 //! Initializes a checker in the given mode.
94 TestReferenceDataImpl(ReferenceDataMode mode
, bool bSelfTestMode
);
96 //! Performs final reference data processing when test ends.
97 void onTestEnd(bool testPassed
);
99 //! Full path of the reference data file.
100 std::string fullFilename_
;
102 * Root entry for comparing the reference data.
104 * Null after construction iff in compare mode and reference data was
105 * not loaded successfully.
106 * In all write modes, copies are present for nodes added to
107 * \a outputRootEntry_, and ReferenceDataEntry::correspondingOutputEntry()
108 * points to the copy in the output tree.
110 ReferenceDataEntry::EntryPointer compareRootEntry_
;
112 * Root entry for writing new reference data.
114 * Null if only comparing against existing data. Otherwise, starts
116 * When creating new reference data, this is maintained as a copy of
117 * \a compareRootEntry_.
118 * When updating existing data, entries are added either by copying
119 * from \a compareRootEntry_ (if they exist and comparison passes), or
120 * by creating new ones.
122 ReferenceDataEntry::EntryPointer outputRootEntry_
;
124 * Whether updating existing reference data.
126 bool updateMismatchingEntries_
;
127 //! `true` if self-testing (enables extra failure messages).
130 * Whether any reference checkers have been created for this data.
135 } // namespace internal
137 /********************************************************************
144 //! Convenience typedef for a smart pointer to TestReferenceDataImpl.
145 typedef std::shared_ptr
<internal::TestReferenceDataImpl
> TestReferenceDataImplPointer
;
148 * Global reference data instance.
150 * The object is created when the test creates a TestReferenceData, and the
151 * object is destructed (and other post-processing is done) at the end of each
152 * test by ReferenceDataTestEventListener (which is installed as a Google Test
155 TestReferenceDataImplPointer g_referenceData
;
156 //! Global reference data mode set with setReferenceDataMode().
157 ReferenceDataMode g_referenceDataMode
= ReferenceDataMode::Compare
;
159 //! Returns the global reference data mode.
160 ReferenceDataMode
getReferenceDataMode()
162 return g_referenceDataMode
;
165 //! Returns a reference to the global reference data object.
166 TestReferenceDataImplPointer
initReferenceDataInstance()
168 GMX_RELEASE_ASSERT(!g_referenceData
, "Test cannot create multiple TestReferenceData instances");
169 g_referenceData
.reset(new internal::TestReferenceDataImpl(getReferenceDataMode(), false));
170 return g_referenceData
;
173 //! Handles reference data creation for self-tests.
174 TestReferenceDataImplPointer
initReferenceDataInstanceForSelfTest(ReferenceDataMode mode
)
178 GMX_RELEASE_ASSERT(g_referenceData
.unique(),
179 "Test cannot create multiple TestReferenceData instances");
180 g_referenceData
->onTestEnd(true);
181 g_referenceData
.reset();
183 g_referenceData
.reset(new internal::TestReferenceDataImpl(mode
, true));
184 return g_referenceData
;
187 class ReferenceDataTestEventListener
: public ::testing::EmptyTestEventListener
190 void OnTestEnd(const ::testing::TestInfo
& test_info
) override
194 GMX_RELEASE_ASSERT(g_referenceData
.unique(), "Test leaked TestRefeferenceData objects");
195 g_referenceData
->onTestEnd(test_info
.result()->Passed());
196 g_referenceData
.reset();
200 void OnTestProgramEnd(const ::testing::UnitTest
& /*unused*/) override
202 // Could be used e.g. to free internal buffers allocated by an XML parsing library
206 //! Formats a path to a reference data entry with a non-null id.
207 std::string
formatEntryPath(const std::string
& prefix
, const std::string
& id
)
209 return prefix
+ "/" + id
;
212 //! Formats a path to a reference data entry with a null id.
213 std::string
formatSequenceEntryPath(const std::string
& prefix
, int seqIndex
)
215 return formatString("%s/[%d]", prefix
.c_str(), seqIndex
+ 1);
218 //! Finds all entries that have not been checked under a given root.
219 void gatherUnusedEntries(const ReferenceDataEntry
& root
,
220 const std::string
& rootPath
,
221 std::vector
<std::string
>* unusedPaths
)
223 if (!root
.hasBeenChecked())
225 unusedPaths
->push_back(rootPath
);
229 for (const auto& child
: root
.children())
232 if (child
->id().empty())
234 path
= formatSequenceEntryPath(rootPath
, seqIndex
);
239 path
= formatEntryPath(rootPath
, child
->id());
241 gatherUnusedEntries(*child
, path
, unusedPaths
);
245 //! Produces a GTest assertion of any entries under given root have not been checked.
246 void checkUnusedEntries(const ReferenceDataEntry
& root
, const std::string
& rootPath
)
248 std::vector
<std::string
> unusedPaths
;
249 gatherUnusedEntries(root
, rootPath
, &unusedPaths
);
250 if (!unusedPaths
.empty())
253 if (unusedPaths
.size() > 5)
255 paths
= joinStrings(unusedPaths
.begin(), unusedPaths
.begin() + 5, "\n ");
256 paths
= " " + paths
+ "\n ...";
260 paths
= joinStrings(unusedPaths
.begin(), unusedPaths
.end(), "\n ");
263 ADD_FAILURE() << "Reference data items not used in test:" << std::endl
<< paths
;
269 void initReferenceData(IOptionsContainer
* options
)
271 static const gmx::EnumerationArray
<ReferenceDataMode
, const char*> s_refDataNames
= {
272 { "check", "create", "update-changed", "update-all" }
274 options
->addOption(EnumOption
<ReferenceDataMode
>("ref-data")
275 .enumValue(s_refDataNames
)
276 .store(&g_referenceDataMode
)
277 .description("Operation mode for tests that use reference data"));
278 ::testing::UnitTest::GetInstance()->listeners().Append(new ReferenceDataTestEventListener
);
281 /********************************************************************
282 * TestReferenceDataImpl definition
288 TestReferenceDataImpl::TestReferenceDataImpl(ReferenceDataMode mode
, bool bSelfTestMode
) :
289 updateMismatchingEntries_(false),
290 bSelfTestMode_(bSelfTestMode
),
293 const std::string dirname
= bSelfTestMode
? TestFileManager::getGlobalOutputTempDirectory()
294 : TestFileManager::getInputDataDirectory();
295 const std::string filename
= TestFileManager::getTestSpecificFileName(".xml");
296 fullFilename_
= Path::join(dirname
, "refdata", filename
);
300 case ReferenceDataMode::Compare
:
301 if (File::exists(fullFilename_
, File::throwOnError
))
303 compareRootEntry_
= readReferenceDataFile(fullFilename_
);
306 case ReferenceDataMode::CreateMissing
:
307 if (File::exists(fullFilename_
, File::throwOnError
))
309 compareRootEntry_
= readReferenceDataFile(fullFilename_
);
313 compareRootEntry_
= ReferenceDataEntry::createRoot();
314 outputRootEntry_
= ReferenceDataEntry::createRoot();
317 case ReferenceDataMode::UpdateChanged
:
318 if (File::exists(fullFilename_
, File::throwOnError
))
320 compareRootEntry_
= readReferenceDataFile(fullFilename_
);
324 compareRootEntry_
= ReferenceDataEntry::createRoot();
326 outputRootEntry_
= ReferenceDataEntry::createRoot();
327 updateMismatchingEntries_
= true;
329 case ReferenceDataMode::UpdateAll
:
330 compareRootEntry_
= ReferenceDataEntry::createRoot();
331 outputRootEntry_
= ReferenceDataEntry::createRoot();
333 case ReferenceDataMode::Count
: GMX_THROW(InternalError("Invalid reference data mode"));
337 void TestReferenceDataImpl::onTestEnd(bool testPassed
)
343 // TODO: Only write the file with update-changed if there were actual changes.
344 if (outputRootEntry_
)
348 std::string dirname
= Path::getParentPath(fullFilename_
);
349 if (!Directory::exists(dirname
))
351 if (Directory::create(dirname
) != 0)
353 GMX_THROW(TestException("Creation of reference data directory failed: " + dirname
));
356 writeReferenceDataFile(fullFilename_
, *outputRootEntry_
);
359 else if (compareRootEntry_
)
361 checkUnusedEntries(*compareRootEntry_
, "");
365 } // namespace internal
368 /********************************************************************
369 * TestReferenceChecker::Impl
373 * Private implementation class for TestReferenceChecker.
375 * \ingroup module_testutils
377 class TestReferenceChecker::Impl
380 //! String constant for naming XML elements for boolean values.
381 static const char* const cBooleanNodeName
;
382 //! String constant for naming XML elements for string values.
383 static const char* const cStringNodeName
;
384 //! String constant for naming XML elements for unsigned char values.
385 static const char* const cUCharNodeName
;
386 //! String constant for naming XML elements for integer values.
387 static const char* const cIntegerNodeName
;
388 //! String constant for naming XML elements for int32 values.
389 static const char* const cInt32NodeName
;
390 //! String constant for naming XML elements for unsigned int32 values.
391 static const char* const cUInt32NodeName
;
392 //! String constant for naming XML elements for int32 values.
393 static const char* const cInt64NodeName
;
394 //! String constant for naming XML elements for unsigned int64 values.
395 static const char* const cUInt64NodeName
;
396 //! String constant for naming XML elements for floating-point values.
397 static const char* const cRealNodeName
;
398 //! String constant for naming XML attribute for value identifiers.
399 static const char* const cIdAttrName
;
400 //! String constant for naming compounds for vectors.
401 static const char* const cVectorType
;
402 //! String constant for naming compounds for key-value tree objects.
403 static const char* const cObjectType
;
404 //! String constant for naming compounds for sequences.
405 static const char* const cSequenceType
;
406 //! String constant for value identifier for sequence length.
407 static const char* const cSequenceLengthName
;
409 //! Creates a checker that does nothing.
410 explicit Impl(bool initialized
);
411 //! Creates a checker with a given root entry.
412 Impl(const std::string
& path
,
413 ReferenceDataEntry
* compareRootEntry
,
414 ReferenceDataEntry
* outputRootEntry
,
415 bool updateMismatchingEntries
,
417 const FloatingPointTolerance
& defaultTolerance
);
419 //! Returns the path of this checker with \p id appended.
420 std::string
appendPath(const char* id
) const;
422 //! Creates an entry with given parameters and fills it with \p checker.
423 static ReferenceDataEntry::EntryPointer
createEntry(const char* type
,
425 const IReferenceDataEntryChecker
& checker
)
427 ReferenceDataEntry::EntryPointer
entry(new ReferenceDataEntry(type
, id
));
428 checker
.fillEntry(entry
.get());
431 //! Checks an entry for correct type and using \p checker.
432 static ::testing::AssertionResult
checkEntry(const ReferenceDataEntry
& entry
,
433 const std::string
& fullId
,
435 const IReferenceDataEntryChecker
& checker
)
437 if (entry
.type() != type
)
439 return ::testing::AssertionFailure() << "Mismatching reference data item type" << std::endl
440 << " In item: " << fullId
<< std::endl
441 << " Actual: " << type
<< std::endl
442 << "Reference: " << entry
.type();
444 return checker
.checkEntry(entry
, fullId
);
446 //! Finds an entry by id and updates the last found entry pointer.
447 ReferenceDataEntry
* findEntry(const char* id
);
449 * Finds/creates a reference data entry to match against.
451 * \param[in] type Type of entry to create.
452 * \param[in] id Unique identifier of the entry (can be NULL, in
453 * which case the next entry without an id is matched).
454 * \param[out] checker Checker to use for filling out created entries.
455 * \returns Matching entry, or NULL if no matching entry found
456 * (NULL is never returned in write mode; new entries are created
459 ReferenceDataEntry
* findOrCreateEntry(const char* type
,
461 const IReferenceDataEntryChecker
& checker
);
463 * Helper method for checking a reference data value.
465 * \param[in] name Type of entry to find.
466 * \param[in] id Unique identifier of the entry (can be NULL, in
467 * which case the next entry without an id is matched).
468 * \param[in] checker Checker that provides logic specific to the
470 * \returns Whether the reference data matched, including details
471 * of the mismatch if the comparison failed.
472 * \throws TestException if there is a problem parsing the
475 * Performs common tasks in checking a reference value, such as
476 * finding or creating the correct entry.
477 * Caller needs to provide a checker object that provides the string
478 * value for a newly created entry and performs the actual comparison
479 * against a found entry.
481 ::testing::AssertionResult
processItem(const char* name
,
483 const IReferenceDataEntryChecker
& checker
);
485 * Whether the checker is initialized.
487 bool initialized() const { return initialized_
; }
489 * Whether the checker should ignore all validation calls.
491 * This is used to ignore any calls within compounds for which
492 * reference data could not be found, such that only one error is
493 * issued for the missing compound, instead of every individual value.
495 bool shouldIgnore() const
497 GMX_RELEASE_ASSERT(initialized(), "Accessing uninitialized reference data checker.");
498 return compareRootEntry_
== nullptr;
501 //! Whether initialized with other means than the default constructor.
503 //! Default floating-point comparison tolerance.
504 FloatingPointTolerance defaultTolerance_
;
506 * Human-readable path to the root node of this checker.
508 * For the root checker, this will be "/", and for each compound, the
509 * id of the compound is added. Used for reporting comparison
514 * Current entry under which reference data is searched for comparison.
516 * Points to either the TestReferenceDataImpl::compareRootEntry_, or to
517 * a compound entry in the tree rooted at that entry.
519 * Can be NULL, in which case this checker does nothing (doesn't even
520 * report errors, see shouldIgnore()).
522 ReferenceDataEntry
* compareRootEntry_
;
524 * Current entry under which entries for writing are created.
526 * Points to either the TestReferenceDataImpl::outputRootEntry_, or to
527 * a compound entry in the tree rooted at that entry. NULL if only
528 * comparing, or if shouldIgnore() returns `false`.
530 ReferenceDataEntry
* outputRootEntry_
;
532 * Iterator to a child of \a compareRootEntry_ that was last found.
534 * If `compareRootEntry_->isValidChild()` returns false, no entry has
536 * After every check, is updated to point to the entry that was used
538 * Subsequent checks start the search for the matching node on this
541 ReferenceDataEntry::ChildIterator lastFoundEntry_
;
543 * Whether the reference data is being written (true) or compared
546 bool updateMismatchingEntries_
;
547 //! `true` if self-testing (enables extra failure messages).
550 * Current number of unnamed elements in a sequence.
552 * It is the index of the current unnamed element.
557 const char* const TestReferenceChecker::Impl::cBooleanNodeName
= "Bool";
558 const char* const TestReferenceChecker::Impl::cStringNodeName
= "String";
559 const char* const TestReferenceChecker::Impl::cUCharNodeName
= "UChar";
560 const char* const TestReferenceChecker::Impl::cIntegerNodeName
= "Int";
561 const char* const TestReferenceChecker::Impl::cInt32NodeName
= "Int32";
562 const char* const TestReferenceChecker::Impl::cUInt32NodeName
= "UInt32";
563 const char* const TestReferenceChecker::Impl::cInt64NodeName
= "Int64";
564 const char* const TestReferenceChecker::Impl::cUInt64NodeName
= "UInt64";
565 const char* const TestReferenceChecker::Impl::cRealNodeName
= "Real";
566 const char* const TestReferenceChecker::Impl::cIdAttrName
= "Name";
567 const char* const TestReferenceChecker::Impl::cVectorType
= "Vector";
568 const char* const TestReferenceChecker::Impl::cObjectType
= "Object";
569 const char* const TestReferenceChecker::Impl::cSequenceType
= "Sequence";
570 const char* const TestReferenceChecker::Impl::cSequenceLengthName
= "Length";
573 TestReferenceChecker::Impl::Impl(bool initialized
) :
574 initialized_(initialized
),
575 defaultTolerance_(defaultRealTolerance()),
576 compareRootEntry_(nullptr),
577 outputRootEntry_(nullptr),
578 updateMismatchingEntries_(false),
579 bSelfTestMode_(false),
585 TestReferenceChecker::Impl::Impl(const std::string
& path
,
586 ReferenceDataEntry
* compareRootEntry
,
587 ReferenceDataEntry
* outputRootEntry
,
588 bool updateMismatchingEntries
,
590 const FloatingPointTolerance
& defaultTolerance
) :
592 defaultTolerance_(defaultTolerance
),
594 compareRootEntry_(compareRootEntry
),
595 outputRootEntry_(outputRootEntry
),
596 lastFoundEntry_(compareRootEntry
->children().end()),
597 updateMismatchingEntries_(updateMismatchingEntries
),
598 bSelfTestMode_(bSelfTestMode
),
604 std::string
TestReferenceChecker::Impl::appendPath(const char* id
) const
606 return id
!= nullptr ? formatEntryPath(path_
, id
) : formatSequenceEntryPath(path_
, seqIndex_
);
610 ReferenceDataEntry
* TestReferenceChecker::Impl::findEntry(const char* id
)
612 ReferenceDataEntry::ChildIterator entry
= compareRootEntry_
->findChild(id
, lastFoundEntry_
);
613 seqIndex_
= (id
== nullptr) ? seqIndex_
+ 1 : -1;
614 if (compareRootEntry_
->isValidChild(entry
))
616 lastFoundEntry_
= entry
;
622 ReferenceDataEntry
* TestReferenceChecker::Impl::findOrCreateEntry(const char* type
,
624 const IReferenceDataEntryChecker
& checker
)
626 ReferenceDataEntry
* entry
= findEntry(id
);
627 if (entry
== nullptr && outputRootEntry_
!= nullptr)
629 lastFoundEntry_
= compareRootEntry_
->addChild(createEntry(type
, id
, checker
));
630 entry
= lastFoundEntry_
->get();
635 ::testing::AssertionResult
TestReferenceChecker::Impl::processItem(const char* type
,
637 const IReferenceDataEntryChecker
& checker
)
641 return ::testing::AssertionSuccess();
643 std::string fullId
= appendPath(id
);
644 ReferenceDataEntry
* entry
= findOrCreateEntry(type
, id
, checker
);
645 if (entry
== nullptr)
647 return ::testing::AssertionFailure() << "Reference data item " << fullId
<< " not found";
650 ::testing::AssertionResult
result(checkEntry(*entry
, fullId
, type
, checker
));
651 if (outputRootEntry_
!= nullptr && entry
->correspondingOutputEntry() == nullptr)
653 if (!updateMismatchingEntries_
|| result
)
655 outputRootEntry_
->addChild(entry
->cloneToOutputEntry());
659 ReferenceDataEntry::EntryPointer
outputEntry(createEntry(type
, id
, checker
));
660 entry
->setCorrespondingOutputEntry(outputEntry
.get());
661 outputRootEntry_
->addChild(move(outputEntry
));
662 return ::testing::AssertionSuccess();
665 if (bSelfTestMode_
&& !result
)
667 ReferenceDataEntry
expected(type
, id
);
668 checker
.fillEntry(&expected
);
670 << "String value: '" << expected
.value() << "'" << std::endl
671 << " Ref. string: '" << entry
->value() << "'";
677 /********************************************************************
681 TestReferenceData::TestReferenceData() : impl_(initReferenceDataInstance()) {}
684 TestReferenceData::TestReferenceData(ReferenceDataMode mode
) :
685 impl_(initReferenceDataInstanceForSelfTest(mode
))
690 TestReferenceData::~TestReferenceData() {}
693 TestReferenceChecker
TestReferenceData::rootChecker()
695 if (!impl_
->bInUse_
&& !impl_
->compareRootEntry_
)
697 ADD_FAILURE() << "Reference data file not found: " << impl_
->fullFilename_
;
699 impl_
->bInUse_
= true;
700 if (!impl_
->compareRootEntry_
)
702 return TestReferenceChecker(new TestReferenceChecker::Impl(true));
704 impl_
->compareRootEntry_
->setChecked();
705 return TestReferenceChecker(new TestReferenceChecker::Impl(
706 "", impl_
->compareRootEntry_
.get(), impl_
->outputRootEntry_
.get(),
707 impl_
->updateMismatchingEntries_
, impl_
->bSelfTestMode_
, defaultRealTolerance()));
711 /********************************************************************
712 * TestReferenceChecker
715 TestReferenceChecker::TestReferenceChecker() : impl_(new Impl(false)) {}
717 TestReferenceChecker::TestReferenceChecker(Impl
* impl
) : impl_(impl
) {}
719 TestReferenceChecker::TestReferenceChecker(const TestReferenceChecker
& other
) :
720 impl_(new Impl(*other
.impl_
))
724 TestReferenceChecker::TestReferenceChecker(TestReferenceChecker
&& other
) noexcept
:
725 impl_(std::move(other
.impl_
))
729 TestReferenceChecker
& TestReferenceChecker::operator=(TestReferenceChecker
&& other
) noexcept
731 impl_
= std::move(other
.impl_
);
735 TestReferenceChecker::~TestReferenceChecker() {}
737 bool TestReferenceChecker::isValid() const
739 return impl_
->initialized();
743 void TestReferenceChecker::setDefaultTolerance(const FloatingPointTolerance
& tolerance
)
745 impl_
->defaultTolerance_
= tolerance
;
749 void TestReferenceChecker::checkUnusedEntries()
751 if (impl_
->compareRootEntry_
)
753 gmx::test::checkUnusedEntries(*impl_
->compareRootEntry_
, impl_
->path_
);
754 // Mark them checked so that they are reported only once.
755 impl_
->compareRootEntry_
->setCheckedIncludingChildren();
760 bool TestReferenceChecker::checkPresent(bool bPresent
, const char* id
)
762 if (impl_
->shouldIgnore() || impl_
->outputRootEntry_
!= nullptr)
766 ReferenceDataEntry::ChildIterator entry
=
767 impl_
->compareRootEntry_
->findChild(id
, impl_
->lastFoundEntry_
);
768 const bool bFound
= impl_
->compareRootEntry_
->isValidChild(entry
);
769 if (bFound
!= bPresent
)
771 ADD_FAILURE() << "Mismatch while checking reference data item '" << impl_
->appendPath(id
) << "'\n"
772 << "Expected: " << (bPresent
? "it is present.\n" : "it is absent.\n")
773 << " Actual: " << (bFound
? "it is present." : "it is absent.");
775 if (bFound
&& bPresent
)
777 impl_
->lastFoundEntry_
= entry
;
784 TestReferenceChecker
TestReferenceChecker::checkCompound(const char* type
, const char* id
)
786 if (impl_
->shouldIgnore())
788 return TestReferenceChecker(new Impl(true));
790 std::string fullId
= impl_
->appendPath(id
);
792 ReferenceDataEntry
* entry
= impl_
->findOrCreateEntry(type
, id
, checker
);
793 if (entry
== nullptr)
795 ADD_FAILURE() << "Reference data item " << fullId
<< " not found";
796 return TestReferenceChecker(new Impl(true));
799 if (impl_
->updateMismatchingEntries_
)
801 entry
->makeCompound(type
);
805 ::testing::AssertionResult
result(impl_
->checkEntry(*entry
, fullId
, type
, checker
));
806 EXPECT_PLAIN(result
);
809 return TestReferenceChecker(new Impl(true));
812 if (impl_
->outputRootEntry_
!= nullptr && entry
->correspondingOutputEntry() == nullptr)
814 impl_
->outputRootEntry_
->addChild(entry
->cloneToOutputEntry());
816 return TestReferenceChecker(new Impl(fullId
, entry
, entry
->correspondingOutputEntry(),
817 impl_
->updateMismatchingEntries_
, impl_
->bSelfTestMode_
,
818 impl_
->defaultTolerance_
));
821 TestReferenceChecker
TestReferenceChecker::checkCompound(const char* type
, const std::string
& id
)
823 return checkCompound(type
, id
.c_str());
826 /*! \brief Throw a TestException if the caller tries to write particular refdata that can't work.
828 * If the string to write is non-empty and has only whitespace,
829 * TinyXML2 can't read it correctly, so throw an exception for this
830 * case, so that we can't accidentally use it and run into mysterious
833 * \todo Eliminate this limitation of TinyXML2. See
834 * e.g. https://github.com/leethomason/tinyxml2/issues/432
836 static void throwIfNonEmptyAndOnlyWhitespace(const std::string
& s
, const char* id
)
838 if (!s
.empty() && std::all_of(s
.cbegin(), s
.cend(), [](const char& c
) { return std::isspace(c
); }))
840 std::string
message("String '" + s
+ "' with ");
841 message
+= (id
!= nullptr) ? "null " : "";
843 message
+= (id
!= nullptr) ? "" : id
;
845 " cannot be handled. We must refuse to write a refdata String"
846 "field for a non-empty string that contains only whitespace, "
847 "because it will not be read correctly by TinyXML2.";
848 GMX_THROW(TestException(message
));
852 void TestReferenceChecker::checkBoolean(bool value
, const char* id
)
854 EXPECT_PLAIN(impl_
->processItem(Impl::cBooleanNodeName
, id
,
855 ExactStringChecker(value
? "true" : "false")));
859 void TestReferenceChecker::checkString(const char* value
, const char* id
)
861 throwIfNonEmptyAndOnlyWhitespace(value
, id
);
862 EXPECT_PLAIN(impl_
->processItem(Impl::cStringNodeName
, id
, ExactStringChecker(value
)));
866 void TestReferenceChecker::checkString(const std::string
& value
, const char* id
)
868 throwIfNonEmptyAndOnlyWhitespace(value
, id
);
869 EXPECT_PLAIN(impl_
->processItem(Impl::cStringNodeName
, id
, ExactStringChecker(value
)));
873 void TestReferenceChecker::checkTextBlock(const std::string
& value
, const char* id
)
875 EXPECT_PLAIN(impl_
->processItem(Impl::cStringNodeName
, id
, ExactStringBlockChecker(value
)));
879 void TestReferenceChecker::checkUChar(unsigned char value
, const char* id
)
881 EXPECT_PLAIN(impl_
->processItem(Impl::cUCharNodeName
, id
,
882 ExactStringChecker(formatString("%d", value
))));
885 void TestReferenceChecker::checkInteger(int value
, const char* id
)
887 EXPECT_PLAIN(impl_
->processItem(Impl::cIntegerNodeName
, id
,
888 ExactStringChecker(formatString("%d", value
))));
891 void TestReferenceChecker::checkInt32(int32_t value
, const char* id
)
893 EXPECT_PLAIN(impl_
->processItem(Impl::cInt32NodeName
, id
,
894 ExactStringChecker(formatString("%" PRId32
, value
))));
897 void TestReferenceChecker::checkUInt32(uint32_t value
, const char* id
)
899 EXPECT_PLAIN(impl_
->processItem(Impl::cUInt32NodeName
, id
,
900 ExactStringChecker(formatString("%" PRIu32
, value
))));
903 void TestReferenceChecker::checkInt64(int64_t value
, const char* id
)
905 EXPECT_PLAIN(impl_
->processItem(Impl::cInt64NodeName
, id
,
906 ExactStringChecker(formatString("%" PRId64
, value
))));
909 void TestReferenceChecker::checkUInt64(uint64_t value
, const char* id
)
911 EXPECT_PLAIN(impl_
->processItem(Impl::cUInt64NodeName
, id
,
912 ExactStringChecker(formatString("%" PRIu64
, value
))));
915 void TestReferenceChecker::checkDouble(double value
, const char* id
)
917 FloatingPointChecker
<double> checker(value
, impl_
->defaultTolerance_
);
918 EXPECT_PLAIN(impl_
->processItem(Impl::cRealNodeName
, id
, checker
));
922 void TestReferenceChecker::checkFloat(float value
, const char* id
)
924 FloatingPointChecker
<float> checker(value
, impl_
->defaultTolerance_
);
925 EXPECT_PLAIN(impl_
->processItem(Impl::cRealNodeName
, id
, checker
));
929 void TestReferenceChecker::checkReal(float value
, const char* id
)
931 checkFloat(value
, id
);
935 void TestReferenceChecker::checkReal(double value
, const char* id
)
937 checkDouble(value
, id
);
941 void TestReferenceChecker::checkRealFromString(const std::string
& value
, const char* id
)
943 FloatingPointFromStringChecker
<real
> checker(value
, impl_
->defaultTolerance_
);
944 EXPECT_PLAIN(impl_
->processItem(Impl::cRealNodeName
, id
, checker
));
948 void TestReferenceChecker::checkVector(const int value
[3], const char* id
)
950 TestReferenceChecker
compound(checkCompound(Impl::cVectorType
, id
));
951 compound
.checkInteger(value
[0], "X");
952 compound
.checkInteger(value
[1], "Y");
953 compound
.checkInteger(value
[2], "Z");
957 void TestReferenceChecker::checkVector(const float value
[3], const char* id
)
959 TestReferenceChecker
compound(checkCompound(Impl::cVectorType
, id
));
960 compound
.checkReal(value
[0], "X");
961 compound
.checkReal(value
[1], "Y");
962 compound
.checkReal(value
[2], "Z");
966 void TestReferenceChecker::checkVector(const double value
[3], const char* id
)
968 TestReferenceChecker
compound(checkCompound(Impl::cVectorType
, id
));
969 compound
.checkReal(value
[0], "X");
970 compound
.checkReal(value
[1], "Y");
971 compound
.checkReal(value
[2], "Z");
975 void TestReferenceChecker::checkAny(const Any
& any
, const char* id
)
977 if (any
.isType
<bool>())
979 checkBoolean(any
.cast
<bool>(), id
);
981 else if (any
.isType
<int>())
983 checkInteger(any
.cast
<int>(), id
);
985 else if (any
.isType
<int32_t>())
987 checkInt32(any
.cast
<int32_t>(), id
);
989 else if (any
.isType
<uint32_t>())
991 checkInt32(any
.cast
<uint32_t>(), id
);
993 else if (any
.isType
<int64_t>())
995 checkInt64(any
.cast
<int64_t>(), id
);
997 else if (any
.isType
<uint64_t>())
999 checkInt64(any
.cast
<uint64_t>(), id
);
1001 else if (any
.isType
<float>())
1003 checkFloat(any
.cast
<float>(), id
);
1005 else if (any
.isType
<double>())
1007 checkDouble(any
.cast
<double>(), id
);
1009 else if (any
.isType
<std::string
>())
1011 checkString(any
.cast
<std::string
>(), id
);
1015 GMX_THROW(TestException("Unsupported any type"));
1020 void TestReferenceChecker::checkKeyValueTreeObject(const KeyValueTreeObject
& tree
, const char* id
)
1022 TestReferenceChecker
compound(checkCompound(Impl::cObjectType
, id
));
1023 for (const auto& prop
: tree
.properties())
1025 compound
.checkKeyValueTreeValue(prop
.value(), prop
.key().c_str());
1027 compound
.checkUnusedEntries();
1031 void TestReferenceChecker::checkKeyValueTreeValue(const KeyValueTreeValue
& value
, const char* id
)
1033 if (value
.isObject())
1035 checkKeyValueTreeObject(value
.asObject(), id
);
1037 else if (value
.isArray())
1039 const auto& values
= value
.asArray().values();
1040 checkSequence(values
.begin(), values
.end(), id
);
1044 checkAny(value
.asAny(), id
);
1049 TestReferenceChecker
TestReferenceChecker::checkSequenceCompound(const char* id
, size_t length
)
1051 TestReferenceChecker
compound(checkCompound(Impl::cSequenceType
, id
));
1052 compound
.checkInteger(static_cast<int>(length
), Impl::cSequenceLengthName
);
1057 unsigned char TestReferenceChecker::readUChar(const char* id
)
1059 if (impl_
->shouldIgnore())
1061 GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1064 EXPECT_PLAIN(impl_
->processItem(Impl::cUCharNodeName
, id
, ValueExtractor
<int>(&value
)));
1069 int TestReferenceChecker::readInteger(const char* id
)
1071 if (impl_
->shouldIgnore())
1073 GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1076 EXPECT_PLAIN(impl_
->processItem(Impl::cIntegerNodeName
, id
, ValueExtractor
<int>(&value
)));
1081 int32_t TestReferenceChecker::readInt32(const char* id
)
1083 if (impl_
->shouldIgnore())
1085 GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1088 EXPECT_PLAIN(impl_
->processItem(Impl::cInt32NodeName
, id
, ValueExtractor
<int32_t>(&value
)));
1093 int64_t TestReferenceChecker::readInt64(const char* id
)
1095 if (impl_
->shouldIgnore())
1097 GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1100 EXPECT_PLAIN(impl_
->processItem(Impl::cInt64NodeName
, id
, ValueExtractor
<int64_t>(&value
)));
1105 float TestReferenceChecker::readFloat(const char* id
)
1107 if (impl_
->shouldIgnore())
1109 GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1112 EXPECT_PLAIN(impl_
->processItem(Impl::cRealNodeName
, id
, ValueExtractor
<float>(&value
)));
1117 double TestReferenceChecker::readDouble(const char* id
)
1119 if (impl_
->shouldIgnore())
1121 GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1124 EXPECT_PLAIN(impl_
->processItem(Impl::cRealNodeName
, id
, ValueExtractor
<double>(&value
)));
1129 std::string
TestReferenceChecker::readString(const char* id
)
1131 if (impl_
->shouldIgnore())
1133 GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1136 EXPECT_PLAIN(impl_
->processItem(Impl::cStringNodeName
, id
, ValueExtractor
<std::string
>(&value
)));