reformatter_facebook_test.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # Copyright 2016 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Facebook tests for yapf.reformatter."""
  15. import textwrap
  16. import unittest
  17. from yapf.yapflib import reformatter
  18. from yapf.yapflib import style
  19. from yapftests import yapf_test_helper
  20. class TestsForFacebookStyle(yapf_test_helper.YAPFTest):
  21. @classmethod
  22. def setUpClass(cls):
  23. style.SetGlobalStyle(style.CreateFacebookStyle())
  24. def testNoNeedForLineBreaks(self):
  25. unformatted_code = textwrap.dedent("""\
  26. def overly_long_function_name(
  27. just_one_arg, **kwargs):
  28. pass
  29. """)
  30. expected_formatted_code = textwrap.dedent("""\
  31. def overly_long_function_name(just_one_arg, **kwargs):
  32. pass
  33. """)
  34. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  35. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  36. def testDedentClosingBracket(self):
  37. unformatted_code = textwrap.dedent("""\
  38. def overly_long_function_name(
  39. first_argument_on_the_same_line,
  40. second_argument_makes_the_line_too_long):
  41. pass
  42. """)
  43. expected_formatted_code = textwrap.dedent("""\
  44. def overly_long_function_name(
  45. first_argument_on_the_same_line, second_argument_makes_the_line_too_long
  46. ):
  47. pass
  48. """) # noqa
  49. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  50. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  51. def testBreakAfterOpeningBracketIfContentsTooBig(self):
  52. unformatted_code = textwrap.dedent("""\
  53. def overly_long_function_name(a, b, c, d, e, f, g, h, i, j, k, l, m,
  54. n, o, p, q, r, s, t, u, v, w, x, y, z):
  55. pass
  56. """)
  57. expected_formatted_code = textwrap.dedent("""\
  58. def overly_long_function_name(
  59. a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, \
  60. v, w, x, y, z
  61. ):
  62. pass
  63. """)
  64. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  65. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  66. def testDedentClosingBracketWithComments(self):
  67. unformatted_code = textwrap.dedent("""\
  68. def overly_long_function_name(
  69. # comment about the first argument
  70. first_argument_with_a_very_long_name_or_so,
  71. # comment about the second argument
  72. second_argument_makes_the_line_too_long):
  73. pass
  74. """)
  75. expected_formatted_code = textwrap.dedent("""\
  76. def overly_long_function_name(
  77. # comment about the first argument
  78. first_argument_with_a_very_long_name_or_so,
  79. # comment about the second argument
  80. second_argument_makes_the_line_too_long
  81. ):
  82. pass
  83. """)
  84. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  85. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  86. def testDedentImportAsNames(self):
  87. code = textwrap.dedent("""\
  88. from module import (
  89. internal_function as function,
  90. SOME_CONSTANT_NUMBER1,
  91. SOME_CONSTANT_NUMBER2,
  92. SOME_CONSTANT_NUMBER3,
  93. )
  94. """)
  95. llines = yapf_test_helper.ParseAndUnwrap(code)
  96. self.assertCodeEqual(code, reformatter.Reformat(llines))
  97. def testDedentTestListGexp(self):
  98. unformatted_code = textwrap.dedent("""\
  99. try:
  100. pass
  101. except (
  102. IOError, OSError, LookupError, RuntimeError, OverflowError
  103. ) as exception:
  104. pass
  105. try:
  106. pass
  107. except (
  108. IOError, OSError, LookupError, RuntimeError, OverflowError,
  109. ) as exception:
  110. pass
  111. """)
  112. expected_formatted_code = textwrap.dedent("""\
  113. try:
  114. pass
  115. except (
  116. IOError, OSError, LookupError, RuntimeError, OverflowError
  117. ) as exception:
  118. pass
  119. try:
  120. pass
  121. except (
  122. IOError,
  123. OSError,
  124. LookupError,
  125. RuntimeError,
  126. OverflowError,
  127. ) as exception:
  128. pass
  129. """)
  130. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  131. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  132. def testBrokenIdempotency(self):
  133. # TODO(ambv): The following behaviour should be fixed.
  134. pass0_code = textwrap.dedent("""\
  135. try:
  136. pass
  137. except (IOError, OSError, LookupError, RuntimeError, OverflowError) as exception:
  138. pass
  139. """) # noqa
  140. pass1_code = textwrap.dedent("""\
  141. try:
  142. pass
  143. except (
  144. IOError, OSError, LookupError, RuntimeError, OverflowError
  145. ) as exception:
  146. pass
  147. """)
  148. llines = yapf_test_helper.ParseAndUnwrap(pass0_code)
  149. self.assertCodeEqual(pass1_code, reformatter.Reformat(llines))
  150. pass2_code = textwrap.dedent("""\
  151. try:
  152. pass
  153. except (
  154. IOError, OSError, LookupError, RuntimeError, OverflowError
  155. ) as exception:
  156. pass
  157. """)
  158. llines = yapf_test_helper.ParseAndUnwrap(pass1_code)
  159. self.assertCodeEqual(pass2_code, reformatter.Reformat(llines))
  160. def testIfExprHangingIndent(self):
  161. unformatted_code = textwrap.dedent("""\
  162. if True:
  163. if True:
  164. if True:
  165. if not self.frobbies and (
  166. self.foobars.counters['db.cheeses'] != 1 or
  167. self.foobars.counters['db.marshmellow_skins'] != 1):
  168. pass
  169. """)
  170. expected_formatted_code = textwrap.dedent("""\
  171. if True:
  172. if True:
  173. if True:
  174. if not self.frobbies and (
  175. self.foobars.counters['db.cheeses'] != 1 or
  176. self.foobars.counters['db.marshmellow_skins'] != 1
  177. ):
  178. pass
  179. """)
  180. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  181. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  182. def testSimpleDedenting(self):
  183. unformatted_code = textwrap.dedent("""\
  184. if True:
  185. self.assertEqual(result.reason_not_added, "current preflight is still running")
  186. """) # noqa
  187. expected_formatted_code = textwrap.dedent("""\
  188. if True:
  189. self.assertEqual(
  190. result.reason_not_added, "current preflight is still running"
  191. )
  192. """)
  193. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  194. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  195. def testDedentingWithSubscripts(self):
  196. unformatted_code = textwrap.dedent("""\
  197. class Foo:
  198. class Bar:
  199. @classmethod
  200. def baz(cls, clues_list, effect, constraints, constraint_manager):
  201. if clues_lists:
  202. return cls.single_constraint_not(clues_lists, effect, constraints[0], constraint_manager)
  203. """) # noqa
  204. expected_formatted_code = textwrap.dedent("""\
  205. class Foo:
  206. class Bar:
  207. @classmethod
  208. def baz(cls, clues_list, effect, constraints, constraint_manager):
  209. if clues_lists:
  210. return cls.single_constraint_not(
  211. clues_lists, effect, constraints[0], constraint_manager
  212. )
  213. """) # noqa
  214. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  215. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  216. def testDedentingCallsWithInnerLists(self):
  217. code = textwrap.dedent("""\
  218. class _():
  219. def _():
  220. cls.effect_clues = {
  221. 'effect': Clue((cls.effect_time, 'apache_host'), effect_line, 40)
  222. }
  223. """) # noqa
  224. llines = yapf_test_helper.ParseAndUnwrap(code)
  225. self.assertCodeEqual(code, reformatter.Reformat(llines))
  226. def testDedentingListComprehension(self):
  227. unformatted_code = textwrap.dedent("""\
  228. class Foo():
  229. def _pack_results_for_constraint_or():
  230. self.param_groups = dict(
  231. (
  232. key + 1, ParamGroup(groups[key], default_converter)
  233. ) for key in six.moves.range(len(groups))
  234. )
  235. for combination in cls._clues_combinations(clues_lists):
  236. if all(
  237. cls._verify_constraint(combination, effect, constraint)
  238. for constraint in constraints
  239. ):
  240. pass
  241. guessed_dict = dict(
  242. (
  243. key, guessed_pattern_matches[key]
  244. ) for key in six.moves.range(len(guessed_pattern_matches))
  245. )
  246. content = "".join(
  247. itertools.chain(
  248. (first_line_fragment, ), lines_between, (last_line_fragment, )
  249. )
  250. )
  251. rule = Rule(
  252. [self.cause1, self.cause2, self.cause1, self.cause2], self.effect, constraints1,
  253. Rule.LINKAGE_AND
  254. )
  255. assert sorted(log_type.files_to_parse) == [
  256. ('localhost', os.path.join(path, 'node_1.log'), super_parser),
  257. ('localhost', os.path.join(path, 'node_2.log'), super_parser)
  258. ]
  259. """) # noqa
  260. expected_formatted_code = textwrap.dedent("""\
  261. class Foo():
  262. def _pack_results_for_constraint_or():
  263. self.param_groups = dict(
  264. (key + 1, ParamGroup(groups[key], default_converter))
  265. for key in six.moves.range(len(groups))
  266. )
  267. for combination in cls._clues_combinations(clues_lists):
  268. if all(
  269. cls._verify_constraint(combination, effect, constraint)
  270. for constraint in constraints
  271. ):
  272. pass
  273. guessed_dict = dict(
  274. (key, guessed_pattern_matches[key])
  275. for key in six.moves.range(len(guessed_pattern_matches))
  276. )
  277. content = "".join(
  278. itertools.chain(
  279. (first_line_fragment, ), lines_between, (last_line_fragment, )
  280. )
  281. )
  282. rule = Rule(
  283. [self.cause1, self.cause2, self.cause1, self.cause2], self.effect,
  284. constraints1, Rule.LINKAGE_AND
  285. )
  286. assert sorted(log_type.files_to_parse) == [
  287. ('localhost', os.path.join(path, 'node_1.log'), super_parser),
  288. ('localhost', os.path.join(path, 'node_2.log'), super_parser)
  289. ]
  290. """) # noqa
  291. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  292. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  293. def testMustSplitDedenting(self):
  294. code = textwrap.dedent("""\
  295. class _():
  296. def _():
  297. effect_line = FrontInput(
  298. effect_line_offset, line_content,
  299. LineSource('localhost', xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)
  300. )
  301. """) # noqa
  302. llines = yapf_test_helper.ParseAndUnwrap(code)
  303. self.assertCodeEqual(code, reformatter.Reformat(llines))
  304. def testDedentIfConditional(self):
  305. code = textwrap.dedent("""\
  306. class _():
  307. def _():
  308. if True:
  309. if not self.frobbies and (
  310. self.foobars.counters['db.cheeses'] != 1 or
  311. self.foobars.counters['db.marshmellow_skins'] != 1
  312. ):
  313. pass
  314. """)
  315. llines = yapf_test_helper.ParseAndUnwrap(code)
  316. self.assertCodeEqual(code, reformatter.Reformat(llines))
  317. def testDedentSet(self):
  318. code = textwrap.dedent("""\
  319. class _():
  320. def _():
  321. assert set(self.constraint_links.get_links()) == set(
  322. [
  323. (2, 10, 100),
  324. (2, 10, 200),
  325. (2, 20, 100),
  326. (2, 20, 200),
  327. ]
  328. )
  329. """)
  330. llines = yapf_test_helper.ParseAndUnwrap(code)
  331. self.assertCodeEqual(code, reformatter.Reformat(llines))
  332. def testDedentingInnerScope(self):
  333. code = textwrap.dedent("""\
  334. class Foo():
  335. @classmethod
  336. def _pack_results_for_constraint_or(cls, combination, constraints):
  337. return cls._create_investigation_result(
  338. (clue for clue in combination if not clue == Verifier.UNMATCHED),
  339. constraints, InvestigationResult.OR
  340. )
  341. """) # noqa
  342. llines = yapf_test_helper.ParseAndUnwrap(code)
  343. reformatted_code = reformatter.Reformat(llines)
  344. self.assertCodeEqual(code, reformatted_code)
  345. llines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
  346. reformatted_code = reformatter.Reformat(llines)
  347. self.assertCodeEqual(code, reformatted_code)
  348. def testCommentWithNewlinesInPrefix(self):
  349. unformatted_code = textwrap.dedent("""\
  350. def foo():
  351. if 0:
  352. return False
  353. #a deadly comment
  354. elif 1:
  355. return True
  356. print(foo())
  357. """)
  358. expected_formatted_code = textwrap.dedent("""\
  359. def foo():
  360. if 0:
  361. return False
  362. #a deadly comment
  363. elif 1:
  364. return True
  365. print(foo())
  366. """)
  367. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  368. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  369. def testIfStmtClosingBracket(self):
  370. unformatted_code = """\
  371. if (isinstance(value , (StopIteration , StopAsyncIteration )) and exc.__cause__ is value_asdfasdfasdfasdfsafsafsafdasfasdfs):
  372. return False
  373. """ # noqa
  374. expected_formatted_code = """\
  375. if (
  376. isinstance(value, (StopIteration, StopAsyncIteration)) and
  377. exc.__cause__ is value_asdfasdfasdfasdfsafsafsafdasfasdfs
  378. ):
  379. return False
  380. """
  381. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  382. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  383. if __name__ == '__main__':
  384. unittest.main()