Merge branch 'origin/release-2020' into master
[alexxy/gromacs.git] / src / testutils / refdata.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
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.
9  *
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.
14  *
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.
19  *
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.
24  *
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.
32  *
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.
35  */
36 /*! \internal \file
37  * \brief
38  * Implements classes and functions from refdata.h.
39  *
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  * \ingroup module_testutils
42  */
43 #include "gmxpre.h"
44
45 #include "refdata.h"
46
47 #include <cctype>
48 #include <cstdlib>
49
50 #include <algorithm>
51 #include <limits>
52 #include <string>
53
54 #include <gtest/gtest.h>
55
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"
65
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"
72
73 namespace gmx
74 {
75 namespace test
76 {
77
78 /********************************************************************
79  * TestReferenceData::Impl declaration
80  */
81
82 namespace internal
83 {
84
85 /*! \internal \brief
86  * Private implementation class for TestReferenceData.
87  *
88  * \ingroup module_testutils
89  */
90 class TestReferenceDataImpl
91 {
92 public:
93     //! Initializes a checker in the given mode.
94     TestReferenceDataImpl(ReferenceDataMode mode, bool bSelfTestMode);
95
96     //! Performs final reference data processing when test ends.
97     void onTestEnd(bool testPassed);
98
99     //! Full path of the reference data file.
100     std::string fullFilename_;
101     /*! \brief
102      * Root entry for comparing the reference data.
103      *
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.
109      */
110     ReferenceDataEntry::EntryPointer compareRootEntry_;
111     /*! \brief
112      * Root entry for writing new reference data.
113      *
114      * Null if only comparing against existing data.  Otherwise, starts
115      * always as empty.
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.
121      */
122     ReferenceDataEntry::EntryPointer outputRootEntry_;
123     /*! \brief
124      * Whether updating existing reference data.
125      */
126     bool updateMismatchingEntries_;
127     //! `true` if self-testing (enables extra failure messages).
128     bool bSelfTestMode_;
129     /*! \brief
130      * Whether any reference checkers have been created for this data.
131      */
132     bool bInUse_;
133 };
134
135 } // namespace internal
136
137 /********************************************************************
138  * Internal helpers
139  */
140
141 namespace
142 {
143
144 //! Convenience typedef for a smart pointer to TestReferenceDataImpl.
145 typedef std::shared_ptr<internal::TestReferenceDataImpl> TestReferenceDataImplPointer;
146
147 /*! \brief
148  * Global reference data instance.
149  *
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
153  * test listener).
154  */
155 TestReferenceDataImplPointer g_referenceData;
156 //! Global reference data mode set with setReferenceDataMode().
157 ReferenceDataMode g_referenceDataMode = ReferenceDataMode::Compare;
158
159 //! Returns the global reference data mode.
160 ReferenceDataMode getReferenceDataMode()
161 {
162     return g_referenceDataMode;
163 }
164
165 //! Returns a reference to the global reference data object.
166 TestReferenceDataImplPointer initReferenceDataInstance()
167 {
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;
171 }
172
173 //! Handles reference data creation for self-tests.
174 TestReferenceDataImplPointer initReferenceDataInstanceForSelfTest(ReferenceDataMode mode)
175 {
176     if (g_referenceData)
177     {
178         GMX_RELEASE_ASSERT(g_referenceData.unique(),
179                            "Test cannot create multiple TestReferenceData instances");
180         g_referenceData->onTestEnd(true);
181         g_referenceData.reset();
182     }
183     g_referenceData.reset(new internal::TestReferenceDataImpl(mode, true));
184     return g_referenceData;
185 }
186
187 class ReferenceDataTestEventListener : public ::testing::EmptyTestEventListener
188 {
189 public:
190     void OnTestEnd(const ::testing::TestInfo& test_info) override
191     {
192         if (g_referenceData)
193         {
194             GMX_RELEASE_ASSERT(g_referenceData.unique(), "Test leaked TestRefeferenceData objects");
195             g_referenceData->onTestEnd(test_info.result()->Passed());
196             g_referenceData.reset();
197         }
198     }
199
200     void OnTestProgramEnd(const ::testing::UnitTest& /*unused*/) override
201     {
202         // Could be used e.g. to free internal buffers allocated by an XML parsing library
203     }
204 };
205
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)
208 {
209     return prefix + "/" + id;
210 }
211
212 //! Formats a path to a reference data entry with a null id.
213 std::string formatSequenceEntryPath(const std::string& prefix, int seqIndex)
214 {
215     return formatString("%s/[%d]", prefix.c_str(), seqIndex + 1);
216 }
217
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)
222 {
223     if (!root.hasBeenChecked())
224     {
225         unusedPaths->push_back(rootPath);
226         return;
227     }
228     int seqIndex = 0;
229     for (const auto& child : root.children())
230     {
231         std::string path;
232         if (child->id().empty())
233         {
234             path = formatSequenceEntryPath(rootPath, seqIndex);
235             ++seqIndex;
236         }
237         else
238         {
239             path = formatEntryPath(rootPath, child->id());
240         }
241         gatherUnusedEntries(*child, path, unusedPaths);
242     }
243 }
244
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)
247 {
248     std::vector<std::string> unusedPaths;
249     gatherUnusedEntries(root, rootPath, &unusedPaths);
250     if (!unusedPaths.empty())
251     {
252         std::string paths;
253         if (unusedPaths.size() > 5)
254         {
255             paths = joinStrings(unusedPaths.begin(), unusedPaths.begin() + 5, "\n  ");
256             paths = "  " + paths + "\n  ...";
257         }
258         else
259         {
260             paths = joinStrings(unusedPaths.begin(), unusedPaths.end(), "\n  ");
261             paths = "  " + paths;
262         }
263         ADD_FAILURE() << "Reference data items not used in test:" << std::endl << paths;
264     }
265 }
266
267 } // namespace
268
269 void initReferenceData(IOptionsContainer* options)
270 {
271     static const gmx::EnumerationArray<ReferenceDataMode, const char*> s_refDataNames = {
272         { "check", "create", "update-changed", "update-all" }
273     };
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);
279 }
280
281 /********************************************************************
282  * TestReferenceDataImpl definition
283  */
284
285 namespace internal
286 {
287
288 TestReferenceDataImpl::TestReferenceDataImpl(ReferenceDataMode mode, bool bSelfTestMode) :
289     updateMismatchingEntries_(false),
290     bSelfTestMode_(bSelfTestMode),
291     bInUse_(false)
292 {
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);
297
298     switch (mode)
299     {
300         case ReferenceDataMode::Compare:
301             if (File::exists(fullFilename_, File::throwOnError))
302             {
303                 compareRootEntry_ = readReferenceDataFile(fullFilename_);
304             }
305             break;
306         case ReferenceDataMode::CreateMissing:
307             if (File::exists(fullFilename_, File::throwOnError))
308             {
309                 compareRootEntry_ = readReferenceDataFile(fullFilename_);
310             }
311             else
312             {
313                 compareRootEntry_ = ReferenceDataEntry::createRoot();
314                 outputRootEntry_  = ReferenceDataEntry::createRoot();
315             }
316             break;
317         case ReferenceDataMode::UpdateChanged:
318             if (File::exists(fullFilename_, File::throwOnError))
319             {
320                 compareRootEntry_ = readReferenceDataFile(fullFilename_);
321             }
322             else
323             {
324                 compareRootEntry_ = ReferenceDataEntry::createRoot();
325             }
326             outputRootEntry_          = ReferenceDataEntry::createRoot();
327             updateMismatchingEntries_ = true;
328             break;
329         case ReferenceDataMode::UpdateAll:
330             compareRootEntry_ = ReferenceDataEntry::createRoot();
331             outputRootEntry_  = ReferenceDataEntry::createRoot();
332             break;
333         case ReferenceDataMode::Count: GMX_THROW(InternalError("Invalid reference data mode"));
334     }
335 }
336
337 void TestReferenceDataImpl::onTestEnd(bool testPassed)
338 {
339     if (!bInUse_)
340     {
341         return;
342     }
343     // TODO: Only write the file with update-changed if there were actual changes.
344     if (outputRootEntry_)
345     {
346         if (testPassed)
347         {
348             std::string dirname = Path::getParentPath(fullFilename_);
349             if (!Directory::exists(dirname))
350             {
351                 if (Directory::create(dirname) != 0)
352                 {
353                     GMX_THROW(TestException("Creation of reference data directory failed: " + dirname));
354                 }
355             }
356             writeReferenceDataFile(fullFilename_, *outputRootEntry_);
357         }
358     }
359     else if (compareRootEntry_)
360     {
361         checkUnusedEntries(*compareRootEntry_, "");
362     }
363 }
364
365 } // namespace internal
366
367
368 /********************************************************************
369  * TestReferenceChecker::Impl
370  */
371
372 /*! \internal \brief
373  * Private implementation class for TestReferenceChecker.
374  *
375  * \ingroup module_testutils
376  */
377 class TestReferenceChecker::Impl
378 {
379 public:
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;
408
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,
416          bool                          bSelfTestMode,
417          const FloatingPointTolerance& defaultTolerance);
418
419     //! Returns the path of this checker with \p id appended.
420     std::string appendPath(const char* id) const;
421
422     //! Creates an entry with given parameters and fills it with \p checker.
423     static ReferenceDataEntry::EntryPointer createEntry(const char*                       type,
424                                                         const char*                       id,
425                                                         const IReferenceDataEntryChecker& checker)
426     {
427         ReferenceDataEntry::EntryPointer entry(new ReferenceDataEntry(type, id));
428         checker.fillEntry(entry.get());
429         return entry;
430     }
431     //! Checks an entry for correct type and using \p checker.
432     static ::testing::AssertionResult checkEntry(const ReferenceDataEntry&         entry,
433                                                  const std::string&                fullId,
434                                                  const char*                       type,
435                                                  const IReferenceDataEntryChecker& checker)
436     {
437         if (entry.type() != type)
438         {
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();
443         }
444         return checker.checkEntry(entry, fullId);
445     }
446     //! Finds an entry by id and updates the last found entry pointer.
447     ReferenceDataEntry* findEntry(const char* id);
448     /*! \brief
449      * Finds/creates a reference data entry to match against.
450      *
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
457      *      instead).
458      */
459     ReferenceDataEntry* findOrCreateEntry(const char*                       type,
460                                           const char*                       id,
461                                           const IReferenceDataEntryChecker& checker);
462     /*! \brief
463      * Helper method for checking a reference data value.
464      *
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
469      *     type of the entry.
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
473      *     reference data.
474      *
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.
480      */
481     ::testing::AssertionResult processItem(const char*                       name,
482                                            const char*                       id,
483                                            const IReferenceDataEntryChecker& checker);
484     /*! \brief
485      * Whether the checker is initialized.
486      */
487     bool initialized() const { return initialized_; }
488     /*! \brief
489      * Whether the checker should ignore all validation calls.
490      *
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.
494      */
495     bool shouldIgnore() const
496     {
497         GMX_RELEASE_ASSERT(initialized(), "Accessing uninitialized reference data checker.");
498         return compareRootEntry_ == nullptr;
499     }
500
501     //! Whether initialized with other means than the default constructor.
502     bool initialized_;
503     //! Default floating-point comparison tolerance.
504     FloatingPointTolerance defaultTolerance_;
505     /*! \brief
506      * Human-readable path to the root node of this checker.
507      *
508      * For the root checker, this will be "/", and for each compound, the
509      * id of the compound is added.  Used for reporting comparison
510      * mismatches.
511      */
512     std::string path_;
513     /*! \brief
514      * Current entry under which reference data is searched for comparison.
515      *
516      * Points to either the TestReferenceDataImpl::compareRootEntry_, or to
517      * a compound entry in the tree rooted at that entry.
518      *
519      * Can be NULL, in which case this checker does nothing (doesn't even
520      * report errors, see shouldIgnore()).
521      */
522     ReferenceDataEntry* compareRootEntry_;
523     /*! \brief
524      * Current entry under which entries for writing are created.
525      *
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`.
529      */
530     ReferenceDataEntry* outputRootEntry_;
531     /*! \brief
532      * Iterator to a child of \a compareRootEntry_ that was last found.
533      *
534      * If `compareRootEntry_->isValidChild()` returns false, no entry has
535      * been found yet.
536      * After every check, is updated to point to the entry that was used
537      * for the check.
538      * Subsequent checks start the search for the matching node on this
539      * node.
540      */
541     ReferenceDataEntry::ChildIterator lastFoundEntry_;
542     /*! \brief
543      * Whether the reference data is being written (true) or compared
544      * (false).
545      */
546     bool updateMismatchingEntries_;
547     //! `true` if self-testing (enables extra failure messages).
548     bool bSelfTestMode_;
549     /*! \brief
550      * Current number of unnamed elements in a sequence.
551      *
552      * It is the index of the current unnamed element.
553      */
554     int seqIndex_;
555 };
556
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";
571
572
573 TestReferenceChecker::Impl::Impl(bool initialized) :
574     initialized_(initialized),
575     defaultTolerance_(defaultRealTolerance()),
576     compareRootEntry_(nullptr),
577     outputRootEntry_(nullptr),
578     updateMismatchingEntries_(false),
579     bSelfTestMode_(false),
580     seqIndex_(-1)
581 {
582 }
583
584
585 TestReferenceChecker::Impl::Impl(const std::string&            path,
586                                  ReferenceDataEntry*           compareRootEntry,
587                                  ReferenceDataEntry*           outputRootEntry,
588                                  bool                          updateMismatchingEntries,
589                                  bool                          bSelfTestMode,
590                                  const FloatingPointTolerance& defaultTolerance) :
591     initialized_(true),
592     defaultTolerance_(defaultTolerance),
593     path_(path),
594     compareRootEntry_(compareRootEntry),
595     outputRootEntry_(outputRootEntry),
596     lastFoundEntry_(compareRootEntry->children().end()),
597     updateMismatchingEntries_(updateMismatchingEntries),
598     bSelfTestMode_(bSelfTestMode),
599     seqIndex_(-1)
600 {
601 }
602
603
604 std::string TestReferenceChecker::Impl::appendPath(const char* id) const
605 {
606     return id != nullptr ? formatEntryPath(path_, id) : formatSequenceEntryPath(path_, seqIndex_);
607 }
608
609
610 ReferenceDataEntry* TestReferenceChecker::Impl::findEntry(const char* id)
611 {
612     ReferenceDataEntry::ChildIterator entry = compareRootEntry_->findChild(id, lastFoundEntry_);
613     seqIndex_                               = (id == nullptr) ? seqIndex_ + 1 : -1;
614     if (compareRootEntry_->isValidChild(entry))
615     {
616         lastFoundEntry_ = entry;
617         return entry->get();
618     }
619     return nullptr;
620 }
621
622 ReferenceDataEntry* TestReferenceChecker::Impl::findOrCreateEntry(const char* type,
623                                                                   const char* id,
624                                                                   const IReferenceDataEntryChecker& checker)
625 {
626     ReferenceDataEntry* entry = findEntry(id);
627     if (entry == nullptr && outputRootEntry_ != nullptr)
628     {
629         lastFoundEntry_ = compareRootEntry_->addChild(createEntry(type, id, checker));
630         entry           = lastFoundEntry_->get();
631     }
632     return entry;
633 }
634
635 ::testing::AssertionResult TestReferenceChecker::Impl::processItem(const char* type,
636                                                                    const char* id,
637                                                                    const IReferenceDataEntryChecker& checker)
638 {
639     if (shouldIgnore())
640     {
641         return ::testing::AssertionSuccess();
642     }
643     std::string         fullId = appendPath(id);
644     ReferenceDataEntry* entry  = findOrCreateEntry(type, id, checker);
645     if (entry == nullptr)
646     {
647         return ::testing::AssertionFailure() << "Reference data item " << fullId << " not found";
648     }
649     entry->setChecked();
650     ::testing::AssertionResult result(checkEntry(*entry, fullId, type, checker));
651     if (outputRootEntry_ != nullptr && entry->correspondingOutputEntry() == nullptr)
652     {
653         if (!updateMismatchingEntries_ || result)
654         {
655             outputRootEntry_->addChild(entry->cloneToOutputEntry());
656         }
657         else
658         {
659             ReferenceDataEntry::EntryPointer outputEntry(createEntry(type, id, checker));
660             entry->setCorrespondingOutputEntry(outputEntry.get());
661             outputRootEntry_->addChild(move(outputEntry));
662             return ::testing::AssertionSuccess();
663         }
664     }
665     if (bSelfTestMode_ && !result)
666     {
667         ReferenceDataEntry expected(type, id);
668         checker.fillEntry(&expected);
669         result << std::endl
670                << "String value: '" << expected.value() << "'" << std::endl
671                << " Ref. string: '" << entry->value() << "'";
672     }
673     return result;
674 }
675
676
677 /********************************************************************
678  * TestReferenceData
679  */
680
681 TestReferenceData::TestReferenceData() : impl_(initReferenceDataInstance()) {}
682
683
684 TestReferenceData::TestReferenceData(ReferenceDataMode mode) :
685     impl_(initReferenceDataInstanceForSelfTest(mode))
686 {
687 }
688
689
690 TestReferenceData::~TestReferenceData() {}
691
692
693 TestReferenceChecker TestReferenceData::rootChecker()
694 {
695     if (!impl_->bInUse_ && !impl_->compareRootEntry_)
696     {
697         ADD_FAILURE() << "Reference data file not found: " << impl_->fullFilename_;
698     }
699     impl_->bInUse_ = true;
700     if (!impl_->compareRootEntry_)
701     {
702         return TestReferenceChecker(new TestReferenceChecker::Impl(true));
703     }
704     impl_->compareRootEntry_->setChecked();
705     return TestReferenceChecker(new TestReferenceChecker::Impl(
706             "", impl_->compareRootEntry_.get(), impl_->outputRootEntry_.get(),
707             impl_->updateMismatchingEntries_, impl_->bSelfTestMode_, defaultRealTolerance()));
708 }
709
710
711 /********************************************************************
712  * TestReferenceChecker
713  */
714
715 TestReferenceChecker::TestReferenceChecker() : impl_(new Impl(false)) {}
716
717 TestReferenceChecker::TestReferenceChecker(Impl* impl) : impl_(impl) {}
718
719 TestReferenceChecker::TestReferenceChecker(const TestReferenceChecker& other) :
720     impl_(new Impl(*other.impl_))
721 {
722 }
723
724 TestReferenceChecker::TestReferenceChecker(TestReferenceChecker&& other) noexcept :
725     impl_(std::move(other.impl_))
726 {
727 }
728
729 TestReferenceChecker& TestReferenceChecker::operator=(TestReferenceChecker&& other) noexcept
730 {
731     impl_ = std::move(other.impl_);
732     return *this;
733 }
734
735 TestReferenceChecker::~TestReferenceChecker() {}
736
737 bool TestReferenceChecker::isValid() const
738 {
739     return impl_->initialized();
740 }
741
742
743 void TestReferenceChecker::setDefaultTolerance(const FloatingPointTolerance& tolerance)
744 {
745     impl_->defaultTolerance_ = tolerance;
746 }
747
748
749 void TestReferenceChecker::checkUnusedEntries()
750 {
751     if (impl_->compareRootEntry_)
752     {
753         gmx::test::checkUnusedEntries(*impl_->compareRootEntry_, impl_->path_);
754         // Mark them checked so that they are reported only once.
755         impl_->compareRootEntry_->setCheckedIncludingChildren();
756     }
757 }
758
759
760 bool TestReferenceChecker::checkPresent(bool bPresent, const char* id)
761 {
762     if (impl_->shouldIgnore() || impl_->outputRootEntry_ != nullptr)
763     {
764         return bPresent;
765     }
766     ReferenceDataEntry::ChildIterator entry =
767             impl_->compareRootEntry_->findChild(id, impl_->lastFoundEntry_);
768     const bool bFound = impl_->compareRootEntry_->isValidChild(entry);
769     if (bFound != bPresent)
770     {
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.");
774     }
775     if (bFound && bPresent)
776     {
777         impl_->lastFoundEntry_ = entry;
778         return true;
779     }
780     return false;
781 }
782
783
784 TestReferenceChecker TestReferenceChecker::checkCompound(const char* type, const char* id)
785 {
786     if (impl_->shouldIgnore())
787     {
788         return TestReferenceChecker(new Impl(true));
789     }
790     std::string         fullId = impl_->appendPath(id);
791     NullChecker         checker;
792     ReferenceDataEntry* entry = impl_->findOrCreateEntry(type, id, checker);
793     if (entry == nullptr)
794     {
795         ADD_FAILURE() << "Reference data item " << fullId << " not found";
796         return TestReferenceChecker(new Impl(true));
797     }
798     entry->setChecked();
799     if (impl_->updateMismatchingEntries_)
800     {
801         entry->makeCompound(type);
802     }
803     else
804     {
805         ::testing::AssertionResult result(impl_->checkEntry(*entry, fullId, type, checker));
806         EXPECT_PLAIN(result);
807         if (!result)
808         {
809             return TestReferenceChecker(new Impl(true));
810         }
811     }
812     if (impl_->outputRootEntry_ != nullptr && entry->correspondingOutputEntry() == nullptr)
813     {
814         impl_->outputRootEntry_->addChild(entry->cloneToOutputEntry());
815     }
816     return TestReferenceChecker(new Impl(fullId, entry, entry->correspondingOutputEntry(),
817                                          impl_->updateMismatchingEntries_, impl_->bSelfTestMode_,
818                                          impl_->defaultTolerance_));
819 }
820
821 TestReferenceChecker TestReferenceChecker::checkCompound(const char* type, const std::string& id)
822 {
823     return checkCompound(type, id.c_str());
824 }
825
826 /*! \brief Throw a TestException if the caller tries to write particular refdata that can't work.
827  *
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
831  * problems.
832  *
833  * \todo Eliminate this limitation of TinyXML2. See
834  * e.g. https://github.com/leethomason/tinyxml2/issues/432
835  */
836 static void throwIfNonEmptyAndOnlyWhitespace(const std::string& s, const char* id)
837 {
838     if (!s.empty() && std::all_of(s.cbegin(), s.cend(), [](const char& c) { return std::isspace(c); }))
839     {
840         std::string message("String '" + s + "' with ");
841         message += (id != nullptr) ? "null " : "";
842         message += "ID ";
843         message += (id != nullptr) ? "" : id;
844         message +=
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));
849     }
850 }
851
852 void TestReferenceChecker::checkBoolean(bool value, const char* id)
853 {
854     EXPECT_PLAIN(impl_->processItem(Impl::cBooleanNodeName, id,
855                                     ExactStringChecker(value ? "true" : "false")));
856 }
857
858
859 void TestReferenceChecker::checkString(const char* value, const char* id)
860 {
861     throwIfNonEmptyAndOnlyWhitespace(value, id);
862     EXPECT_PLAIN(impl_->processItem(Impl::cStringNodeName, id, ExactStringChecker(value)));
863 }
864
865
866 void TestReferenceChecker::checkString(const std::string& value, const char* id)
867 {
868     throwIfNonEmptyAndOnlyWhitespace(value, id);
869     EXPECT_PLAIN(impl_->processItem(Impl::cStringNodeName, id, ExactStringChecker(value)));
870 }
871
872
873 void TestReferenceChecker::checkTextBlock(const std::string& value, const char* id)
874 {
875     EXPECT_PLAIN(impl_->processItem(Impl::cStringNodeName, id, ExactStringBlockChecker(value)));
876 }
877
878
879 void TestReferenceChecker::checkUChar(unsigned char value, const char* id)
880 {
881     EXPECT_PLAIN(impl_->processItem(Impl::cUCharNodeName, id,
882                                     ExactStringChecker(formatString("%d", value))));
883 }
884
885 void TestReferenceChecker::checkInteger(int value, const char* id)
886 {
887     EXPECT_PLAIN(impl_->processItem(Impl::cIntegerNodeName, id,
888                                     ExactStringChecker(formatString("%d", value))));
889 }
890
891 void TestReferenceChecker::checkInt32(int32_t value, const char* id)
892 {
893     EXPECT_PLAIN(impl_->processItem(Impl::cInt32NodeName, id,
894                                     ExactStringChecker(formatString("%" PRId32, value))));
895 }
896
897 void TestReferenceChecker::checkUInt32(uint32_t value, const char* id)
898 {
899     EXPECT_PLAIN(impl_->processItem(Impl::cUInt32NodeName, id,
900                                     ExactStringChecker(formatString("%" PRIu32, value))));
901 }
902
903 void TestReferenceChecker::checkInt64(int64_t value, const char* id)
904 {
905     EXPECT_PLAIN(impl_->processItem(Impl::cInt64NodeName, id,
906                                     ExactStringChecker(formatString("%" PRId64, value))));
907 }
908
909 void TestReferenceChecker::checkUInt64(uint64_t value, const char* id)
910 {
911     EXPECT_PLAIN(impl_->processItem(Impl::cUInt64NodeName, id,
912                                     ExactStringChecker(formatString("%" PRIu64, value))));
913 }
914
915 void TestReferenceChecker::checkDouble(double value, const char* id)
916 {
917     FloatingPointChecker<double> checker(value, impl_->defaultTolerance_);
918     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, checker));
919 }
920
921
922 void TestReferenceChecker::checkFloat(float value, const char* id)
923 {
924     FloatingPointChecker<float> checker(value, impl_->defaultTolerance_);
925     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, checker));
926 }
927
928
929 void TestReferenceChecker::checkReal(float value, const char* id)
930 {
931     checkFloat(value, id);
932 }
933
934
935 void TestReferenceChecker::checkReal(double value, const char* id)
936 {
937     checkDouble(value, id);
938 }
939
940
941 void TestReferenceChecker::checkRealFromString(const std::string& value, const char* id)
942 {
943     FloatingPointFromStringChecker<real> checker(value, impl_->defaultTolerance_);
944     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, checker));
945 }
946
947
948 void TestReferenceChecker::checkVector(const int value[3], const char* id)
949 {
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");
954 }
955
956
957 void TestReferenceChecker::checkVector(const float value[3], const char* id)
958 {
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");
963 }
964
965
966 void TestReferenceChecker::checkVector(const double value[3], const char* id)
967 {
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");
972 }
973
974
975 void TestReferenceChecker::checkAny(const Any& any, const char* id)
976 {
977     if (any.isType<bool>())
978     {
979         checkBoolean(any.cast<bool>(), id);
980     }
981     else if (any.isType<int>())
982     {
983         checkInteger(any.cast<int>(), id);
984     }
985     else if (any.isType<int32_t>())
986     {
987         checkInt32(any.cast<int32_t>(), id);
988     }
989     else if (any.isType<uint32_t>())
990     {
991         checkInt32(any.cast<uint32_t>(), id);
992     }
993     else if (any.isType<int64_t>())
994     {
995         checkInt64(any.cast<int64_t>(), id);
996     }
997     else if (any.isType<uint64_t>())
998     {
999         checkInt64(any.cast<uint64_t>(), id);
1000     }
1001     else if (any.isType<float>())
1002     {
1003         checkFloat(any.cast<float>(), id);
1004     }
1005     else if (any.isType<double>())
1006     {
1007         checkDouble(any.cast<double>(), id);
1008     }
1009     else if (any.isType<std::string>())
1010     {
1011         checkString(any.cast<std::string>(), id);
1012     }
1013     else
1014     {
1015         GMX_THROW(TestException("Unsupported any type"));
1016     }
1017 }
1018
1019
1020 void TestReferenceChecker::checkKeyValueTreeObject(const KeyValueTreeObject& tree, const char* id)
1021 {
1022     TestReferenceChecker compound(checkCompound(Impl::cObjectType, id));
1023     for (const auto& prop : tree.properties())
1024     {
1025         compound.checkKeyValueTreeValue(prop.value(), prop.key().c_str());
1026     }
1027     compound.checkUnusedEntries();
1028 }
1029
1030
1031 void TestReferenceChecker::checkKeyValueTreeValue(const KeyValueTreeValue& value, const char* id)
1032 {
1033     if (value.isObject())
1034     {
1035         checkKeyValueTreeObject(value.asObject(), id);
1036     }
1037     else if (value.isArray())
1038     {
1039         const auto& values = value.asArray().values();
1040         checkSequence(values.begin(), values.end(), id);
1041     }
1042     else
1043     {
1044         checkAny(value.asAny(), id);
1045     }
1046 }
1047
1048
1049 TestReferenceChecker TestReferenceChecker::checkSequenceCompound(const char* id, size_t length)
1050 {
1051     TestReferenceChecker compound(checkCompound(Impl::cSequenceType, id));
1052     compound.checkInteger(static_cast<int>(length), Impl::cSequenceLengthName);
1053     return compound;
1054 }
1055
1056
1057 unsigned char TestReferenceChecker::readUChar(const char* id)
1058 {
1059     if (impl_->shouldIgnore())
1060     {
1061         GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1062     }
1063     int value = 0;
1064     EXPECT_PLAIN(impl_->processItem(Impl::cUCharNodeName, id, ValueExtractor<int>(&value)));
1065     return value;
1066 }
1067
1068
1069 int TestReferenceChecker::readInteger(const char* id)
1070 {
1071     if (impl_->shouldIgnore())
1072     {
1073         GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1074     }
1075     int value = 0;
1076     EXPECT_PLAIN(impl_->processItem(Impl::cIntegerNodeName, id, ValueExtractor<int>(&value)));
1077     return value;
1078 }
1079
1080
1081 int32_t TestReferenceChecker::readInt32(const char* id)
1082 {
1083     if (impl_->shouldIgnore())
1084     {
1085         GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1086     }
1087     int32_t value = 0;
1088     EXPECT_PLAIN(impl_->processItem(Impl::cInt32NodeName, id, ValueExtractor<int32_t>(&value)));
1089     return value;
1090 }
1091
1092
1093 int64_t TestReferenceChecker::readInt64(const char* id)
1094 {
1095     if (impl_->shouldIgnore())
1096     {
1097         GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1098     }
1099     int64_t value = 0;
1100     EXPECT_PLAIN(impl_->processItem(Impl::cInt64NodeName, id, ValueExtractor<int64_t>(&value)));
1101     return value;
1102 }
1103
1104
1105 float TestReferenceChecker::readFloat(const char* id)
1106 {
1107     if (impl_->shouldIgnore())
1108     {
1109         GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1110     }
1111     float value = 0;
1112     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, ValueExtractor<float>(&value)));
1113     return value;
1114 }
1115
1116
1117 double TestReferenceChecker::readDouble(const char* id)
1118 {
1119     if (impl_->shouldIgnore())
1120     {
1121         GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1122     }
1123     double value = 0;
1124     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, ValueExtractor<double>(&value)));
1125     return value;
1126 }
1127
1128
1129 std::string TestReferenceChecker::readString(const char* id)
1130 {
1131     if (impl_->shouldIgnore())
1132     {
1133         GMX_THROW(TestException("Trying to read from non-existent reference data value"));
1134     }
1135     std::string value;
1136     EXPECT_PLAIN(impl_->processItem(Impl::cStringNodeName, id, ValueExtractor<std::string>(&value)));
1137     return value;
1138 }
1139
1140 } // namespace test
1141 } // namespace gmx