reformatter_pep8_test.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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. """PEP8 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 TestsForPEP8Style(yapf_test_helper.YAPFTest):
  21. @classmethod
  22. def setUpClass(cls): # pylint: disable=g-missing-super-call
  23. style.SetGlobalStyle(style.CreatePEP8Style())
  24. def testIndent4(self):
  25. unformatted_code = textwrap.dedent("""\
  26. if a+b:
  27. pass
  28. """)
  29. expected_formatted_code = textwrap.dedent("""\
  30. if a + b:
  31. pass
  32. """)
  33. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  34. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  35. def testSingleLineIfStatements(self):
  36. code = textwrap.dedent("""\
  37. if True: a = 42
  38. elif False: b = 42
  39. else: c = 42
  40. """)
  41. llines = yapf_test_helper.ParseAndUnwrap(code)
  42. self.assertCodeEqual(code, reformatter.Reformat(llines))
  43. def testBlankBetweenClassAndDef(self):
  44. unformatted_code = textwrap.dedent("""\
  45. class Foo:
  46. def joe():
  47. pass
  48. """)
  49. expected_formatted_code = textwrap.dedent("""\
  50. class Foo:
  51. def joe():
  52. pass
  53. """)
  54. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  55. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  56. def testBlankBetweenDefsInClass(self):
  57. unformatted_code = textwrap.dedent('''\
  58. class TestClass:
  59. def __init__(self):
  60. self.running = False
  61. def run(self):
  62. """Override in subclass"""
  63. def is_running(self):
  64. return self.running
  65. ''')
  66. expected_formatted_code = textwrap.dedent('''\
  67. class TestClass:
  68. def __init__(self):
  69. self.running = False
  70. def run(self):
  71. """Override in subclass"""
  72. def is_running(self):
  73. return self.running
  74. ''')
  75. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  76. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  77. def testSingleWhiteBeforeTrailingComment(self):
  78. unformatted_code = textwrap.dedent("""\
  79. if a+b: # comment
  80. pass
  81. """)
  82. expected_formatted_code = textwrap.dedent("""\
  83. if a + b: # comment
  84. pass
  85. """)
  86. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  87. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  88. def testSpaceBetweenEndingCommandAndClosingBracket(self):
  89. unformatted_code = textwrap.dedent("""\
  90. a = (
  91. 1,
  92. )
  93. """)
  94. expected_formatted_code = textwrap.dedent("""\
  95. a = (1, )
  96. """)
  97. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  98. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  99. def testContinuedNonOutdentedLine(self):
  100. code = textwrap.dedent("""\
  101. class eld(d):
  102. if str(geom.geom_type).upper(
  103. ) != self.geom_type and not self.geom_type == 'GEOMETRY':
  104. ror(code='om_type')
  105. """)
  106. llines = yapf_test_helper.ParseAndUnwrap(code)
  107. self.assertCodeEqual(code, reformatter.Reformat(llines))
  108. def testWrappingPercentExpressions(self):
  109. unformatted_code = textwrap.dedent("""\
  110. def f():
  111. if True:
  112. zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxx.yyy + 1)
  113. zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxx.yyy + 1)
  114. zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxxxxxx + 1)
  115. zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxxxxxx + 1)
  116. """) # noqa
  117. expected_formatted_code = textwrap.dedent("""\
  118. def f():
  119. if True:
  120. zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxxxxx + 1,
  121. xxxxxxxxxxxxxxxxx.yyy + 1)
  122. zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxxxxx + 1,
  123. xxxxxxxxxxxxxxxxx.yyy + 1)
  124. zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxx + 1,
  125. xxxxxxxxxxxxxxxxxxxxx + 1)
  126. zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxx + 1,
  127. xxxxxxxxxxxxxxxxxxxxx + 1)
  128. """)
  129. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  130. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  131. def testAlignClosingBracketWithVisualIndentation(self):
  132. unformatted_code = textwrap.dedent("""\
  133. TEST_LIST = ('foo', 'bar', # first comment
  134. 'baz' # second comment
  135. )
  136. """)
  137. expected_formatted_code = textwrap.dedent("""\
  138. TEST_LIST = (
  139. 'foo',
  140. 'bar', # first comment
  141. 'baz' # second comment
  142. )
  143. """)
  144. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  145. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  146. unformatted_code = textwrap.dedent("""\
  147. def f():
  148. def g():
  149. while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa' and
  150. xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'
  151. ):
  152. pass
  153. """) # noqa
  154. expected_formatted_code = textwrap.dedent("""\
  155. def f():
  156. def g():
  157. while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa'
  158. and xxxxxxxxxxxxxxxxxxxx(
  159. yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'):
  160. pass
  161. """) # noqa
  162. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  163. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  164. def testIndentSizeChanging(self):
  165. unformatted_code = textwrap.dedent("""\
  166. if True:
  167. runtime_mins = (program_end_time - program_start_time).total_seconds() / 60.0
  168. """) # noqa
  169. expected_formatted_code = textwrap.dedent("""\
  170. if True:
  171. runtime_mins = (program_end_time -
  172. program_start_time).total_seconds() / 60.0
  173. """)
  174. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  175. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  176. def testHangingIndentCollision(self):
  177. unformatted_code = textwrap.dedent("""\
  178. if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx or yyyyyyyyyyyyyyyyy):
  179. pass
  180. elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa, bbbbbbbbbbbbbb, cccccccccccc, dddddddddd=None)):
  181. pass
  182. def h():
  183. if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
  184. pass
  185. for connection in itertools.chain(branch.contact, branch.address, morestuff.andmore.andmore.andmore.andmore.andmore.andmore.andmore):
  186. dosomething(connection)
  187. """) # noqa
  188. expected_formatted_code = textwrap.dedent("""\
  189. if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx
  190. or yyyyyyyyyyyyyyyyy):
  191. pass
  192. elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa,
  193. bbbbbbbbbbbbbb,
  194. cccccccccccc,
  195. dddddddddd=None)):
  196. pass
  197. def h():
  198. if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
  199. xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
  200. pass
  201. for connection in itertools.chain(
  202. branch.contact, branch.address,
  203. morestuff.andmore.andmore.andmore.andmore.andmore.andmore.andmore):
  204. dosomething(connection)
  205. """) # noqa
  206. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  207. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  208. def testSplittingBeforeLogicalOperator(self):
  209. try:
  210. style.SetGlobalStyle(
  211. style.CreateStyleFromConfig(
  212. '{based_on_style: pep8, split_before_logical_operator: True}'))
  213. unformatted_code = textwrap.dedent("""\
  214. def foo():
  215. return bool(update.message.new_chat_member or update.message.left_chat_member or
  216. update.message.new_chat_title or update.message.new_chat_photo or
  217. update.message.delete_chat_photo or update.message.group_chat_created or
  218. update.message.supergroup_chat_created or update.message.channel_chat_created
  219. or update.message.migrate_to_chat_id or update.message.migrate_from_chat_id or
  220. update.message.pinned_message)
  221. """) # noqa
  222. expected_formatted_code = textwrap.dedent("""\
  223. def foo():
  224. return bool(
  225. update.message.new_chat_member or update.message.left_chat_member
  226. or update.message.new_chat_title or update.message.new_chat_photo
  227. or update.message.delete_chat_photo
  228. or update.message.group_chat_created
  229. or update.message.supergroup_chat_created
  230. or update.message.channel_chat_created
  231. or update.message.migrate_to_chat_id
  232. or update.message.migrate_from_chat_id
  233. or update.message.pinned_message)
  234. """) # noqa
  235. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  236. self.assertCodeEqual(expected_formatted_code,
  237. reformatter.Reformat(llines))
  238. finally:
  239. style.SetGlobalStyle(style.CreatePEP8Style())
  240. def testContiguousListEndingWithComment(self):
  241. unformatted_code = textwrap.dedent("""\
  242. if True:
  243. if True:
  244. keys.append(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) # may be unassigned.
  245. """) # noqa
  246. expected_formatted_code = textwrap.dedent("""\
  247. if True:
  248. if True:
  249. keys.append(
  250. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) # may be unassigned.
  251. """) # noqa
  252. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  253. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  254. def testSplittingBeforeFirstArgument(self):
  255. try:
  256. style.SetGlobalStyle(
  257. style.CreateStyleFromConfig(
  258. '{based_on_style: pep8, split_before_first_argument: True}'))
  259. unformatted_code = textwrap.dedent("""\
  260. a_very_long_function_name(long_argument_name_1=1, long_argument_name_2=2,
  261. long_argument_name_3=3, long_argument_name_4=4)
  262. """) # noqa
  263. expected_formatted_code = textwrap.dedent("""\
  264. a_very_long_function_name(
  265. long_argument_name_1=1,
  266. long_argument_name_2=2,
  267. long_argument_name_3=3,
  268. long_argument_name_4=4)
  269. """)
  270. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  271. self.assertCodeEqual(expected_formatted_code,
  272. reformatter.Reformat(llines))
  273. finally:
  274. style.SetGlobalStyle(style.CreatePEP8Style())
  275. def testSplittingExpressionsInsideSubscripts(self):
  276. unformatted_code = textwrap.dedent("""\
  277. def foo():
  278. df = df[(df['campaign_status'] == 'LIVE') & (df['action_status'] == 'LIVE')]
  279. """) # noqa
  280. expected_formatted_code = textwrap.dedent("""\
  281. def foo():
  282. df = df[(df['campaign_status'] == 'LIVE')
  283. & (df['action_status'] == 'LIVE')]
  284. """)
  285. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  286. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  287. def testSplitListsAndDictSetMakersIfCommaTerminated(self):
  288. unformatted_code = textwrap.dedent("""\
  289. DJANGO_TEMPLATES_OPTIONS = {"context_processors": []}
  290. DJANGO_TEMPLATES_OPTIONS = {"context_processors": [],}
  291. x = ["context_processors"]
  292. x = ["context_processors",]
  293. """)
  294. expected_formatted_code = textwrap.dedent("""\
  295. DJANGO_TEMPLATES_OPTIONS = {"context_processors": []}
  296. DJANGO_TEMPLATES_OPTIONS = {
  297. "context_processors": [],
  298. }
  299. x = ["context_processors"]
  300. x = [
  301. "context_processors",
  302. ]
  303. """)
  304. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  305. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  306. def testSplitAroundNamedAssigns(self):
  307. unformatted_code = textwrap.dedent("""\
  308. class a():
  309. def a(): return a(
  310. aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)
  311. """)
  312. expected_formatted_code = textwrap.dedent("""\
  313. class a():
  314. def a():
  315. return a(
  316. aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  317. )
  318. """)
  319. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  320. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  321. def testUnaryOperator(self):
  322. unformatted_code = textwrap.dedent("""\
  323. if not -3 < x < 3:
  324. pass
  325. if -3 < x < 3:
  326. pass
  327. """)
  328. expected_formatted_code = textwrap.dedent("""\
  329. if not -3 < x < 3:
  330. pass
  331. if -3 < x < 3:
  332. pass
  333. """)
  334. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  335. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  336. def testNoSplitBeforeDictValue(self):
  337. try:
  338. style.SetGlobalStyle(
  339. style.CreateStyleFromConfig('{based_on_style: pep8, '
  340. 'allow_split_before_dict_value: false, '
  341. 'coalesce_brackets: true, '
  342. 'dedent_closing_brackets: true, '
  343. 'each_dict_entry_on_separate_line: true, '
  344. 'split_before_logical_operator: true}'))
  345. unformatted_code = textwrap.dedent("""\
  346. some_dict = {
  347. 'title': _("I am example data"),
  348. 'description': _("Lorem ipsum dolor met sit amet elit, si vis pacem para bellum "
  349. "elites nihi very long string."),
  350. }
  351. """) # noqa
  352. expected_formatted_code = textwrap.dedent("""\
  353. some_dict = {
  354. 'title': _("I am example data"),
  355. 'description': _(
  356. "Lorem ipsum dolor met sit amet elit, si vis pacem para bellum "
  357. "elites nihi very long string."
  358. ),
  359. }
  360. """) # noqa
  361. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  362. self.assertCodeEqual(expected_formatted_code,
  363. reformatter.Reformat(llines))
  364. unformatted_code = textwrap.dedent("""\
  365. X = {'a': 1, 'b': 2, 'key': this_is_a_function_call_that_goes_over_the_column_limit_im_pretty_sure()}
  366. """) # noqa
  367. expected_formatted_code = textwrap.dedent("""\
  368. X = {
  369. 'a': 1,
  370. 'b': 2,
  371. 'key': this_is_a_function_call_that_goes_over_the_column_limit_im_pretty_sure()
  372. }
  373. """) # noqa
  374. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  375. self.assertCodeEqual(expected_formatted_code,
  376. reformatter.Reformat(llines))
  377. unformatted_code = textwrap.dedent("""\
  378. attrs = {
  379. 'category': category,
  380. 'role': forms.ModelChoiceField(label=_("Role"), required=False, queryset=category_roles, initial=selected_role, empty_label=_("No access"),),
  381. }
  382. """) # noqa
  383. expected_formatted_code = textwrap.dedent("""\
  384. attrs = {
  385. 'category': category,
  386. 'role': forms.ModelChoiceField(
  387. label=_("Role"),
  388. required=False,
  389. queryset=category_roles,
  390. initial=selected_role,
  391. empty_label=_("No access"),
  392. ),
  393. }
  394. """)
  395. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  396. self.assertCodeEqual(expected_formatted_code,
  397. reformatter.Reformat(llines))
  398. unformatted_code = textwrap.dedent("""\
  399. css_class = forms.CharField(
  400. label=_("CSS class"),
  401. required=False,
  402. help_text=_("Optional CSS class used to customize this category appearance from templates."),
  403. )
  404. """) # noqa
  405. expected_formatted_code = textwrap.dedent("""\
  406. css_class = forms.CharField(
  407. label=_("CSS class"),
  408. required=False,
  409. help_text=_(
  410. "Optional CSS class used to customize this category appearance from templates."
  411. ),
  412. )
  413. """) # noqa
  414. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  415. self.assertCodeEqual(expected_formatted_code,
  416. reformatter.Reformat(llines))
  417. finally:
  418. style.SetGlobalStyle(style.CreatePEP8Style())
  419. def testBitwiseOperandSplitting(self):
  420. unformatted_code = """\
  421. def _():
  422. include_values = np.where(
  423. (cdffile['Quality_Flag'][:] >= 5) & (
  424. cdffile['Day_Night_Flag'][:] == 1) & (
  425. cdffile['Longitude'][:] >= select_lon - radius) & (
  426. cdffile['Longitude'][:] <= select_lon + radius) & (
  427. cdffile['Latitude'][:] >= select_lat - radius) & (
  428. cdffile['Latitude'][:] <= select_lat + radius))
  429. """
  430. expected_code = """\
  431. def _():
  432. include_values = np.where(
  433. (cdffile['Quality_Flag'][:] >= 5) & (cdffile['Day_Night_Flag'][:] == 1)
  434. & (cdffile['Longitude'][:] >= select_lon - radius)
  435. & (cdffile['Longitude'][:] <= select_lon + radius)
  436. & (cdffile['Latitude'][:] >= select_lat - radius)
  437. & (cdffile['Latitude'][:] <= select_lat + radius))
  438. """
  439. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  440. self.assertEqual(expected_code, reformatter.Reformat(llines))
  441. def testNoBlankLinesOnlyForFirstNestedObject(self):
  442. unformatted_code = '''\
  443. class Demo:
  444. """
  445. Demo docs
  446. """
  447. def foo(self):
  448. """
  449. foo docs
  450. """
  451. def bar(self):
  452. """
  453. bar docs
  454. """
  455. '''
  456. expected_code = '''\
  457. class Demo:
  458. """
  459. Demo docs
  460. """
  461. def foo(self):
  462. """
  463. foo docs
  464. """
  465. def bar(self):
  466. """
  467. bar docs
  468. """
  469. '''
  470. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  471. self.assertEqual(expected_code, reformatter.Reformat(llines))
  472. def testSplitBeforeArithmeticOperators(self):
  473. try:
  474. style.SetGlobalStyle(
  475. style.CreateStyleFromConfig(
  476. '{based_on_style: pep8, split_before_arithmetic_operator: true}'))
  477. unformatted_code = """\
  478. def _():
  479. raise ValueError('This is a long message that ends with an argument: ' + str(42))
  480. """ # noqa
  481. expected_formatted_code = """\
  482. def _():
  483. raise ValueError('This is a long message that ends with an argument: '
  484. + str(42))
  485. """
  486. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  487. self.assertCodeEqual(expected_formatted_code,
  488. reformatter.Reformat(llines))
  489. finally:
  490. style.SetGlobalStyle(style.CreatePEP8Style())
  491. def testListSplitting(self):
  492. unformatted_code = """\
  493. foo([(1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
  494. (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
  495. (1,10), (1,11), (1, 10), (1,11), (10,11)])
  496. """
  497. expected_code = """\
  498. foo([(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1),
  499. (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 10), (1, 11), (1, 10),
  500. (1, 11), (10, 11)])
  501. """
  502. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  503. self.assertCodeEqual(expected_code, reformatter.Reformat(llines))
  504. def testNoBlankLineBeforeNestedFuncOrClass(self):
  505. try:
  506. style.SetGlobalStyle(
  507. style.CreateStyleFromConfig(
  508. '{based_on_style: pep8, '
  509. 'blank_line_before_nested_class_or_def: false}'))
  510. unformatted_code = '''\
  511. def normal_function():
  512. """Return the nested function."""
  513. def nested_function():
  514. """Do nothing just nest within."""
  515. @nested(klass)
  516. class nested_class():
  517. pass
  518. pass
  519. return nested_function
  520. '''
  521. expected_formatted_code = '''\
  522. def normal_function():
  523. """Return the nested function."""
  524. def nested_function():
  525. """Do nothing just nest within."""
  526. @nested(klass)
  527. class nested_class():
  528. pass
  529. pass
  530. return nested_function
  531. '''
  532. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  533. self.assertCodeEqual(expected_formatted_code,
  534. reformatter.Reformat(llines))
  535. finally:
  536. style.SetGlobalStyle(style.CreatePEP8Style())
  537. def testParamListIndentationCollision1(self):
  538. unformatted_code = textwrap.dedent("""\
  539. class _():
  540. def __init__(self, title: Optional[str], diffs: Collection[BinaryDiff] = (), charset: Union[Type[AsciiCharset], Type[LineCharset]] = AsciiCharset, preprocess: Callable[[str], str] = identity,
  541. # TODO(somebody): Make this a Literal type.
  542. justify: str = 'rjust'):
  543. self._cs = charset
  544. self._preprocess = preprocess
  545. """) # noqa
  546. expected_formatted_code = textwrap.dedent("""\
  547. class _():
  548. def __init__(
  549. self,
  550. title: Optional[str],
  551. diffs: Collection[BinaryDiff] = (),
  552. charset: Union[Type[AsciiCharset],
  553. Type[LineCharset]] = AsciiCharset,
  554. preprocess: Callable[[str], str] = identity,
  555. # TODO(somebody): Make this a Literal type.
  556. justify: str = 'rjust'):
  557. self._cs = charset
  558. self._preprocess = preprocess
  559. """)
  560. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  561. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  562. def testParamListIndentationCollision2(self):
  563. code = textwrap.dedent("""\
  564. def simple_pass_function_with_an_extremely_long_name_and_some_arguments(
  565. argument0, argument1):
  566. pass
  567. """)
  568. llines = yapf_test_helper.ParseAndUnwrap(code)
  569. self.assertCodeEqual(code, reformatter.Reformat(llines))
  570. def testParamListIndentationCollision3(self):
  571. code = textwrap.dedent("""\
  572. def func1(
  573. arg1,
  574. arg2,
  575. ) -> None:
  576. pass
  577. def func2(
  578. arg1,
  579. arg2,
  580. ):
  581. pass
  582. """)
  583. llines = yapf_test_helper.ParseAndUnwrap(code)
  584. self.assertCodeEqual(code, reformatter.Reformat(llines))
  585. def testTwoWordComparisonOperators(self):
  586. unformatted_code = textwrap.dedent("""\
  587. _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
  588. _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
  589. """) # noqa
  590. expected_formatted_code = textwrap.dedent("""\
  591. _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
  592. is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
  593. _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
  594. not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
  595. """)
  596. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  597. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  598. def testStableInlinedDictionaryFormatting(self):
  599. unformatted_code = textwrap.dedent("""\
  600. def _():
  601. url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
  602. value, urllib.urlencode({'action': 'update', 'parameter': value}))
  603. """) # noqa
  604. expected_formatted_code = textwrap.dedent("""\
  605. def _():
  606. url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
  607. value, urllib.urlencode({
  608. 'action': 'update',
  609. 'parameter': value
  610. }))
  611. """)
  612. llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
  613. reformatted_code = reformatter.Reformat(llines)
  614. self.assertCodeEqual(expected_formatted_code, reformatted_code)
  615. llines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
  616. reformatted_code = reformatter.Reformat(llines)
  617. self.assertCodeEqual(expected_formatted_code, reformatted_code)
  618. class TestsForSpacesInsideBrackets(yapf_test_helper.YAPFTest):
  619. """Test the SPACE_INSIDE_BRACKETS style option."""
  620. unformatted_code = textwrap.dedent("""\
  621. foo()
  622. foo(1)
  623. foo(1,2)
  624. foo((1,))
  625. foo((1, 2))
  626. foo((1, 2,))
  627. foo(bar['baz'][0])
  628. set1 = {1, 2, 3}
  629. dict1 = {1: 1, foo: 2, 3: bar}
  630. dict2 = {
  631. 1: 1,
  632. foo: 2,
  633. 3: bar,
  634. }
  635. dict3[3][1][get_index(*args,**kwargs)]
  636. dict4[3][1][get_index(**kwargs)]
  637. x = dict5[4](foo(*args))
  638. a = list1[:]
  639. b = list2[slice_start:]
  640. c = list3[slice_start:slice_end]
  641. d = list4[slice_start:slice_end:]
  642. e = list5[slice_start:slice_end:slice_step]
  643. # Print gets special handling
  644. print(set2)
  645. compound = ((10+3)/(5-2**(6+x)))
  646. string_idx = "mystring"[3]
  647. """)
  648. def testEnabled(self):
  649. style.SetGlobalStyle(
  650. style.CreateStyleFromConfig('{space_inside_brackets: True}'))
  651. expected_formatted_code = textwrap.dedent("""\
  652. foo()
  653. foo( 1 )
  654. foo( 1, 2 )
  655. foo( ( 1, ) )
  656. foo( ( 1, 2 ) )
  657. foo( (
  658. 1,
  659. 2,
  660. ) )
  661. foo( bar[ 'baz' ][ 0 ] )
  662. set1 = { 1, 2, 3 }
  663. dict1 = { 1: 1, foo: 2, 3: bar }
  664. dict2 = {
  665. 1: 1,
  666. foo: 2,
  667. 3: bar,
  668. }
  669. dict3[ 3 ][ 1 ][ get_index( *args, **kwargs ) ]
  670. dict4[ 3 ][ 1 ][ get_index( **kwargs ) ]
  671. x = dict5[ 4 ]( foo( *args ) )
  672. a = list1[ : ]
  673. b = list2[ slice_start: ]
  674. c = list3[ slice_start:slice_end ]
  675. d = list4[ slice_start:slice_end: ]
  676. e = list5[ slice_start:slice_end:slice_step ]
  677. # Print gets special handling
  678. print( set2 )
  679. compound = ( ( 10 + 3 ) / ( 5 - 2**( 6 + x ) ) )
  680. string_idx = "mystring"[ 3 ]
  681. """)
  682. llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
  683. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  684. def testDefault(self):
  685. style.SetGlobalStyle(style.CreatePEP8Style())
  686. expected_formatted_code = textwrap.dedent("""\
  687. foo()
  688. foo(1)
  689. foo(1, 2)
  690. foo((1, ))
  691. foo((1, 2))
  692. foo((
  693. 1,
  694. 2,
  695. ))
  696. foo(bar['baz'][0])
  697. set1 = {1, 2, 3}
  698. dict1 = {1: 1, foo: 2, 3: bar}
  699. dict2 = {
  700. 1: 1,
  701. foo: 2,
  702. 3: bar,
  703. }
  704. dict3[3][1][get_index(*args, **kwargs)]
  705. dict4[3][1][get_index(**kwargs)]
  706. x = dict5[4](foo(*args))
  707. a = list1[:]
  708. b = list2[slice_start:]
  709. c = list3[slice_start:slice_end]
  710. d = list4[slice_start:slice_end:]
  711. e = list5[slice_start:slice_end:slice_step]
  712. # Print gets special handling
  713. print(set2)
  714. compound = ((10 + 3) / (5 - 2**(6 + x)))
  715. string_idx = "mystring"[3]
  716. """)
  717. llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
  718. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  719. class TestsForSpacesAroundSubscriptColon(yapf_test_helper.YAPFTest):
  720. """Test the SPACES_AROUND_SUBSCRIPT_COLON style option."""
  721. unformatted_code = textwrap.dedent("""\
  722. a = list1[ : ]
  723. b = list2[ slice_start: ]
  724. c = list3[ slice_start:slice_end ]
  725. d = list4[ slice_start:slice_end: ]
  726. e = list5[ slice_start:slice_end:slice_step ]
  727. a1 = list1[ : ]
  728. b1 = list2[ 1: ]
  729. c1 = list3[ 1:20 ]
  730. d1 = list4[ 1:20: ]
  731. e1 = list5[ 1:20:3 ]
  732. """)
  733. def testEnabled(self):
  734. style.SetGlobalStyle(
  735. style.CreateStyleFromConfig('{spaces_around_subscript_colon: True}'))
  736. expected_formatted_code = textwrap.dedent("""\
  737. a = list1[:]
  738. b = list2[slice_start :]
  739. c = list3[slice_start : slice_end]
  740. d = list4[slice_start : slice_end :]
  741. e = list5[slice_start : slice_end : slice_step]
  742. a1 = list1[:]
  743. b1 = list2[1 :]
  744. c1 = list3[1 : 20]
  745. d1 = list4[1 : 20 :]
  746. e1 = list5[1 : 20 : 3]
  747. """)
  748. llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
  749. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  750. def testWithSpaceInsideBrackets(self):
  751. style.SetGlobalStyle(
  752. style.CreateStyleFromConfig('{'
  753. 'spaces_around_subscript_colon: true, '
  754. 'space_inside_brackets: true,'
  755. '}'))
  756. expected_formatted_code = textwrap.dedent("""\
  757. a = list1[ : ]
  758. b = list2[ slice_start : ]
  759. c = list3[ slice_start : slice_end ]
  760. d = list4[ slice_start : slice_end : ]
  761. e = list5[ slice_start : slice_end : slice_step ]
  762. a1 = list1[ : ]
  763. b1 = list2[ 1 : ]
  764. c1 = list3[ 1 : 20 ]
  765. d1 = list4[ 1 : 20 : ]
  766. e1 = list5[ 1 : 20 : 3 ]
  767. """)
  768. llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
  769. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  770. def testDefault(self):
  771. style.SetGlobalStyle(style.CreatePEP8Style())
  772. expected_formatted_code = textwrap.dedent("""\
  773. a = list1[:]
  774. b = list2[slice_start:]
  775. c = list3[slice_start:slice_end]
  776. d = list4[slice_start:slice_end:]
  777. e = list5[slice_start:slice_end:slice_step]
  778. a1 = list1[:]
  779. b1 = list2[1:]
  780. c1 = list3[1:20]
  781. d1 = list4[1:20:]
  782. e1 = list5[1:20:3]
  783. """)
  784. llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
  785. self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
  786. if __name__ == '__main__':
  787. unittest.main()