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