gen_gtest_pred_impl.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2006, Google Inc.
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. #
  10. # * Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # * Redistributions in binary form must reproduce the above
  13. # copyright notice, this list of conditions and the following disclaimer
  14. # in the documentation and/or other materials provided with the
  15. # distribution.
  16. # * Neither the name of Google Inc. nor the names of its
  17. # contributors may be used to endorse or promote products derived from
  18. # this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """gen_gtest_pred_impl.py v0.1
  32. Generates the implementation of Google Test predicate assertions and
  33. accompanying tests.
  34. Usage:
  35. gen_gtest_pred_impl.py MAX_ARITY
  36. where MAX_ARITY is a positive integer.
  37. The command generates the implementation of up-to MAX_ARITY-ary
  38. predicate assertions, and writes it to file gtest_pred_impl.h in the
  39. directory where the script is. It also generates the accompanying
  40. unit test in file gtest_pred_impl_unittest.cc.
  41. """
  42. __author__ = 'wan@google.com (Zhanyong Wan)'
  43. import os
  44. import sys
  45. import time
  46. # Where this script is.
  47. SCRIPT_DIR = os.path.dirname(sys.argv[0])
  48. # Where to store the generated header.
  49. HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
  50. # Where to store the generated unit test.
  51. UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
  52. def HeaderPreamble(n):
  53. """Returns the preamble for the header file.
  54. Args:
  55. n: the maximum arity of the predicate macros to be generated.
  56. """
  57. # A map that defines the values used in the preamble template.
  58. DEFS = {
  59. 'today' : time.strftime('%m/%d/%Y'),
  60. 'year' : time.strftime('%Y'),
  61. 'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
  62. 'n' : n
  63. }
  64. return (
  65. """// Copyright 2006, Google Inc.
  66. // All rights reserved.
  67. //
  68. // Redistribution and use in source and binary forms, with or without
  69. // modification, are permitted provided that the following conditions are
  70. // met:
  71. //
  72. // * Redistributions of source code must retain the above copyright
  73. // notice, this list of conditions and the following disclaimer.
  74. // * Redistributions in binary form must reproduce the above
  75. // copyright notice, this list of conditions and the following disclaimer
  76. // in the documentation and/or other materials provided with the
  77. // distribution.
  78. // * Neither the name of Google Inc. nor the names of its
  79. // contributors may be used to endorse or promote products derived from
  80. // this software without specific prior written permission.
  81. //
  82. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  83. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  84. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  85. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  86. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  87. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  88. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  89. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  90. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  91. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  92. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  93. // This file is AUTOMATICALLY GENERATED on %(today)s by command
  94. // '%(command)s'. DO NOT EDIT BY HAND!
  95. //
  96. // Implements a family of generic predicate assertion macros.
  97. // GOOGLETEST_CM0001 DO NOT DELETE
  98. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  99. #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  100. #include "gtest/gtest.h"
  101. namespace testing {
  102. // This header implements a family of generic predicate assertion
  103. // macros:
  104. //
  105. // ASSERT_PRED_FORMAT1(pred_format, v1)
  106. // ASSERT_PRED_FORMAT2(pred_format, v1, v2)
  107. // ...
  108. //
  109. // where pred_format is a function or functor that takes n (in the
  110. // case of ASSERT_PRED_FORMATn) values and their source expression
  111. // text, and returns a testing::AssertionResult. See the definition
  112. // of ASSERT_EQ in gtest.h for an example.
  113. //
  114. // If you don't care about formatting, you can use the more
  115. // restrictive version:
  116. //
  117. // ASSERT_PRED1(pred, v1)
  118. // ASSERT_PRED2(pred, v1, v2)
  119. // ...
  120. //
  121. // where pred is an n-ary function or functor that returns bool,
  122. // and the values v1, v2, ..., must support the << operator for
  123. // streaming to std::ostream.
  124. //
  125. // We also define the EXPECT_* variations.
  126. //
  127. // For now we only support predicates whose arity is at most %(n)s.
  128. // Please email googletestframework@googlegroups.com if you need
  129. // support for higher arities.
  130. // GTEST_ASSERT_ is the basic statement to which all of the assertions
  131. // in this file reduce. Don't use this in your code.
  132. #define GTEST_ASSERT_(expression, on_failure) \\
  133. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
  134. if (const ::testing::AssertionResult gtest_ar = (expression)) \\
  135. ; \\
  136. else \\
  137. on_failure(gtest_ar.failure_message())
  138. """ % DEFS)
  139. def Arity(n):
  140. """Returns the English name of the given arity."""
  141. if n < 0:
  142. return None
  143. elif n <= 3:
  144. return ['nullary', 'unary', 'binary', 'ternary'][n]
  145. else:
  146. return '%s-ary' % n
  147. def Title(word):
  148. """Returns the given word in title case. The difference between
  149. this and string's title() method is that Title('4-ary') is '4-ary'
  150. while '4-ary'.title() is '4-Ary'."""
  151. return word[0].upper() + word[1:]
  152. def OneTo(n):
  153. """Returns the list [1, 2, 3, ..., n]."""
  154. return range(1, n + 1)
  155. def Iter(n, format, sep=''):
  156. """Given a positive integer n, a format string that contains 0 or
  157. more '%s' format specs, and optionally a separator string, returns
  158. the join of n strings, each formatted with the format string on an
  159. iterator ranged from 1 to n.
  160. Example:
  161. Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
  162. """
  163. # How many '%s' specs are in format?
  164. spec_count = len(format.split('%s')) - 1
  165. return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
  166. def ImplementationForArity(n):
  167. """Returns the implementation of n-ary predicate assertions."""
  168. # A map the defines the values used in the implementation template.
  169. DEFS = {
  170. 'n' : str(n),
  171. 'vs' : Iter(n, 'v%s', sep=', '),
  172. 'vts' : Iter(n, '#v%s', sep=', '),
  173. 'arity' : Arity(n),
  174. 'Arity' : Title(Arity(n))
  175. }
  176. impl = """
  177. // Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use
  178. // this in your code.
  179. template <typename Pred""" % DEFS
  180. impl += Iter(n, """,
  181. typename T%s""")
  182. impl += """>
  183. AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
  184. impl += Iter(n, """,
  185. const char* e%s""")
  186. impl += """,
  187. Pred pred"""
  188. impl += Iter(n, """,
  189. const T%s& v%s""")
  190. impl += """) {
  191. if (pred(%(vs)s)) return AssertionSuccess();
  192. """ % DEFS
  193. impl += ' return AssertionFailure() << pred_text << "("'
  194. impl += Iter(n, """
  195. << e%s""", sep=' << ", "')
  196. impl += ' << ") evaluates to false, where"'
  197. impl += Iter(
  198. n, """
  199. << "\\n" << e%s << " evaluates to " << ::testing::PrintToString(v%s)"""
  200. )
  201. impl += """;
  202. }
  203. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
  204. // Don't use this in your code.
  205. #define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
  206. GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\
  207. on_failure)
  208. // Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use
  209. // this in your code.
  210. #define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
  211. GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
  212. impl += Iter(n, """, \\
  213. #v%s""")
  214. impl += """, \\
  215. pred"""
  216. impl += Iter(n, """, \\
  217. v%s""")
  218. impl += """), on_failure)
  219. // %(Arity)s predicate assertion macros.
  220. #define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
  221. GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
  222. #define EXPECT_PRED%(n)s(pred, %(vs)s) \\
  223. GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
  224. #define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
  225. GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
  226. #define ASSERT_PRED%(n)s(pred, %(vs)s) \\
  227. GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
  228. """ % DEFS
  229. return impl
  230. def HeaderPostamble():
  231. """Returns the postamble for the header file."""
  232. return """
  233. } // namespace testing
  234. #endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  235. """
  236. def GenerateFile(path, content):
  237. """Given a file path and a content string
  238. overwrites it with the given content.
  239. """
  240. print 'Updating file %s . . .' % path
  241. f = file(path, 'w+')
  242. print >>f, content,
  243. f.close()
  244. print 'File %s has been updated.' % path
  245. def GenerateHeader(n):
  246. """Given the maximum arity n, updates the header file that implements
  247. the predicate assertions.
  248. """
  249. GenerateFile(HEADER,
  250. HeaderPreamble(n)
  251. + ''.join([ImplementationForArity(i) for i in OneTo(n)])
  252. + HeaderPostamble())
  253. def UnitTestPreamble():
  254. """Returns the preamble for the unit test file."""
  255. # A map that defines the values used in the preamble template.
  256. DEFS = {
  257. 'today' : time.strftime('%m/%d/%Y'),
  258. 'year' : time.strftime('%Y'),
  259. 'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
  260. }
  261. return (
  262. """// Copyright 2006, Google Inc.
  263. // All rights reserved.
  264. //
  265. // Redistribution and use in source and binary forms, with or without
  266. // modification, are permitted provided that the following conditions are
  267. // met:
  268. //
  269. // * Redistributions of source code must retain the above copyright
  270. // notice, this list of conditions and the following disclaimer.
  271. // * Redistributions in binary form must reproduce the above
  272. // copyright notice, this list of conditions and the following disclaimer
  273. // in the documentation and/or other materials provided with the
  274. // distribution.
  275. // * Neither the name of Google Inc. nor the names of its
  276. // contributors may be used to endorse or promote products derived from
  277. // this software without specific prior written permission.
  278. //
  279. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  280. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  281. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  282. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  283. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  284. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  285. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  286. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  287. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  288. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  289. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  290. // This file is AUTOMATICALLY GENERATED on %(today)s by command
  291. // '%(command)s'. DO NOT EDIT BY HAND!
  292. // Regression test for gtest_pred_impl.h
  293. //
  294. // This file is generated by a script and quite long. If you intend to
  295. // learn how Google Test works by reading its unit tests, read
  296. // gtest_unittest.cc instead.
  297. //
  298. // This is intended as a regression test for the Google Test predicate
  299. // assertions. We compile it as part of the gtest_unittest target
  300. // only to keep the implementation tidy and compact, as it is quite
  301. // involved to set up the stage for testing Google Test using Google
  302. // Test itself.
  303. //
  304. // Currently, gtest_unittest takes ~11 seconds to run in the testing
  305. // daemon. In the future, if it grows too large and needs much more
  306. // time to finish, we should consider separating this file into a
  307. // stand-alone regression test.
  308. #include <iostream>
  309. #include "gtest/gtest.h"
  310. #include "gtest/gtest-spi.h"
  311. // A user-defined data type.
  312. struct Bool {
  313. explicit Bool(int val) : value(val != 0) {}
  314. bool operator>(int n) const { return value > Bool(n).value; }
  315. Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
  316. bool operator==(const Bool& rhs) const { return value == rhs.value; }
  317. bool value;
  318. };
  319. // Enables Bool to be used in assertions.
  320. std::ostream& operator<<(std::ostream& os, const Bool& x) {
  321. return os << (x.value ? "true" : "false");
  322. }
  323. """ % DEFS)
  324. def TestsForArity(n):
  325. """Returns the tests for n-ary predicate assertions."""
  326. # A map that defines the values used in the template for the tests.
  327. DEFS = {
  328. 'n' : n,
  329. 'es' : Iter(n, 'e%s', sep=', '),
  330. 'vs' : Iter(n, 'v%s', sep=', '),
  331. 'vts' : Iter(n, '#v%s', sep=', '),
  332. 'tvs' : Iter(n, 'T%s v%s', sep=', '),
  333. 'int_vs' : Iter(n, 'int v%s', sep=', '),
  334. 'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
  335. 'types' : Iter(n, 'typename T%s', sep=', '),
  336. 'v_sum' : Iter(n, 'v%s', sep=' + '),
  337. 'arity' : Arity(n),
  338. 'Arity' : Title(Arity(n)),
  339. }
  340. tests = (
  341. """// Sample functions/functors for testing %(arity)s predicate assertions.
  342. // A %(arity)s predicate function.
  343. template <%(types)s>
  344. bool PredFunction%(n)s(%(tvs)s) {
  345. return %(v_sum)s > 0;
  346. }
  347. // The following two functions are needed because a compiler doesn't have
  348. // a context yet to know which template function must be instantiated.
  349. bool PredFunction%(n)sInt(%(int_vs)s) {
  350. return %(v_sum)s > 0;
  351. }
  352. bool PredFunction%(n)sBool(%(Bool_vs)s) {
  353. return %(v_sum)s > 0;
  354. }
  355. """ % DEFS)
  356. tests += """
  357. // A %(arity)s predicate functor.
  358. struct PredFunctor%(n)s {
  359. template <%(types)s>
  360. bool operator()(""" % DEFS
  361. tests += Iter(n, 'const T%s& v%s', sep=""",
  362. """)
  363. tests += """) {
  364. return %(v_sum)s > 0;
  365. }
  366. };
  367. """ % DEFS
  368. tests += """
  369. // A %(arity)s predicate-formatter function.
  370. template <%(types)s>
  371. testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
  372. tests += Iter(n, 'const char* e%s', sep=""",
  373. """)
  374. tests += Iter(n, """,
  375. const T%s& v%s""")
  376. tests += """) {
  377. if (PredFunction%(n)s(%(vs)s))
  378. return testing::AssertionSuccess();
  379. return testing::AssertionFailure()
  380. << """ % DEFS
  381. tests += Iter(n, 'e%s', sep=' << " + " << ')
  382. tests += """
  383. << " is expected to be positive, but evaluates to "
  384. << %(v_sum)s << ".";
  385. }
  386. """ % DEFS
  387. tests += """
  388. // A %(arity)s predicate-formatter functor.
  389. struct PredFormatFunctor%(n)s {
  390. template <%(types)s>
  391. testing::AssertionResult operator()(""" % DEFS
  392. tests += Iter(n, 'const char* e%s', sep=""",
  393. """)
  394. tests += Iter(n, """,
  395. const T%s& v%s""")
  396. tests += """) const {
  397. return PredFormatFunction%(n)s(%(es)s, %(vs)s);
  398. }
  399. };
  400. """ % DEFS
  401. tests += """
  402. // Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
  403. class Predicate%(n)sTest : public testing::Test {
  404. protected:
  405. void SetUp() override {
  406. expected_to_finish_ = true;
  407. finished_ = false;""" % DEFS
  408. tests += """
  409. """ + Iter(n, 'n%s_ = ') + """0;
  410. }
  411. """
  412. tests += """
  413. void TearDown() override {
  414. // Verifies that each of the predicate's arguments was evaluated
  415. // exactly once."""
  416. tests += ''.join(["""
  417. EXPECT_EQ(1, n%s_) <<
  418. "The predicate assertion didn't evaluate argument %s "
  419. "exactly once.";""" % (i, i + 1) for i in OneTo(n)])
  420. tests += """
  421. // Verifies that the control flow in the test function is expected.
  422. if (expected_to_finish_ && !finished_) {
  423. FAIL() << "The predicate assertion unexpactedly aborted the test.";
  424. } else if (!expected_to_finish_ && finished_) {
  425. FAIL() << "The failed predicate assertion didn't abort the test "
  426. "as expected.";
  427. }
  428. }
  429. // true if and only if the test function is expected to run to finish.
  430. static bool expected_to_finish_;
  431. // true if and only if the test function did run to finish.
  432. static bool finished_;
  433. """ % DEFS
  434. tests += Iter(n, """
  435. static int n%s_;""")
  436. tests += """
  437. };
  438. bool Predicate%(n)sTest::expected_to_finish_;
  439. bool Predicate%(n)sTest::finished_;
  440. """ % DEFS
  441. tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
  442. """) % DEFS
  443. tests += """
  444. typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
  445. typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
  446. typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
  447. typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
  448. """ % DEFS
  449. def GenTest(use_format, use_assert, expect_failure,
  450. use_functor, use_user_type):
  451. """Returns the test for a predicate assertion macro.
  452. Args:
  453. use_format: true if and only if the assertion is a *_PRED_FORMAT*.
  454. use_assert: true if and only if the assertion is a ASSERT_*.
  455. expect_failure: true if and only if the assertion is expected to fail.
  456. use_functor: true if and only if the first argument of the assertion is
  457. a functor (as opposed to a function)
  458. use_user_type: true if and only if the predicate functor/function takes
  459. argument(s) of a user-defined type.
  460. Example:
  461. GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
  462. of a successful EXPECT_PRED_FORMATn() that takes a functor
  463. whose arguments have built-in types."""
  464. if use_assert:
  465. assrt = 'ASSERT' # 'assert' is reserved, so we cannot use
  466. # that identifier here.
  467. else:
  468. assrt = 'EXPECT'
  469. assertion = assrt + '_PRED'
  470. if use_format:
  471. pred_format = 'PredFormat'
  472. assertion += '_FORMAT'
  473. else:
  474. pred_format = 'Pred'
  475. assertion += '%(n)s' % DEFS
  476. if use_functor:
  477. pred_format_type = 'functor'
  478. pred_format += 'Functor%(n)s()'
  479. else:
  480. pred_format_type = 'function'
  481. pred_format += 'Function%(n)s'
  482. if not use_format:
  483. if use_user_type:
  484. pred_format += 'Bool'
  485. else:
  486. pred_format += 'Int'
  487. test_name = pred_format_type.title()
  488. if use_user_type:
  489. arg_type = 'user-defined type (Bool)'
  490. test_name += 'OnUserType'
  491. if expect_failure:
  492. arg = 'Bool(n%s_++)'
  493. else:
  494. arg = 'Bool(++n%s_)'
  495. else:
  496. arg_type = 'built-in type (int)'
  497. test_name += 'OnBuiltInType'
  498. if expect_failure:
  499. arg = 'n%s_++'
  500. else:
  501. arg = '++n%s_'
  502. if expect_failure:
  503. successful_or_failed = 'failed'
  504. expected_or_not = 'expected.'
  505. test_name += 'Failure'
  506. else:
  507. successful_or_failed = 'successful'
  508. expected_or_not = 'UNEXPECTED!'
  509. test_name += 'Success'
  510. # A map that defines the values used in the test template.
  511. defs = DEFS.copy()
  512. defs.update({
  513. 'assert' : assrt,
  514. 'assertion' : assertion,
  515. 'test_name' : test_name,
  516. 'pf_type' : pred_format_type,
  517. 'pf' : pred_format,
  518. 'arg_type' : arg_type,
  519. 'arg' : arg,
  520. 'successful' : successful_or_failed,
  521. 'expected' : expected_or_not,
  522. })
  523. test = """
  524. // Tests a %(successful)s %(assertion)s where the
  525. // predicate-formatter is a %(pf_type)s on a %(arg_type)s.
  526. TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
  527. indent = (len(assertion) + 3)*' '
  528. extra_indent = ''
  529. if expect_failure:
  530. extra_indent = ' '
  531. if use_assert:
  532. test += """
  533. expected_to_finish_ = false;
  534. EXPECT_FATAL_FAILURE({ // NOLINT"""
  535. else:
  536. test += """
  537. EXPECT_NONFATAL_FAILURE({ // NOLINT"""
  538. test += '\n' + extra_indent + """ %(assertion)s(%(pf)s""" % defs
  539. test = test % defs
  540. test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
  541. test += ');\n' + extra_indent + ' finished_ = true;\n'
  542. if expect_failure:
  543. test += ' }, "");\n'
  544. test += '}\n'
  545. return test
  546. # Generates tests for all 2**6 = 64 combinations.
  547. tests += ''.join([GenTest(use_format, use_assert, expect_failure,
  548. use_functor, use_user_type)
  549. for use_format in [0, 1]
  550. for use_assert in [0, 1]
  551. for expect_failure in [0, 1]
  552. for use_functor in [0, 1]
  553. for use_user_type in [0, 1]
  554. ])
  555. return tests
  556. def UnitTestPostamble():
  557. """Returns the postamble for the tests."""
  558. return ''
  559. def GenerateUnitTest(n):
  560. """Returns the tests for up-to n-ary predicate assertions."""
  561. GenerateFile(UNIT_TEST,
  562. UnitTestPreamble()
  563. + ''.join([TestsForArity(i) for i in OneTo(n)])
  564. + UnitTestPostamble())
  565. def _Main():
  566. """The entry point of the script. Generates the header file and its
  567. unit test."""
  568. if len(sys.argv) != 2:
  569. print __doc__
  570. print 'Author: ' + __author__
  571. sys.exit(1)
  572. n = int(sys.argv[1])
  573. GenerateHeader(n)
  574. GenerateUnitTest(n)
  575. if __name__ == '__main__':
  576. _Main()