/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/scripts/gen_gtest_pred_impl.py

http://github.com/tomahawk-player/tomahawk · Python · 733 lines · 483 code · 106 blank · 144 comment · 37 complexity · d33fdf6ceda834ba9af9223d3fa95768 MD5 · raw file

  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. Message msg;
  194. """ % DEFS
  195. impl += ' msg << pred_text << "("'
  196. impl += Iter(n, """
  197. << e%s""", sep=' << ", "')
  198. impl += ' << ") evaluates to false, where"'
  199. impl += Iter(n, """
  200. << "\\n" << e%s << " evaluates to " << v%s""")
  201. impl += """;
  202. return AssertionFailure(msg);
  203. }
  204. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
  205. // Don't use this in your code.
  206. #define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
  207. GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s),\\
  208. on_failure)
  209. // Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use
  210. // this in your code.
  211. #define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
  212. GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
  213. impl += Iter(n, """, \\
  214. #v%s""")
  215. impl += """, \\
  216. pred"""
  217. impl += Iter(n, """, \\
  218. v%s""")
  219. impl += """), on_failure)
  220. // %(Arity)s predicate assertion macros.
  221. #define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
  222. GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
  223. #define EXPECT_PRED%(n)s(pred, %(vs)s) \\
  224. GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
  225. #define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
  226. GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
  227. #define ASSERT_PRED%(n)s(pred, %(vs)s) \\
  228. GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
  229. """ % DEFS
  230. return impl
  231. def HeaderPostamble():
  232. """Returns the postamble for the header file."""
  233. return """
  234. #endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  235. """
  236. def GenerateFile(path, content):
  237. """Given a file path and a content string, overwrites it with the
  238. given content."""
  239. print 'Updating file %s . . .' % path
  240. f = file(path, 'w+')
  241. print >>f, content,
  242. f.close()
  243. print 'File %s has been updated.' % path
  244. def GenerateHeader(n):
  245. """Given the maximum arity n, updates the header file that implements
  246. the predicate assertions."""
  247. GenerateFile(HEADER,
  248. HeaderPreamble(n)
  249. + ''.join([ImplementationForArity(i) for i in OneTo(n)])
  250. + HeaderPostamble())
  251. def UnitTestPreamble():
  252. """Returns the preamble for the unit test file."""
  253. # A map that defines the values used in the preamble template.
  254. DEFS = {
  255. 'today' : time.strftime('%m/%d/%Y'),
  256. 'year' : time.strftime('%Y'),
  257. 'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
  258. }
  259. return (
  260. """// Copyright 2006, Google Inc.
  261. // All rights reserved.
  262. //
  263. // Redistribution and use in source and binary forms, with or without
  264. // modification, are permitted provided that the following conditions are
  265. // met:
  266. //
  267. // * Redistributions of source code must retain the above copyright
  268. // notice, this list of conditions and the following disclaimer.
  269. // * Redistributions in binary form must reproduce the above
  270. // copyright notice, this list of conditions and the following disclaimer
  271. // in the documentation and/or other materials provided with the
  272. // distribution.
  273. // * Neither the name of Google Inc. nor the names of its
  274. // contributors may be used to endorse or promote products derived from
  275. // this software without specific prior written permission.
  276. //
  277. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  278. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  279. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  280. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  281. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  282. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  283. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  284. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  285. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  286. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  287. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  288. // This file is AUTOMATICALLY GENERATED on %(today)s by command
  289. // '%(command)s'. DO NOT EDIT BY HAND!
  290. // Regression test for gtest_pred_impl.h
  291. //
  292. // This file is generated by a script and quite long. If you intend to
  293. // learn how Google Test works by reading its unit tests, read
  294. // gtest_unittest.cc instead.
  295. //
  296. // This is intended as a regression test for the Google Test predicate
  297. // assertions. We compile it as part of the gtest_unittest target
  298. // only to keep the implementation tidy and compact, as it is quite
  299. // involved to set up the stage for testing Google Test using Google
  300. // Test itself.
  301. //
  302. // Currently, gtest_unittest takes ~11 seconds to run in the testing
  303. // daemon. In the future, if it grows too large and needs much more
  304. // time to finish, we should consider separating this file into a
  305. // stand-alone regression test.
  306. #include <iostream>
  307. #include <gtest/gtest.h>
  308. #include <gtest/gtest-spi.h>
  309. // A user-defined data type.
  310. struct Bool {
  311. explicit Bool(int val) : value(val != 0) {}
  312. bool operator>(int n) const { return value > Bool(n).value; }
  313. Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
  314. bool operator==(const Bool& rhs) const { return value == rhs.value; }
  315. bool value;
  316. };
  317. // Enables Bool to be used in assertions.
  318. std::ostream& operator<<(std::ostream& os, const Bool& x) {
  319. return os << (x.value ? "true" : "false");
  320. }
  321. """ % DEFS)
  322. def TestsForArity(n):
  323. """Returns the tests for n-ary predicate assertions."""
  324. # A map that defines the values used in the template for the tests.
  325. DEFS = {
  326. 'n' : n,
  327. 'es' : Iter(n, 'e%s', sep=', '),
  328. 'vs' : Iter(n, 'v%s', sep=', '),
  329. 'vts' : Iter(n, '#v%s', sep=', '),
  330. 'tvs' : Iter(n, 'T%s v%s', sep=', '),
  331. 'int_vs' : Iter(n, 'int v%s', sep=', '),
  332. 'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
  333. 'types' : Iter(n, 'typename T%s', sep=', '),
  334. 'v_sum' : Iter(n, 'v%s', sep=' + '),
  335. 'arity' : Arity(n),
  336. 'Arity' : Title(Arity(n)),
  337. }
  338. tests = (
  339. """// Sample functions/functors for testing %(arity)s predicate assertions.
  340. // A %(arity)s predicate function.
  341. template <%(types)s>
  342. bool PredFunction%(n)s(%(tvs)s) {
  343. return %(v_sum)s > 0;
  344. }
  345. // The following two functions are needed to circumvent a bug in
  346. // gcc 2.95.3, which sometimes has problem with the above template
  347. // function.
  348. bool PredFunction%(n)sInt(%(int_vs)s) {
  349. return %(v_sum)s > 0;
  350. }
  351. bool PredFunction%(n)sBool(%(Bool_vs)s) {
  352. return %(v_sum)s > 0;
  353. }
  354. """ % DEFS)
  355. tests += """
  356. // A %(arity)s predicate functor.
  357. struct PredFunctor%(n)s {
  358. template <%(types)s>
  359. bool operator()(""" % DEFS
  360. tests += Iter(n, 'const T%s& v%s', sep=""",
  361. """)
  362. tests += """) {
  363. return %(v_sum)s > 0;
  364. }
  365. };
  366. """ % DEFS
  367. tests += """
  368. // A %(arity)s predicate-formatter function.
  369. template <%(types)s>
  370. testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
  371. tests += Iter(n, 'const char* e%s', sep=""",
  372. """)
  373. tests += Iter(n, """,
  374. const T%s& v%s""")
  375. tests += """) {
  376. if (PredFunction%(n)s(%(vs)s))
  377. return testing::AssertionSuccess();
  378. testing::Message msg;
  379. msg << """ % DEFS
  380. tests += Iter(n, 'e%s', sep=' << " + " << ')
  381. tests += """
  382. << " is expected to be positive, but evaluates to "
  383. << %(v_sum)s << ".";
  384. return testing::AssertionFailure(msg);
  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. virtual void SetUp() {
  406. expected_to_finish_ = true;
  407. finished_ = false;""" % DEFS
  408. tests += """
  409. """ + Iter(n, 'n%s_ = ') + """0;
  410. }
  411. """
  412. tests += """
  413. virtual void TearDown() {
  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 iff the test function is expected to run to finish.
  430. static bool expected_to_finish_;
  431. // true iff 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 iff the assertion is a *_PRED_FORMAT*.
  454. use_assert: true iff the assertion is a ASSERT_*.
  455. expect_failure: true iff the assertion is expected to fail.
  456. use_functor: true iff the first argument of the assertion is
  457. a functor (as opposed to a function)
  458. use_user_type: true iff 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()