gen_gtest_pred_impl.py 21 KB

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