Merge branch release-2016
[alexxy/gromacs.git] / src / testutils / refdata.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2011,2012,2013,2014,2015,2016, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements classes and functions from refdata.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_testutils
41  */
42 #include "gmxpre.h"
43
44 #include "refdata.h"
45
46 #include <cctype>
47 #include <cstdlib>
48
49 #include <algorithm>
50 #include <limits>
51 #include <string>
52
53 #include <gtest/gtest.h>
54
55 #include "gromacs/options/basicoptions.h"
56 #include "gromacs/options/ioptionscontainer.h"
57 #include "gromacs/utility/exceptions.h"
58 #include "gromacs/utility/gmxassert.h"
59 #include "gromacs/utility/keyvaluetree.h"
60 #include "gromacs/utility/path.h"
61 #include "gromacs/utility/real.h"
62 #include "gromacs/utility/stringutil.h"
63 #include "gromacs/utility/variant.h"
64
65 #include "testutils/refdata-checkers.h"
66 #include "testutils/refdata-impl.h"
67 #include "testutils/refdata-xml.h"
68 #include "testutils/testasserts.h"
69 #include "testutils/testexceptions.h"
70 #include "testutils/testfilemanager.h"
71
72 namespace gmx
73 {
74 namespace test
75 {
76
77 /********************************************************************
78  * TestReferenceData::Impl declaration
79  */
80
81 namespace internal
82 {
83
84 /*! \internal \brief
85  * Private implementation class for TestReferenceData.
86  *
87  * \ingroup module_testutils
88  */
89 class TestReferenceDataImpl
90 {
91     public:
92         //! Initializes a checker in the given mode.
93         TestReferenceDataImpl(ReferenceDataMode mode, bool bSelfTestMode);
94
95         //! Performs final reference data processing when test ends.
96         void onTestEnd(bool testPassed);
97
98         //! Full path of the reference data file.
99         std::string             fullFilename_;
100         /*! \brief
101          * Root entry for comparing the reference data.
102          *
103          * Null after construction iff in compare mode and reference data was
104          * not loaded successfully.
105          * In all write modes, copies are present for nodes added to
106          * \a outputRootEntry_, and ReferenceDataEntry::correspondingOutputEntry()
107          * points to the copy in the output tree.
108          */
109         ReferenceDataEntry::EntryPointer  compareRootEntry_;
110         /*! \brief
111          * Root entry for writing new reference data.
112          *
113          * Null if only comparing against existing data.  Otherwise, starts
114          * always as empty.
115          * When creating new reference data, this is maintained as a copy of
116          * \a compareRootEntry_.
117          * When updating existing data, entries are added either by copying
118          * from \a compareRootEntry_ (if they exist and comparison passes), or
119          * by creating new ones.
120          */
121         ReferenceDataEntry::EntryPointer  outputRootEntry_;
122         /*! \brief
123          * Whether updating existing reference data.
124          */
125         bool                    updateMismatchingEntries_;
126         //! `true` if self-testing (enables extra failure messages).
127         bool                    bSelfTestMode_;
128         /*! \brief
129          * Whether any reference checkers have been created for this data.
130          */
131         bool                    bInUse_;
132 };
133
134 }       // namespace internal
135
136 /********************************************************************
137  * Internal helpers
138  */
139
140 namespace
141 {
142
143 //! Convenience typedef for a smart pointer to TestReferenceDataImpl.
144 typedef std::shared_ptr<internal::TestReferenceDataImpl>
145     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 = erefdataCompare;
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,
169                        "Test cannot create multiple TestReferenceData instances");
170     g_referenceData.reset(new internal::TestReferenceDataImpl(getReferenceDataMode(), false));
171     return g_referenceData;
172 }
173
174 //! Handles reference data creation for self-tests.
175 TestReferenceDataImplPointer initReferenceDataInstanceForSelfTest(ReferenceDataMode mode)
176 {
177     if (g_referenceData)
178     {
179         GMX_RELEASE_ASSERT(g_referenceData.unique(),
180                            "Test cannot create multiple TestReferenceData instances");
181         g_referenceData->onTestEnd(true);
182         g_referenceData.reset();
183     }
184     g_referenceData.reset(new internal::TestReferenceDataImpl(mode, true));
185     return g_referenceData;
186 }
187
188 class ReferenceDataTestEventListener : public ::testing::EmptyTestEventListener
189 {
190     public:
191         virtual void OnTestEnd(const ::testing::TestInfo &test_info)
192         {
193             if (g_referenceData)
194             {
195                 GMX_RELEASE_ASSERT(g_referenceData.unique(),
196                                    "Test leaked TestRefeferenceData objects");
197                 g_referenceData->onTestEnd(test_info.result()->Passed());
198                 g_referenceData.reset();
199             }
200         }
201
202         virtual void OnTestProgramEnd(const ::testing::UnitTest &)
203         {
204             // Could be used e.g. to free internal buffers allocated by an XML parsing library
205         }
206 };
207
208 //! Formats a path to a reference data entry with a non-null id.
209 std::string formatEntryPath(const std::string &prefix, const std::string &id)
210 {
211     return prefix + "/" + id;
212 }
213
214 //! Formats a path to a reference data entry with a null id.
215 std::string formatSequenceEntryPath(const std::string &prefix, int seqIndex)
216 {
217     return formatString("%s/[%d]", prefix.c_str(), seqIndex+1);
218 }
219
220 //! Finds all entries that have not been checked under a given root.
221 void gatherUnusedEntries(const ReferenceDataEntry &root,
222                          const std::string        &rootPath,
223                          std::vector<std::string> *unusedPaths)
224 {
225     if (!root.hasBeenChecked())
226     {
227         unusedPaths->push_back(rootPath);
228         return;
229     }
230     int seqIndex = 0;
231     for (const auto &child : root.children())
232     {
233         std::string path;
234         if (child->id().empty())
235         {
236             path = formatSequenceEntryPath(rootPath, seqIndex);
237             ++seqIndex;
238         }
239         else
240         {
241             path = formatEntryPath(rootPath, child->id());
242         }
243         gatherUnusedEntries(*child, path, unusedPaths);
244     }
245 }
246
247 //! Produces a GTest assertion of any entries under given root have not been checked.
248 void checkUnusedEntries(const ReferenceDataEntry &root, const std::string &rootPath)
249 {
250     std::vector<std::string> unusedPaths;
251     gatherUnusedEntries(root, rootPath, &unusedPaths);
252     if (!unusedPaths.empty())
253     {
254         std::string paths;
255         if (unusedPaths.size() > 5)
256         {
257             paths = joinStrings(unusedPaths.begin(), unusedPaths.begin() + 5, "\n  ");
258             paths = "  " + paths + "\n  ...";
259         }
260         else
261         {
262             paths = joinStrings(unusedPaths.begin(), unusedPaths.end(), "\n  ");
263             paths = "  " + paths;
264         }
265         ADD_FAILURE() << "Reference data items not used in test:" << std::endl << paths;
266     }
267 }
268
269 }       // namespace
270
271 void initReferenceData(IOptionsContainer *options)
272 {
273     // Needs to correspond to the enum order in refdata.h.
274     const char *const refDataEnum[] =
275     { "check", "create", "update-changed", "update-all" };
276     options->addOption(
277             EnumOption<ReferenceDataMode>("ref-data")
278                 .enumValue(refDataEnum).store(&g_referenceDataMode)
279                 .description("Operation mode for tests that use reference data"));
280     ::testing::UnitTest::GetInstance()->listeners().Append(
281             new ReferenceDataTestEventListener);
282 }
283
284 /********************************************************************
285  * TestReferenceDataImpl definition
286  */
287
288 namespace internal
289 {
290
291 TestReferenceDataImpl::TestReferenceDataImpl(
292         ReferenceDataMode mode, bool bSelfTestMode)
293     : updateMismatchingEntries_(false), bSelfTestMode_(bSelfTestMode), bInUse_(false)
294 {
295     const std::string dirname =
296         bSelfTestMode
297         ? TestFileManager::getGlobalOutputTempDirectory()
298         : TestFileManager::getInputDataDirectory();
299     const std::string filename = TestFileManager::getTestSpecificFileName(".xml");
300     fullFilename_ = Path::join(dirname, "refdata", filename);
301
302     switch (mode)
303     {
304         case erefdataCompare:
305             if (File::exists(fullFilename_, File::throwOnError))
306             {
307                 compareRootEntry_ = readReferenceDataFile(fullFilename_);
308             }
309             break;
310         case erefdataCreateMissing:
311             if (File::exists(fullFilename_, File::throwOnError))
312             {
313                 compareRootEntry_ = readReferenceDataFile(fullFilename_);
314             }
315             else
316             {
317                 compareRootEntry_ = ReferenceDataEntry::createRoot();
318                 outputRootEntry_  = ReferenceDataEntry::createRoot();
319             }
320             break;
321         case erefdataUpdateChanged:
322             if (File::exists(fullFilename_, File::throwOnError))
323             {
324                 compareRootEntry_ = readReferenceDataFile(fullFilename_);
325             }
326             else
327             {
328                 compareRootEntry_ = ReferenceDataEntry::createRoot();
329             }
330             outputRootEntry_          = ReferenceDataEntry::createRoot();
331             updateMismatchingEntries_ = true;
332             break;
333         case erefdataUpdateAll:
334             compareRootEntry_ = ReferenceDataEntry::createRoot();
335             outputRootEntry_  = ReferenceDataEntry::createRoot();
336             break;
337     }
338 }
339
340 void TestReferenceDataImpl::onTestEnd(bool testPassed)
341 {
342     if (!bInUse_)
343     {
344         return;
345     }
346     // TODO: Only write the file with update-changed if there were actual changes.
347     if (outputRootEntry_)
348     {
349         if (testPassed)
350         {
351             std::string dirname = Path::getParentPath(fullFilename_);
352             if (!Directory::exists(dirname))
353             {
354                 if (Directory::create(dirname) != 0)
355                 {
356                     GMX_THROW(TestException("Creation of reference data directory failed: " + dirname));
357                 }
358             }
359             writeReferenceDataFile(fullFilename_, *outputRootEntry_);
360         }
361     }
362     else if (compareRootEntry_)
363     {
364         checkUnusedEntries(*compareRootEntry_, "");
365     }
366 }
367
368 }       // namespace internal
369
370
371 /********************************************************************
372  * TestReferenceChecker::Impl
373  */
374
375 /*! \internal \brief
376  * Private implementation class for TestReferenceChecker.
377  *
378  * \ingroup module_testutils
379  */
380 class TestReferenceChecker::Impl
381 {
382     public:
383         //! String constant for naming XML elements for boolean values.
384         static const char * const    cBooleanNodeName;
385         //! String constant for naming XML elements for string values.
386         static const char * const    cStringNodeName;
387         //! String constant for naming XML elements for integer values.
388         static const char * const    cIntegerNodeName;
389         //! String constant for naming XML elements for int64 values.
390         static const char * const    cInt64NodeName;
391         //! String constant for naming XML elements for unsigned int64 values.
392         static const char * const    cUInt64NodeName;
393         //! String constant for naming XML elements for floating-point values.
394         static const char * const    cRealNodeName;
395         //! String constant for naming XML attribute for value identifiers.
396         static const char * const    cIdAttrName;
397         //! String constant for naming compounds for vectors.
398         static const char * const    cVectorType;
399         //! String constant for naming compounds for key-value tree objects.
400         static const char * const    cObjectType;
401         //! String constant for naming compounds for sequences.
402         static const char * const    cSequenceType;
403         //! String constant for value identifier for sequence length.
404         static const char * const    cSequenceLengthName;
405
406         //! Creates a checker that does nothing.
407         explicit Impl(bool initialized);
408         //! Creates a checker with a given root entry.
409         Impl(const std::string &path, ReferenceDataEntry *compareRootEntry,
410              ReferenceDataEntry *outputRootEntry, bool updateMismatchingEntries,
411              bool bSelfTestMode, const FloatingPointTolerance &defaultTolerance);
412
413         //! Returns the path of this checker with \p id appended.
414         std::string appendPath(const char *id) const;
415
416         //! Creates an entry with given parameters and fills it with \p checker.
417         ReferenceDataEntry::EntryPointer
418         createEntry(const char *type, const char *id,
419                     const IReferenceDataEntryChecker &checker) const
420         {
421             ReferenceDataEntry::EntryPointer entry(new ReferenceDataEntry(type, id));
422             checker.fillEntry(entry.get());
423             return entry;
424         }
425         //! Checks an entry for correct type and using \p checker.
426         ::testing::AssertionResult
427         checkEntry(const ReferenceDataEntry &entry, const std::string &fullId,
428                    const char *type, const IReferenceDataEntryChecker &checker) const
429         {
430             if (entry.type() != type)
431             {
432                 return ::testing::AssertionFailure()
433                        << "Mismatching reference data item type" << std::endl
434                        << "  In item: " << fullId << std::endl
435                        << "   Actual: " << type << std::endl
436                        << "Reference: " << entry.type();
437             }
438             return checker.checkEntry(entry, fullId);
439         }
440         //! Finds an entry by id and updates the last found entry pointer.
441         ReferenceDataEntry *findEntry(const char *id);
442         /*! \brief
443          * Finds/creates a reference data entry to match against.
444          *
445          * \param[in]  type   Type of entry to create.
446          * \param[in]  id     Unique identifier of the entry (can be NULL, in
447          *      which case the next entry without an id is matched).
448          * \param[out] checker  Checker to use for filling out created entries.
449          * \returns    Matching entry, or NULL if no matching entry found
450          *      (NULL is never returned in write mode; new entries are created
451          *      instead).
452          */
453         ReferenceDataEntry *
454         findOrCreateEntry(const char *type, const char *id,
455                           const IReferenceDataEntryChecker &checker);
456         /*! \brief
457          * Helper method for checking a reference data value.
458          *
459          * \param[in]  name   Type of entry to find.
460          * \param[in]  id     Unique identifier of the entry (can be NULL, in
461          *     which case the next entry without an id is matched).
462          * \param[in]  checker  Checker that provides logic specific to the
463          *     type of the entry.
464          * \returns    Whether the reference data matched, including details
465          *     of the mismatch if the comparison failed.
466          * \throws     TestException if there is a problem parsing the
467          *     reference data.
468          *
469          * Performs common tasks in checking a reference value, such as
470          * finding or creating the correct entry.
471          * Caller needs to provide a checker object that provides the string
472          * value for a newly created entry and performs the actual comparison
473          * against a found entry.
474          */
475         ::testing::AssertionResult
476         processItem(const char *name, const char *id,
477                     const IReferenceDataEntryChecker &checker);
478         /*! \brief
479          * Whether the checker is initialized.
480          */
481         bool initialized() const { return initialized_; }
482         /*! \brief
483          * Whether the checker should ignore all validation calls.
484          *
485          * This is used to ignore any calls within compounds for which
486          * reference data could not be found, such that only one error is
487          * issued for the missing compound, instead of every individual value.
488          */
489         bool shouldIgnore() const
490         {
491             GMX_RELEASE_ASSERT(initialized(),
492                                "Accessing uninitialized reference data checker.");
493             return compareRootEntry_ == NULL;
494         }
495
496         //! Whether initialized with other means than the default constructor.
497         bool                    initialized_;
498         //! Default floating-point comparison tolerance.
499         FloatingPointTolerance  defaultTolerance_;
500         /*! \brief
501          * Human-readable path to the root node of this checker.
502          *
503          * For the root checker, this will be "/", and for each compound, the
504          * id of the compound is added.  Used for reporting comparison
505          * mismatches.
506          */
507         std::string             path_;
508         /*! \brief
509          * Current entry under which reference data is searched for comparison.
510          *
511          * Points to either the TestReferenceDataImpl::compareRootEntry_, or to
512          * a compound entry in the tree rooted at that entry.
513          *
514          * Can be NULL, in which case this checker does nothing (doesn't even
515          * report errors, see shouldIgnore()).
516          */
517         ReferenceDataEntry     *compareRootEntry_;
518         /*! \brief
519          * Current entry under which entries for writing are created.
520          *
521          * Points to either the TestReferenceDataImpl::outputRootEntry_, or to
522          * a compound entry in the tree rooted at that entry.  NULL if only
523          * comparing, or if shouldIgnore() returns `false`.
524          */
525         ReferenceDataEntry     *outputRootEntry_;
526         /*! \brief
527          * Iterator to a child of \a compareRootEntry_ that was last found.
528          *
529          * If `compareRootEntry_->isValidChild()` returns false, no entry has
530          * been found yet.
531          * After every check, is updated to point to the entry that was used
532          * for the check.
533          * Subsequent checks start the search for the matching node on this
534          * node.
535          */
536         ReferenceDataEntry::ChildIterator lastFoundEntry_;
537         /*! \brief
538          * Whether the reference data is being written (true) or compared
539          * (false).
540          */
541         bool                    updateMismatchingEntries_;
542         //! `true` if self-testing (enables extra failure messages).
543         bool                    bSelfTestMode_;
544         /*! \brief
545          * Current number of unnamed elements in a sequence.
546          *
547          * It is the index of the current unnamed element.
548          */
549         int                     seqIndex_;
550 };
551
552 const char *const TestReferenceChecker::Impl::cBooleanNodeName    = "Bool";
553 const char *const TestReferenceChecker::Impl::cStringNodeName     = "String";
554 const char *const TestReferenceChecker::Impl::cIntegerNodeName    = "Int";
555 const char *const TestReferenceChecker::Impl::cInt64NodeName      = "Int64";
556 const char *const TestReferenceChecker::Impl::cUInt64NodeName     = "UInt64";
557 const char *const TestReferenceChecker::Impl::cRealNodeName       = "Real";
558 const char *const TestReferenceChecker::Impl::cIdAttrName         = "Name";
559 const char *const TestReferenceChecker::Impl::cVectorType         = "Vector";
560 const char *const TestReferenceChecker::Impl::cObjectType         = "Object";
561 const char *const TestReferenceChecker::Impl::cSequenceType       = "Sequence";
562 const char *const TestReferenceChecker::Impl::cSequenceLengthName = "Length";
563
564
565 TestReferenceChecker::Impl::Impl(bool initialized)
566     : initialized_(initialized), defaultTolerance_(defaultRealTolerance()),
567       compareRootEntry_(NULL), outputRootEntry_(NULL),
568       updateMismatchingEntries_(false), bSelfTestMode_(false), seqIndex_(-1)
569 {
570 }
571
572
573 TestReferenceChecker::Impl::Impl(const std::string &path,
574                                  ReferenceDataEntry *compareRootEntry,
575                                  ReferenceDataEntry *outputRootEntry,
576                                  bool updateMismatchingEntries, bool bSelfTestMode,
577                                  const FloatingPointTolerance &defaultTolerance)
578     : initialized_(true), defaultTolerance_(defaultTolerance), path_(path),
579       compareRootEntry_(compareRootEntry), outputRootEntry_(outputRootEntry),
580       lastFoundEntry_(compareRootEntry->children().end()),
581       updateMismatchingEntries_(updateMismatchingEntries),
582       bSelfTestMode_(bSelfTestMode), seqIndex_(-1)
583 {
584 }
585
586
587 std::string
588 TestReferenceChecker::Impl::appendPath(const char *id) const
589 {
590     return id != nullptr
591            ? formatEntryPath(path_, id)
592            : formatSequenceEntryPath(path_, seqIndex_);
593 }
594
595
596 ReferenceDataEntry *TestReferenceChecker::Impl::findEntry(const char *id)
597 {
598     ReferenceDataEntry::ChildIterator entry = compareRootEntry_->findChild(id, lastFoundEntry_);
599     seqIndex_ = (id == nullptr) ? seqIndex_+1 : -1;
600     if (compareRootEntry_->isValidChild(entry))
601     {
602         lastFoundEntry_ = entry;
603         return entry->get();
604     }
605     return NULL;
606 }
607
608 ReferenceDataEntry *
609 TestReferenceChecker::Impl::findOrCreateEntry(
610         const char *type, const char *id,
611         const IReferenceDataEntryChecker &checker)
612 {
613     ReferenceDataEntry *entry = findEntry(id);
614     if (entry == NULL && outputRootEntry_ != NULL)
615     {
616         lastFoundEntry_ = compareRootEntry_->addChild(createEntry(type, id, checker));
617         entry           = lastFoundEntry_->get();
618     }
619     return entry;
620 }
621
622 ::testing::AssertionResult
623 TestReferenceChecker::Impl::processItem(const char *type, const char *id,
624                                         const IReferenceDataEntryChecker &checker)
625 {
626     if (shouldIgnore())
627     {
628         return ::testing::AssertionSuccess();
629     }
630     std::string         fullId = appendPath(id);
631     ReferenceDataEntry *entry  = findOrCreateEntry(type, id, checker);
632     if (entry == NULL)
633     {
634         return ::testing::AssertionFailure()
635                << "Reference data item " << fullId << " not found";
636     }
637     entry->setChecked();
638     ::testing::AssertionResult result(checkEntry(*entry, fullId, type, checker));
639     if (outputRootEntry_ != NULL && entry->correspondingOutputEntry() == NULL)
640     {
641         if (!updateMismatchingEntries_ || result)
642         {
643             outputRootEntry_->addChild(entry->cloneToOutputEntry());
644         }
645         else
646         {
647             ReferenceDataEntry::EntryPointer outputEntry(createEntry(type, id, checker));
648             entry->setCorrespondingOutputEntry(outputEntry.get());
649             outputRootEntry_->addChild(move(outputEntry));
650             return ::testing::AssertionSuccess();
651         }
652     }
653     if (bSelfTestMode_ && !result)
654     {
655         ReferenceDataEntry expected(type, id);
656         checker.fillEntry(&expected);
657         result << std::endl
658         << "String value: '" << expected.value() << "'" << std::endl
659         << " Ref. string: '" << entry->value() << "'";
660     }
661     return result;
662 }
663
664
665 /********************************************************************
666  * TestReferenceData
667  */
668
669 TestReferenceData::TestReferenceData()
670     : impl_(initReferenceDataInstance())
671 {
672 }
673
674
675 TestReferenceData::TestReferenceData(ReferenceDataMode mode)
676     : impl_(initReferenceDataInstanceForSelfTest(mode))
677 {
678 }
679
680
681 TestReferenceData::~TestReferenceData()
682 {
683 }
684
685
686 TestReferenceChecker TestReferenceData::rootChecker()
687 {
688     if (!impl_->bInUse_ && !impl_->compareRootEntry_)
689     {
690         ADD_FAILURE() << "Reference data file not found: "
691         << impl_->fullFilename_;
692     }
693     impl_->bInUse_ = true;
694     if (!impl_->compareRootEntry_)
695     {
696         return TestReferenceChecker(new TestReferenceChecker::Impl(true));
697     }
698     impl_->compareRootEntry_->setChecked();
699     return TestReferenceChecker(
700             new TestReferenceChecker::Impl("", impl_->compareRootEntry_.get(),
701                                            impl_->outputRootEntry_.get(),
702                                            impl_->updateMismatchingEntries_, impl_->bSelfTestMode_,
703                                            defaultRealTolerance()));
704 }
705
706
707 /********************************************************************
708  * TestReferenceChecker
709  */
710
711 TestReferenceChecker::TestReferenceChecker()
712     : impl_(new Impl(false))
713 {
714 }
715
716 TestReferenceChecker::TestReferenceChecker(Impl *impl)
717     : impl_(impl)
718 {
719 }
720
721 TestReferenceChecker::TestReferenceChecker(const TestReferenceChecker &other)
722     : impl_(new Impl(*other.impl_))
723 {
724 }
725
726 TestReferenceChecker::TestReferenceChecker(TestReferenceChecker &&other)
727     : impl_(std::move(other.impl_))
728 {
729 }
730
731 TestReferenceChecker &
732 TestReferenceChecker::operator=(TestReferenceChecker &&other)
733 {
734     impl_ = std::move(other.impl_);
735     return *this;
736 }
737
738 TestReferenceChecker::~TestReferenceChecker()
739 {
740 }
741
742 bool TestReferenceChecker::isValid() const
743 {
744     return impl_->initialized();
745 }
746
747
748 void TestReferenceChecker::setDefaultTolerance(
749         const FloatingPointTolerance &tolerance)
750 {
751     impl_->defaultTolerance_ = tolerance;
752 }
753
754
755 void TestReferenceChecker::checkUnusedEntries()
756 {
757     if (impl_->compareRootEntry_)
758     {
759         gmx::test::checkUnusedEntries(*impl_->compareRootEntry_, impl_->path_);
760         // Mark them checked so that they are reported only once.
761         impl_->compareRootEntry_->setCheckedIncludingChildren();
762     }
763 }
764
765
766 bool TestReferenceChecker::checkPresent(bool bPresent, const char *id)
767 {
768     if (impl_->shouldIgnore() || impl_->outputRootEntry_ != NULL)
769     {
770         return bPresent;
771     }
772     ReferenceDataEntry::ChildIterator  entry
773         = impl_->compareRootEntry_->findChild(id, impl_->lastFoundEntry_);
774     const bool                         bFound
775         = impl_->compareRootEntry_->isValidChild(entry);
776     if (bFound != bPresent)
777     {
778         ADD_FAILURE() << "Mismatch while checking reference data item '"
779         << impl_->appendPath(id) << "'\n"
780         << "Expected: " << (bPresent ? "it is present.\n" : "it is absent.\n")
781         << "  Actual: " << (bFound ? "it is present." : "it is absent.");
782     }
783     if (bFound && bPresent)
784     {
785         impl_->lastFoundEntry_ = entry;
786         return true;
787     }
788     return false;
789 }
790
791
792 TestReferenceChecker TestReferenceChecker::checkCompound(const char *type, const char *id)
793 {
794     if (impl_->shouldIgnore())
795     {
796         return TestReferenceChecker(new Impl(true));
797     }
798     std::string         fullId = impl_->appendPath(id);
799     NullChecker         checker;
800     ReferenceDataEntry *entry  = impl_->findOrCreateEntry(type, id, checker);
801     if (entry == NULL)
802     {
803         ADD_FAILURE() << "Reference data item " << fullId << " not found";
804         return TestReferenceChecker(new Impl(true));
805     }
806     entry->setChecked();
807     if (impl_->updateMismatchingEntries_)
808     {
809         entry->makeCompound(type);
810     }
811     else
812     {
813         ::testing::AssertionResult result(impl_->checkEntry(*entry, fullId, type, checker));
814         EXPECT_PLAIN(result);
815         if (!result)
816         {
817             return TestReferenceChecker(new Impl(true));
818         }
819     }
820     if (impl_->outputRootEntry_ != NULL && entry->correspondingOutputEntry() == NULL)
821     {
822         impl_->outputRootEntry_->addChild(entry->cloneToOutputEntry());
823     }
824     return TestReferenceChecker(
825             new Impl(fullId, entry, entry->correspondingOutputEntry(),
826                      impl_->updateMismatchingEntries_, impl_->bSelfTestMode_,
827                      impl_->defaultTolerance_));
828 }
829
830
831 /*! \brief Throw a TestException if the caller tries to write particular refdata that can't work.
832  *
833  * If the string to write is non-empty and has only whitespace,
834  * TinyXML2 can't read it correctly, so throw an exception for this
835  * case, so that we can't accidentally use it and run into mysterious
836  * problems.
837  *
838  * \todo Eliminate this limitation of TinyXML2. See
839  * e.g. https://github.com/leethomason/tinyxml2/issues/432
840  */
841 static void
842 throwIfNonEmptyAndOnlyWhitespace(const std::string &s, const char *id)
843 {
844     if (!s.empty() && std::all_of(s.cbegin(), s.cend(), [](const char &c){ return std::isspace(c); }))
845     {
846         std::string message("String '" + s + "' with ");
847         message += (id != nullptr) ? "null " : "";
848         message += "ID ";
849         message += (id != nullptr) ? "" : id;
850         message += " cannot be handled. We must refuse to write a refdata String"
851             "field for a non-empty string that contains only whitespace, "
852             "because it will not be read correctly by TinyXML2.";
853         GMX_THROW(TestException(message));
854     }
855 }
856
857 void TestReferenceChecker::checkBoolean(bool value, const char *id)
858 {
859     EXPECT_PLAIN(impl_->processItem(Impl::cBooleanNodeName, id,
860                                     ExactStringChecker(value ? "true" : "false")));
861 }
862
863
864 void TestReferenceChecker::checkString(const char *value, const char *id)
865 {
866     throwIfNonEmptyAndOnlyWhitespace(value, id);
867     EXPECT_PLAIN(impl_->processItem(Impl::cStringNodeName, id,
868                                     ExactStringChecker(value)));
869 }
870
871
872 void TestReferenceChecker::checkString(const std::string &value, const char *id)
873 {
874     throwIfNonEmptyAndOnlyWhitespace(value, id);
875     EXPECT_PLAIN(impl_->processItem(Impl::cStringNodeName, id,
876                                     ExactStringChecker(value)));
877 }
878
879
880 void TestReferenceChecker::checkTextBlock(const std::string &value,
881                                           const char        *id)
882 {
883     EXPECT_PLAIN(impl_->processItem(Impl::cStringNodeName, id,
884                                     ExactStringBlockChecker(value)));
885 }
886
887
888 void TestReferenceChecker::checkInteger(int value, const char *id)
889 {
890     EXPECT_PLAIN(impl_->processItem(Impl::cIntegerNodeName, id,
891                                     ExactStringChecker(formatString("%d", value))));
892 }
893
894 void TestReferenceChecker::checkInt64(gmx_int64_t value, const char *id)
895 {
896     EXPECT_PLAIN(impl_->processItem(Impl::cInt64NodeName, id,
897                                     ExactStringChecker(formatString("%" GMX_PRId64, value))));
898 }
899
900 void TestReferenceChecker::checkUInt64(gmx_uint64_t value, const char *id)
901 {
902     EXPECT_PLAIN(impl_->processItem(Impl::cUInt64NodeName, id,
903                                     ExactStringChecker(formatString("%" GMX_PRIu64, value))));
904 }
905
906 void TestReferenceChecker::checkDouble(double value, const char *id)
907 {
908     FloatingPointChecker<double> checker(value, impl_->defaultTolerance_);
909     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, checker));
910 }
911
912
913 void TestReferenceChecker::checkFloat(float value, const char *id)
914 {
915     FloatingPointChecker<float> checker(value, impl_->defaultTolerance_);
916     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, checker));
917 }
918
919
920 void TestReferenceChecker::checkReal(float value, const char *id)
921 {
922     checkFloat(value, id);
923 }
924
925
926 void TestReferenceChecker::checkReal(double value, const char *id)
927 {
928     checkDouble(value, id);
929 }
930
931
932 void TestReferenceChecker::checkRealFromString(const std::string &value, const char *id)
933 {
934     FloatingPointFromStringChecker<real> checker(value, impl_->defaultTolerance_);
935     EXPECT_PLAIN(impl_->processItem(Impl::cRealNodeName, id, checker));
936 }
937
938
939 void TestReferenceChecker::checkVector(const int value[3], const char *id)
940 {
941     TestReferenceChecker compound(checkCompound(Impl::cVectorType, id));
942     compound.checkInteger(value[0], "X");
943     compound.checkInteger(value[1], "Y");
944     compound.checkInteger(value[2], "Z");
945 }
946
947
948 void TestReferenceChecker::checkVector(const float value[3], const char *id)
949 {
950     TestReferenceChecker compound(checkCompound(Impl::cVectorType, id));
951     compound.checkReal(value[0], "X");
952     compound.checkReal(value[1], "Y");
953     compound.checkReal(value[2], "Z");
954 }
955
956
957 void TestReferenceChecker::checkVector(const double 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::checkVariant(const Variant &variant, const char *id)
967 {
968     if (variant.isType<bool>())
969     {
970         checkBoolean(variant.cast<bool>(), id);
971     }
972     else if (variant.isType<int>())
973     {
974         checkInteger(variant.cast<int>(), id);
975     }
976     else if (variant.isType<float>())
977     {
978         checkFloat(variant.cast<float>(), id);
979     }
980     else if (variant.isType<double>())
981     {
982         checkDouble(variant.cast<double>(), id);
983     }
984     else if (variant.isType<std::string>())
985     {
986         checkString(variant.cast<std::string>(), id);
987     }
988     else
989     {
990         GMX_THROW(TestException("Unsupported variant type"));
991     }
992 }
993
994
995 void TestReferenceChecker::checkKeyValueTreeObject(const KeyValueTreeObject &tree, const char *id)
996 {
997     TestReferenceChecker compound(checkCompound(Impl::cObjectType, id));
998     for (const auto &prop : tree.properties())
999     {
1000         compound.checkKeyValueTreeValue(prop.value(), prop.key().c_str());
1001     }
1002     compound.checkUnusedEntries();
1003 }
1004
1005
1006 void TestReferenceChecker::checkKeyValueTreeValue(const KeyValueTreeValue &value, const char *id)
1007 {
1008     if (value.isObject())
1009     {
1010         checkKeyValueTreeObject(value.asObject(), id);
1011     }
1012     else if (value.isArray())
1013     {
1014         const auto &values = value.asArray().values();
1015         checkSequence(values.begin(), values.end(), id);
1016     }
1017     else
1018     {
1019         checkVariant(value.asVariant(), id);
1020     }
1021 }
1022
1023
1024 TestReferenceChecker
1025 TestReferenceChecker::checkSequenceCompound(const char *id, size_t length)
1026 {
1027     TestReferenceChecker compound(checkCompound(Impl::cSequenceType, id));
1028     compound.checkInteger(static_cast<int>(length), Impl::cSequenceLengthName);
1029     return compound;
1030 }
1031
1032 } // namespace test
1033 } // namespace gmx