Teuchos - Trilinos Tools Package  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Teuchos_UnitTestRepository.cpp
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Teuchos: Common Tools Package
5 // Copyright (2004) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ***********************************************************************
40 // @HEADER
41 
42 
44 #include "Teuchos_UnitTestBase.hpp"
46 #include "Teuchos_Array.hpp"
47 #include "Teuchos_Assert.hpp"
48 #include "Teuchos_VerboseObject.hpp"
50 #include "Teuchos_Assert.hpp"
51 #include "Teuchos_Time.hpp"
52 #include "Teuchos_StandardCatchMacros.hpp"
53 
54 
55 namespace Teuchos {
56 
57 
58 struct UnitTestData {
59 
60  const Teuchos::UnitTestBase * unitTest;
61  std::string groupName;
62  std::string testName;
63  int insertionIndex;
64 
65  UnitTestData(
66  Teuchos::UnitTestBase *unitTest_in,
67  const std::string groupName_in,
68  const std::string testName_in
69  )
70  : unitTest(unitTest_in), groupName(groupName_in), testName(testName_in),
71  insertionIndex(insersionIndexCounter_++)
72  {
73 #ifdef TEUCHOS_DEBUG
74  TEUCHOS_ASSERT(unitTest_in);
75 #endif
76  }
77 
78 private:
79  UnitTestData(); // Not defined!
80  static int insersionIndexCounter_;
81 };
82 
83 
84 int UnitTestData::insersionIndexCounter_ = 0;
85 
86 
87 bool operator<(const UnitTestData &a, const UnitTestData &b)
88 {
89  if (a.groupName < b.groupName) {
90  return true;
91  }
92  else if (a.groupName > b.groupName) {
93  return false;
94  }
95  return a.insertionIndex < b.insertionIndex;
96 }
97 
98 
99 
100 std::string getUnitTestName(const std::string groupName,
101  const std::string testName)
102 {
103  std::ostringstream oss;
104  oss << groupName<<"_"<<testName<<"_UnitTest";
105  return oss.str();
106 }
107 
108 
109 enum EShowTestDetails {
110  SHOW_TEST_DETAILS_ALL,
111  SHOW_TEST_DETAILS_TEST_NAMES,
112  SHOW_TEST_DETAILS_FINAL_RESULTS
113 };
114 
115 
116 bool strMatch( const std::string &fullMatchStr, const std::string &str )
117 {
118 
119  const std::string::size_type npos = std::string::npos;
120 
121  const int strLen = str.length();
122  const int fullMatchStrLen = fullMatchStr.length();
123 
124  if (fullMatchStrLen == 0) {
125  return true;
126  }
127 
128  const bool beginGlob = fullMatchStr[0] == '*';
129  const bool endGlob = fullMatchStr[fullMatchStrLen-1] == '*';
130 
131  const int matchStrLen =
132  fullMatchStrLen + (beginGlob ? -1 : 0) + (endGlob ? -1 : 0);
133 
134  if (matchStrLen == 0) {
135  return true;
136  }
137 
138  if (matchStrLen > strLen) {
139  return false;
140  }
141 
142  if (beginGlob && endGlob) {
143  return str.find(fullMatchStr.substr(1, matchStrLen)) != npos;
144  }
145 
146  if (endGlob) {
147  return fullMatchStr.substr(0, matchStrLen) == str.substr(0, matchStrLen);
148  }
149 
150  if (beginGlob) {
151  return fullMatchStr.substr(1, matchStrLen) ==
152  str.substr(strLen-matchStrLen, matchStrLen);
153  }
154 
155  return fullMatchStr == str;
156 
157 }
158 
159 
160 } // namespace Teuchos
161 
162 
163 
164 
165 namespace Teuchos {
166 
167 
168 // Implementation class
169 
170 
171 class UnitTestRepository::InstanceData {
172 public:
173 
174  typedef Teuchos::Array<UnitTestData> unitTests_t;
175 
176  unitTests_t unitTests;
177  CommandLineProcessor clp;
178  EShowTestDetails showTestDetails;
179  bool globallyReduceUnitTestResult;
180  bool showSrcLocation;
181  bool showFailSrcLocation;
182  bool noOp;
183  std::string groupName;
184  std::string testName;
185  std::string notUnitTestName;
186  int testCounter;
187 
188  InstanceData()
189  :clp(false),
190  showTestDetails(SHOW_TEST_DETAILS_TEST_NAMES),
191  globallyReduceUnitTestResult(false),
192  showSrcLocation(false),
193  showFailSrcLocation(true),
194  noOp(false),
195  testCounter(0)
196  {}
197 
198 };
199 
200 
201 // public
202 
203 
205 {
206  return getData().clp;
207 }
208 
209 
211  const bool globallyReduceUnitTestResult)
212 {
213  getData().globallyReduceUnitTestResult = globallyReduceUnitTestResult;
214 }
215 
216 
218 {
219  return getData().globallyReduceUnitTestResult;
220 }
221 
222 
224 {
225 
226  typedef InstanceData::unitTests_t unitTests_t;
227 
228  using std::setprecision;
229 
230  Time overallTimer("overallTimer", true);
231  Time timer("timer");
232 
233  const int timerPrec = 3;
234 
235  out << "\n***\n*** Unit test suite ...\n***\n\n";
236 
237  InstanceData &data = getData();
238 
239  const bool showAll = data.showTestDetails == SHOW_TEST_DETAILS_ALL;
240  const bool showTestNames = data.showTestDetails == SHOW_TEST_DETAILS_TEST_NAMES || showAll;
241 
242  showTestFailureLocation(data.showFailSrcLocation);
243 
244  bool success = true;
245  int testCounter = 0;
246  int numTestsRun = 0;
247  int numTestsFailed = 0;
248 
249  Array<std::string> failedTests;
250 
251  try {
252 
253  out << "\nSorting tests by group name then by the order they were added ...";
254  timer.start(true);
255  std::sort( data.unitTests.begin(), data.unitTests.end() );
256  timer.stop();
257  out << " (time = "<<setprecision(timerPrec)<<timer.totalElapsedTime()<<")\n";
258 
259  out << "\nRunning unit tests ...\n\n";
260  unitTests_t::iterator iter = data.unitTests.begin();
261  for ( ; iter != data.unitTests.end(); ++iter, ++testCounter ) {
262 
263  const UnitTestData &utd = (*iter);
264 
265  const std::string unitTestName = getUnitTestName(utd.groupName, utd.testName);
266 
267  if (
268  (
269  strMatch(data.groupName, utd.groupName)
270  &&
271  strMatch(data.testName, utd.testName)
272  )
273  &&
274  (
275  data.notUnitTestName.length() == 0
276  ||
277  !strMatch(data.notUnitTestName, unitTestName)
278  )
279  )
280  {
281 
282  ++numTestsRun;
283 
284  std::ostringstream testHeaderOSS;
285  testHeaderOSS <<testCounter<<". "<<unitTestName<<" ... ";
286  const std::string testHeader = testHeaderOSS.str();
287 
288  if (showAll)
289  out <<"\n";
290 
291  if (showTestNames)
292  out <<testHeader<<std::flush;
293 
294  {
295 
297  RCP<FancyOStream> localOut;
298  if (showAll) {
299  out << "\n";
300  localOut = rcpFromRef(out);
301  }
302  else {
303  oss = rcp(new std::ostringstream);
304  localOut = fancyOStream(rcp_implicit_cast<std::ostream>(oss));
305  }
306 
307  OSTab tab(out);
308 
309  if (!data.noOp) {
310 
311  timer.start(true);
312  const bool result = runUnitTestImpl(*utd.unitTest, *localOut);
313  timer.stop();
314 
315  if (!result) {
316 
317  failedTests.push_back(testHeader);
318 
319  if (!showTestNames)
320  out <<testHeader<<"\n"<<std::flush;
321  else if (!showAll)
322  out <<"\n";
323 
324  if (!is_null(oss))
325  out << oss->str();
326 
327  out
328  <<"[FAILED] "
329  <<" "<<setprecision(timerPrec)<<"("<<timer.totalElapsedTime()<< " sec)"
330  <<" "<<unitTestName<<"\n"
331  <<"Location: "<<utd.unitTest->unitTestFile()<<":"
332  <<utd.unitTest->unitTestFileLineNumber()<<"\n";
333 
334  if (!is_null(oss))
335  out << "\n";
336 
337  success = false;
338 
339  ++numTestsFailed;
340 
341  }
342  else {
343 
344  if (showTestNames)
345  out << "[Passed] "
346  << setprecision(timerPrec)<<"("<<timer.totalElapsedTime()<<" sec)\n";
347 
348  if (showAll && data.showSrcLocation)
349  out
350  << "Location: "<<utd.unitTest->unitTestFile()<<":"
351  <<utd.unitTest->unitTestFileLineNumber()<<"\n";
352 
353  }
354 
355  }
356  else {
357 
358  if (showTestNames)
359  out << "[Not Run]\n";
360 
361  }
362 
363  }
364 
365  }
366 
367  }
368 
369  TEUCHOS_ASSERT_EQUALITY(testCounter, as<int>(data.unitTests.size()));
370 
371  }
372  TEUCHOS_STANDARD_CATCH_STATEMENTS(true, out, success);
373 
374  if (failedTests.size()) {
375  out << "\nThe following tests FAILED:\n";
376  for (Teuchos_Ordinal i = 0; i < failedTests.size(); ++i)
377  out << " " << failedTests[i] << "\n";
378  }
379 
380  overallTimer.stop();
381  out << "\nTotal Time: " << setprecision(timerPrec)
382  << overallTimer.totalElapsedTime() << " sec\n";
383 
384  out
385  << "\nSummary: total = " << testCounter
386  << ", run = " << numTestsRun;
387 
388  if (!data.noOp) {
389  out
390  << ", passed = " << (numTestsRun-numTestsFailed)
391  << ", failed = " << numTestsFailed << "\n";
392  }
393  else {
394  out
395  << ", passed = ???"
396  << ", failed = ???\n";
397  }
398 
399  return success;
400 
401 }
402 
403 
404 int UnitTestRepository::runUnitTestsFromMain( int argc, char* argv[] )
405 {
406 
408 
409  CommandLineProcessor &clp = getData().clp;
410  setUpCLP(outArg(clp));
412  clp.parse(argc,argv);
413  if ( parse_return != CommandLineProcessor::PARSE_SUCCESSFUL ) {
414  *out << "\nEnd Result: TEST FAILED" << std::endl;
415  return parse_return;
416  }
417 
418  const bool success = runUnitTests(*out);
419 
420  if (success)
421  *out << "\nEnd Result: TEST PASSED" << std::endl;
422  else
423  *out << "\nEnd Result: TEST FAILED" << std::endl;
424 
425  clp.printFinalTimerSummary(out.ptr());
426 
427  return (success ? 0 : 1);
428 
429 }
430 
431 
433  const std::string groupName, const std::string testName_in )
434 {
435  InstanceData &data = getData();
436  std::string testName = testName_in;
437  data.unitTests.push_back(UnitTestData(unitTest, groupName, testName));
438 }
439 
440 
442 {
443  return (getData().showTestDetails == SHOW_TEST_DETAILS_ALL);
444 }
445 
446 
447 // private:
448 
449 
450 UnitTestRepository::UnitTestRepository()
451 {}
452 
453 
454 void UnitTestRepository::setUpCLP(const Ptr<CommandLineProcessor>& clp)
455 {
456 
457  clp->addOutputSetupOptions(true);
458 
459  const int numShowTestDetails = 3;
460  const EShowTestDetails showTestDetailsValues[numShowTestDetails] =
461  { SHOW_TEST_DETAILS_ALL,
462  SHOW_TEST_DETAILS_TEST_NAMES,
463  SHOW_TEST_DETAILS_FINAL_RESULTS
464  };
465  const char* showTestDetailsNames[numShowTestDetails] =
466  { "ALL",
467  "TEST_NAMES",
468  "FINAL_RESULTS"
469  };
470  clp->setOption(
471  "show-test-details", &getData().showTestDetails,
472  numShowTestDetails, showTestDetailsValues, showTestDetailsNames,
473  "Level of detail to show in the tests"
474  );
475  clp->setOption(
476  "details", &getData().showTestDetails,
477  numShowTestDetails, showTestDetailsValues, showTestDetailsNames,
478  "Short for --show-test-details"
479  );
480 
481  clp->setOption(
482  "show-src-location", "no-show-src-location", &getData().showSrcLocation,
483  "If true, then the location of the unit test source code is shown."
484  " Only meaningfull if --show-test-details=ALL."
485  );
486 
487  clp->setOption(
488  "show-fail-src-location", "no-show-fail-src-location", &getData().showFailSrcLocation,
489  "If true, then the location of every failed unit test check is printed."
490  );
491 
492  clp->setOption(
493  "globally-reduce-test-result", "no-globally-reduce-test-result",
494  &getData().globallyReduceUnitTestResult,
495  "If true, individual unit test pass/fail is globally reduced across MPI processes."
496  );
497 
498  clp->setOption(
499  "group-name", &getData().groupName,
500  "If specified, selects only tests that match the group name glob." );
501  clp->setOption(
502  "group", &getData().groupName,
503  "Short for --group-name." );
504 
505  clp->setOption(
506  "test-name", &getData().testName,
507  "If specified, selects only tests that match the test name glob." );
508  clp->setOption(
509  "test", &getData().testName,
510  "Short for --test-name." );
511 
512  clp->setOption(
513  "not-unit-test", &getData().notUnitTestName,
514  "If specified, full unit tests with glob matches will *not* be run." );
515 
516  clp->setOption(
517  "no-op", "do-op", &getData().noOp,
518  "If --no-op, then only the names of the tests that would be run are run."
519  );
520 
521 }
522 
523 
524 UnitTestRepository::InstanceData& UnitTestRepository::getData()
525 {
526  static UnitTestRepository::InstanceData data;
527  return data;
528 }
529 
530 
531 bool UnitTestRepository::runUnitTestImpl(const UnitTestBase &unitTest,
532  FancyOStream &out)
533 {
534  const bool result = unitTest.runUnitTest(out);
535  if (getData().globallyReduceUnitTestResult) {
536  const int globalSum = GlobalMPISession::sum(result ? 0 : 1);
537  if (globalSum == 0) {
538  return true;
539  }
540  else {
541  // Only print that there are failures on processes where the local
542  // unit test actally passed. On processes where the local unit test
543  // fails, users already know that test failed so there is no need to
544  // exlain it.
545  if (result) {
546  out << "NOTE: Global reduction shows failures on other processes!\n"
547  << "(rerun with --output-to-root-rank-only=-1 to see output\n"
548  << "from other processes to see what process failed!)\n";
549  }
550  else {
551  // The test failed on the root process so the user already knows it failed!
552  }
553  // Determine what processes have failing tests
554  const int numProcs = GlobalMPISession::getNProc();
555  Array<int> passFailFlags(numProcs);
556  GlobalMPISession::allGather( result ? 0 : 1, passFailFlags());
557  Array<int> procsThatFailed;
558  for ( int proc_k = 0; proc_k < numProcs; ++proc_k ) {
559  if (passFailFlags[proc_k] != 0) {
560  procsThatFailed.push_back(proc_k);
561  }
562  }
563  // Print what processes have the failing tests. If there is only one
564  // processes, don't print anything.
565  if (numProcs > 1) {
566  if (procsThatFailed.size() == numProcs) {
567  out << "NOTE: Unit test failed on all processes!\n";
568  // NOTE: when all the processes are failing it is useless to print
569  // out a list of all of the processes.
570  }
571  else {
572  out << "NOTE: Unit test failed on processes = " << procsThatFailed << "\n"
573  << "(rerun with --output-to-root-rank-only=<procID> to see output\n"
574  << "from individual processes where the unit test is failing!)\n";
575  }
576  }
577  return false;
578  }
579  }
580  return result;
581 }
582 
583 
584 } // namespace Teuchos
bool is_null(const boost::shared_ptr< T > &p)
Returns true if p.get()==NULL.
static bool verboseUnitTests()
Returns if unit tests are verbose or not.
static int getNProc()
Returns the number of processors relative to MPI_COMM_WORLD
static CommandLineProcessor & getCLP()
Return the CLP to add options to.
Basic wall-clock timer class.
Unit testing support.
basic_FancyOStream< char > FancyOStream
Tabbing class for helping to create formated, indented output for a basic_FancyOStream object...
static void addUnitTest(UnitTestBase *unitTest, const std::string groupName, const std::string testName)
Add an unit test (called indirectly through macros.
Unit testing support.
void showTestFailureLocation(bool)
Set if TEUCHOS_PASS_FAIL(...) should print test failure location.
static int runUnitTestsFromMain(int argc, char *argv[])
Run the unit tests from main() passing in (argc, argv).
void start(bool reset=false)
Start the timer, if the timer is enabled (see disable()).
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Deprecated.
double stop()
Stop the timer, if the timer is enabled (see disable()).
std::ostream subclass that performs the magic of indenting data sent to an std::ostream object among ...
Wall-clock timer.
Ptr< T > ptr() const
Get a safer wrapper raw C++ pointer to the underlying object.
static RCP< FancyOStream > getDefaultOStream()
Get the default output stream object.
EParseCommandLineReturn parse(int argc, char *argv[], std::ostream *errout=&std::cerr) const
Parse a command line.
static void setGloballyReduceTestResult(const bool globallyReduceUnitTestResult)
Set if the unit tests should reduce pass/fail across processes.
static int sum(int localVal)
Sum a set of integers across processes.
EParseCommandLineReturn
Return value for CommandLineProcessor::parse(). Note: These enums are all given non-negative values s...
Templated array class derived from the STL std::vector.
Utilities to make writing tests easier.
static bool runUnitTests(FancyOStream &out)
Run the registered unit tests.
void push_back(const value_type &x)
Basic command line parser for input from (argc,argv[])
static bool getGloballyReduceTestResult()
Get if the unit tests should reduce across processes or not.
size_type size() const
double totalElapsedTime(bool readCurrentTime=false) const
The total time in seconds accumulated by this timer.
static void allGather(int localVal, const ArrayView< int > &allVals)
Global all-to-all of a set of integers across processes.
void printFinalTimerSummary(const Ptr< std::ostream > &out=null)
Call to print timers so that they don&#39;t get printed in the destructor.
#define TEUCHOS_STANDARD_CATCH_STATEMENTS(VERBOSE, ERR_STREAM, SUCCESS_FLAG)
Simple macro that catches and reports standard exceptions and other exceptions.
#define TEUCHOS_ASSERT(assertion_test)
This macro is throws when an assert fails.
#define TEUCHOS_ASSERT_EQUALITY(val1, val2)
This macro is checks that to numbers are equal and if not then throws an exception with a good error ...
Unit test base class.
Class that helps parse command line input arguments from (argc,argv[]) and set options.