• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"""Buganizer tests for yapf.reformatter."""
15
16import textwrap
17import unittest
18
19from yapf.yapflib import reformatter
20from yapf.yapflib import style
21
22from yapftests import yapf_test_helper
23
24
25class BuganizerFixes(yapf_test_helper.YAPFTest):
26
27  @classmethod
28  def setUpClass(cls):
29    style.SetGlobalStyle(style.CreateChromiumStyle())
30
31  def testB77923341(self):
32    code = """\
33def f():
34  if (aaaaaaaaaaaaaa.bbbbbbbbbbbb.ccccc <= 0 and  # pytype: disable=attribute-error
35      ddddddddddd.eeeeeeeee == constants.FFFFFFFFFFFFFF):
36    raise "yo"
37"""
38    uwlines = yapf_test_helper.ParseAndUnwrap(code)
39    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
40
41  def testB77329955(self):
42    code = """\
43class _():
44
45  @parameterized.named_parameters(
46      ('ReadyExpiredSuccess', True, True, True, None, None),
47      ('SpannerUpdateFails', True, False, True, None, None),
48      ('ReadyNotExpired', False, True, True, True, None),
49      # ('ReadyNotExpiredNotHealthy', False, True, True, False, True),
50      # ('ReadyNotExpiredNotHealthyErrorFails', False, True, True, False, False
51      # ('ReadyNotExpiredNotHealthyUpdateFails', False, False, True, False, True
52  )
53  def _():
54    pass
55"""
56    uwlines = yapf_test_helper.ParseAndUnwrap(code)
57    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
58
59  def testB65197969(self):
60    unformatted_code = """\
61class _():
62
63  def _():
64    return timedelta(seconds=max(float(time_scale), small_interval) *
65                   1.41 ** min(num_attempts, 9))
66"""
67    expected_formatted_code = """\
68class _():
69
70  def _():
71    return timedelta(
72        seconds=max(float(time_scale), small_interval) *
73        1.41**min(num_attempts, 9))
74"""
75    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
76    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
77
78  def testB65546221(self):
79    unformatted_code = """\
80SUPPORTED_PLATFORMS = (
81    "centos-6",
82    "centos-7",
83    "ubuntu-1204-precise",
84    "ubuntu-1404-trusty",
85    "ubuntu-1604-xenial",
86    "debian-7-wheezy",
87    "debian-8-jessie",
88    "debian-9-stretch",)
89"""
90    expected_formatted_code = """\
91SUPPORTED_PLATFORMS = (
92    "centos-6",
93    "centos-7",
94    "ubuntu-1204-precise",
95    "ubuntu-1404-trusty",
96    "ubuntu-1604-xenial",
97    "debian-7-wheezy",
98    "debian-8-jessie",
99    "debian-9-stretch",
100)
101"""
102    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
103    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
104
105  def testB30500455(self):
106    unformatted_code = """\
107INITIAL_SYMTAB = dict([(name, 'exception#' + name) for name in INITIAL_EXCEPTIONS
108] * [(name, 'type#' + name) for name in INITIAL_TYPES] + [
109    (name, 'function#' + name) for name in INITIAL_FUNCTIONS
110] + [(name, 'const#' + name) for name in INITIAL_CONSTS])
111"""
112    expected_formatted_code = """\
113INITIAL_SYMTAB = dict(
114    [(name, 'exception#' + name) for name in INITIAL_EXCEPTIONS] *
115    [(name, 'type#' + name) for name in INITIAL_TYPES] +
116    [(name, 'function#' + name) for name in INITIAL_FUNCTIONS] +
117    [(name, 'const#' + name) for name in INITIAL_CONSTS])
118"""
119    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
120    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
121
122  def testB38343525(self):
123    code = """\
124# This does foo.
125@arg.String('some_path_to_a_file', required=True)
126# This does bar.
127@arg.String('some_path_to_a_file', required=True)
128def f():
129  print 1
130"""
131    uwlines = yapf_test_helper.ParseAndUnwrap(code)
132    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
133
134  def testB37099651(self):
135    unformatted_code = """\
136_MEMCACHE = lazy.MakeLazy(
137    # pylint: disable=g-long-lambda
138    lambda: function.call.mem.clients(FLAGS.some_flag_thingy, default_namespace=_LAZY_MEM_NAMESPACE, allow_pickle=True)
139    # pylint: enable=g-long-lambda
140)
141"""
142    expected_formatted_code = """\
143_MEMCACHE = lazy.MakeLazy(
144    # pylint: disable=g-long-lambda
145    lambda: function.call.mem.clients(
146        FLAGS.some_flag_thingy,
147        default_namespace=_LAZY_MEM_NAMESPACE,
148        allow_pickle=True)
149    # pylint: enable=g-long-lambda
150)
151"""
152    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
153    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
154
155  def testB33228502(self):
156    unformatted_code = """\
157def _():
158  success_rate_stream_table = module.Precompute(
159      query_function=module.DefineQueryFunction(
160          name='Response error ratio',
161          expression=((m.Fetch(
162                  m.Raw('monarch.BorgTask',
163                        '/corp/travel/trips2/dispatcher/email/response'),
164                  {'borg_job': module_config.job, 'metric:response_type': 'SUCCESS'}),
165               m.Fetch(m.Raw('monarch.BorgTask', '/corp/travel/trips2/dispatcher/email/response'), {'borg_job': module_config.job}))
166              | m.Window(m.Delta('1h'))
167              | m.Join('successes', 'total')
168              | m.Point(m.VAL['successes'] / m.VAL['total']))))
169"""
170    expected_formatted_code = """\
171def _():
172  success_rate_stream_table = module.Precompute(
173      query_function=module.DefineQueryFunction(
174          name='Response error ratio',
175          expression=(
176              (m.Fetch(
177                  m.Raw('monarch.BorgTask',
178                        '/corp/travel/trips2/dispatcher/email/response'), {
179                            'borg_job': module_config.job,
180                            'metric:response_type': 'SUCCESS'
181                        }),
182               m.Fetch(
183                   m.Raw('monarch.BorgTask',
184                         '/corp/travel/trips2/dispatcher/email/response'),
185                   {'borg_job': module_config.job}))
186              | m.Window(m.Delta('1h'))
187              | m.Join('successes', 'total')
188              | m.Point(m.VAL['successes'] / m.VAL['total']))))
189"""
190    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
191    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
192
193  def testB30394228(self):
194    code = """\
195class _():
196
197  def _(self):
198    return some.randome.function.calling(
199        wf, None, alert.Format(alert.subject, alert=alert, threshold=threshold),
200        alert.Format(alert.body, alert=alert, threshold=threshold),
201        alert.html_formatting)
202"""
203    uwlines = yapf_test_helper.ParseAndUnwrap(code)
204    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
205
206  def testB65246454(self):
207    unformatted_code = """\
208class _():
209
210  def _(self):
211    self.assertEqual({i.id
212                      for i in successful_instances},
213                     {i.id
214                      for i in self._statuses.successful_instances})
215"""
216    expected_formatted_code = """\
217class _():
218
219  def _(self):
220    self.assertEqual({i.id for i in successful_instances},
221                     {i.id for i in self._statuses.successful_instances})
222"""
223    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
224    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
225
226  def testB67935450(self):
227    unformatted_code = """\
228def _():
229  return (
230      (Gauge(
231          metric='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
232          group_by=group_by + ['metric:process_name'],
233          metric_filter={'metric:process_name': process_name_re}),
234       Gauge(
235           metric='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
236           group_by=group_by + ['metric:process_name'],
237           metric_filter={'metric:process_name': process_name_re}))
238      | expr.Join(
239          left_name='start', left_default=0, right_name='end', right_default=0)
240      | m.Point(
241          m.Cond(m.VAL['end'] != 0, m.VAL['end'], k.TimestampMicros() /
242                 1000000L) - m.Cond(m.VAL['start'] != 0, m.VAL['start'],
243                                    m.TimestampMicros() / 1000000L)))
244"""
245    expected_formatted_code = """\
246def _():
247  return (
248      (Gauge(
249          metric='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
250          group_by=group_by + ['metric:process_name'],
251          metric_filter={'metric:process_name': process_name_re}),
252       Gauge(
253           metric='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
254           group_by=group_by + ['metric:process_name'],
255           metric_filter={'metric:process_name': process_name_re}))
256      | expr.Join(
257          left_name='start', left_default=0, right_name='end', right_default=0)
258      | m.Point(
259          m.Cond(m.VAL['end'] != 0, m.VAL['end'],
260                 k.TimestampMicros() / 1000000L) -
261          m.Cond(m.VAL['start'] != 0, m.VAL['start'],
262                 m.TimestampMicros() / 1000000L)))
263"""
264    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
265    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
266
267  def testB66011084(self):
268    unformatted_code = """\
269X = {
270"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":  # Comment 1.
271([] if True else [ # Comment 2.
272    "bbbbbbbbbbbbbbbbbbb",  # Comment 3.
273    "cccccccccccccccccccccccc", # Comment 4.
274    "ddddddddddddddddddddddddd", # Comment 5.
275    "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", # Comment 6.
276    "fffffffffffffffffffffffffffffff", # Comment 7.
277    "ggggggggggggggggggggggggggg", # Comment 8.
278    "hhhhhhhhhhhhhhhhhh",  # Comment 9.
279]),
280}
281"""
282    expected_formatted_code = """\
283X = {
284    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":  # Comment 1.
285        ([] if True else [  # Comment 2.
286            "bbbbbbbbbbbbbbbbbbb",  # Comment 3.
287            "cccccccccccccccccccccccc",  # Comment 4.
288            "ddddddddddddddddddddddddd",  # Comment 5.
289            "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",  # Comment 6.
290            "fffffffffffffffffffffffffffffff",  # Comment 7.
291            "ggggggggggggggggggggggggggg",  # Comment 8.
292            "hhhhhhhhhhhhhhhhhh",  # Comment 9.
293        ]),
294}
295"""
296    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
297    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
298
299  def testB67455376(self):
300    unformatted_code = """\
301sponge_ids.extend(invocation.id() for invocation in self._client.GetInvocationsByLabels(labels))
302"""
303    expected_formatted_code = """\
304sponge_ids.extend(invocation.id()
305                  for invocation in self._client.GetInvocationsByLabels(labels))
306"""
307    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
308    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
309
310  def testB35210351(self):
311    unformatted_code = """\
312def _():
313  config.AnotherRuleThing(
314      'the_title_to_the_thing_here',
315      {'monitorname': 'firefly',
316       'service': ACCOUNTING_THING,
317       'severity': 'the_bug',
318       'monarch_module_name': alerts.TheLabel(qa_module_regexp, invert=True)},
319      fanout,
320      alerts.AlertUsToSomething(
321          GetTheAlertToIt('the_title_to_the_thing_here'),
322          GetNotificationTemplate('your_email_here')))
323"""
324    expected_formatted_code = """\
325def _():
326  config.AnotherRuleThing(
327      'the_title_to_the_thing_here', {
328          'monitorname': 'firefly',
329          'service': ACCOUNTING_THING,
330          'severity': 'the_bug',
331          'monarch_module_name': alerts.TheLabel(qa_module_regexp, invert=True)
332      }, fanout,
333      alerts.AlertUsToSomething(
334          GetTheAlertToIt('the_title_to_the_thing_here'),
335          GetNotificationTemplate('your_email_here')))
336"""
337    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
338    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
339
340  def testB34774905(self):
341    unformatted_code = """\
342x=[VarExprType(ir_name=IrName( value='x',
343expr_type=UnresolvedAttrExprType( atom=UnknownExprType(), attr_name=IrName(
344    value='x', expr_type=UnknownExprType(), usage='UNKNOWN', fqn=None,
345    astn=None), usage='REF'), usage='ATTR', fqn='<attr>.x', astn=None))]
346"""
347    expected_formatted_code = """\
348x = [
349    VarExprType(
350        ir_name=IrName(
351            value='x',
352            expr_type=UnresolvedAttrExprType(
353                atom=UnknownExprType(),
354                attr_name=IrName(
355                    value='x',
356                    expr_type=UnknownExprType(),
357                    usage='UNKNOWN',
358                    fqn=None,
359                    astn=None),
360                usage='REF'),
361            usage='ATTR',
362            fqn='<attr>.x',
363            astn=None))
364]
365"""
366    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
367    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
368
369  def testB65176185(self):
370    code = """\
371xx = zip(*[(a, b) for (a, b, c) in yy])
372"""
373    uwlines = yapf_test_helper.ParseAndUnwrap(code)
374    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
375
376  def testB35210166(self):
377    unformatted_code = """\
378def _():
379  query = (
380      m.Fetch(n.Raw('monarch.BorgTask', '/proc/container/memory/usage'), { 'borg_user': borguser, 'borg_job': jobname })
381      | o.Window(m.Align('5m')) | p.GroupBy(['borg_user', 'borg_job', 'borg_cell'], q.Mean()))
382"""
383    expected_formatted_code = """\
384def _():
385  query = (
386      m.Fetch(
387          n.Raw('monarch.BorgTask', '/proc/container/memory/usage'), {
388              'borg_user': borguser,
389              'borg_job': jobname
390          })
391      | o.Window(m.Align('5m'))
392      | p.GroupBy(['borg_user', 'borg_job', 'borg_cell'], q.Mean()))
393"""
394    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
395    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
396
397  def testB32167774(self):
398    unformatted_code = """\
399X = (
400    'is_official',
401    'is_cover',
402    'is_remix',
403    'is_instrumental',
404    'is_live',
405    'has_lyrics',
406    'is_album',
407    'is_compilation',)
408"""
409    expected_formatted_code = """\
410X = (
411    'is_official',
412    'is_cover',
413    'is_remix',
414    'is_instrumental',
415    'is_live',
416    'has_lyrics',
417    'is_album',
418    'is_compilation',
419)
420"""
421    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
422    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
423
424  def testB66912275(self):
425    unformatted_code = """\
426def _():
427  with self.assertRaisesRegexp(errors.HttpError, 'Invalid'):
428    patch_op = api_client.forwardingRules().patch(
429        project=project_id,
430        region=region,
431        forwardingRule=rule_name,
432        body={'fingerprint': base64.urlsafe_b64encode('invalid_fingerprint')}).execute()
433"""
434    expected_formatted_code = """\
435def _():
436  with self.assertRaisesRegexp(errors.HttpError, 'Invalid'):
437    patch_op = api_client.forwardingRules().patch(
438        project=project_id,
439        region=region,
440        forwardingRule=rule_name,
441        body={
442            'fingerprint': base64.urlsafe_b64encode('invalid_fingerprint')
443        }).execute()
444"""
445    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
446    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
447
448  def testB67312284(self):
449    code = """\
450def _():
451  self.assertEqual(
452      [u'to be published 2', u'to be published 1', u'to be published 0'],
453      [el.text for el in page.first_column_tds])
454"""
455    uwlines = yapf_test_helper.ParseAndUnwrap(code)
456    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
457
458  def testB65241516(self):
459    unformatted_code = """\
460checkpoint_files = gfile.Glob(os.path.join(TrainTraceDir(unit_key, "*", "*"), embedding_model.CHECKPOINT_FILENAME + "-*"))
461"""
462    expected_formatted_code = """\
463checkpoint_files = gfile.Glob(
464    os.path.join(
465        TrainTraceDir(unit_key, "*", "*"),
466        embedding_model.CHECKPOINT_FILENAME + "-*"))
467"""
468    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
469    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
470
471  def testB37460004(self):
472    code = textwrap.dedent("""\
473        assert all(s not in (_SENTINEL, None) for s in nested_schemas
474                  ), 'Nested schemas should never contain None/_SENTINEL'
475        """)
476    uwlines = yapf_test_helper.ParseAndUnwrap(code)
477    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
478
479  def testB36806207(self):
480    code = """\
481def _():
482  linearity_data = [[row] for row in [
483      "%.1f mm" % (np.mean(linearity_values["pos_error"]) * 1000.0),
484      "%.1f mm" % (np.max(linearity_values["pos_error"]) * 1000.0),
485      "%.1f mm" % (np.mean(linearity_values["pos_error_chunk_mean"]) * 1000.0),
486      "%.1f mm" % (np.max(linearity_values["pos_error_chunk_max"]) * 1000.0),
487      "%.1f deg" % math.degrees(np.mean(linearity_values["rot_noise"])),
488      "%.1f deg" % math.degrees(np.max(linearity_values["rot_noise"])),
489      "%.1f deg" % math.degrees(np.mean(linearity_values["rot_drift"])),
490      "%.1f deg" % math.degrees(np.max(linearity_values["rot_drift"])),
491      "%.1f%%" % (np.max(linearity_values["pos_discontinuity"]) * 100.0),
492      "%.1f%%" % (np.max(linearity_values["rot_discontinuity"]) * 100.0)
493  ]]
494"""
495    uwlines = yapf_test_helper.ParseAndUnwrap(code)
496    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
497
498  def testB36215507(self):
499    code = textwrap.dedent("""\
500        class X():
501
502          def _():
503            aaaaaaaaaaaaa._bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(
504                mmmmmmmmmmmmm, nnnnn, ooooooooo,
505                _(ppppppppppppppppppppppppppppppppppppp),
506                *(qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq),
507                **(qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq))
508        """)
509    uwlines = yapf_test_helper.ParseAndUnwrap(code)
510    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
511
512  def testB35212469(self):
513    unformatted_code = textwrap.dedent("""\
514        def _():
515          X = {
516            'retain': {
517                'loadtest':  # This is a comment in the middle of a dictionary entry
518                    ('/some/path/to/a/file/that/is/needed/by/this/process')
519              }
520          }
521        """)
522    expected_formatted_code = textwrap.dedent("""\
523        def _():
524          X = {
525              'retain': {
526                  'loadtest':  # This is a comment in the middle of a dictionary entry
527                      ('/some/path/to/a/file/that/is/needed/by/this/process')
528              }
529          }
530        """)
531    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
532    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
533
534  def testB31063453(self):
535    unformatted_code = textwrap.dedent("""\
536        def _():
537          while ((not mpede_proc) or ((time_time() - last_modified) < FLAGS_boot_idle_timeout)):
538            pass
539        """)
540    expected_formatted_code = textwrap.dedent("""\
541        def _():
542          while ((not mpede_proc) or
543                 ((time_time() - last_modified) < FLAGS_boot_idle_timeout)):
544            pass
545        """)
546    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
547    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
548
549  def testB35021894(self):
550    unformatted_code = textwrap.dedent("""\
551        def _():
552          labelacl = Env(qa={
553              'read': 'name/some-type-of-very-long-name-for-reading-perms',
554              'modify': 'name/some-other-type-of-very-long-name-for-modifying'
555          },
556                         prod={
557                            'read': 'name/some-type-of-very-long-name-for-reading-perms',
558                            'modify': 'name/some-other-type-of-very-long-name-for-modifying'
559                         })
560        """)
561    expected_formatted_code = textwrap.dedent("""\
562        def _():
563          labelacl = Env(
564              qa={
565                  'read': 'name/some-type-of-very-long-name-for-reading-perms',
566                  'modify': 'name/some-other-type-of-very-long-name-for-modifying'
567              },
568              prod={
569                  'read': 'name/some-type-of-very-long-name-for-reading-perms',
570                  'modify': 'name/some-other-type-of-very-long-name-for-modifying'
571              })
572        """)
573    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
574    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
575
576  def testB34682902(self):
577    unformatted_code = textwrap.dedent("""\
578        logging.info("Mean angular velocity norm: %.3f", np.linalg.norm(np.mean(ang_vel_arr, axis=0)))
579        """)
580    expected_formatted_code = textwrap.dedent("""\
581        logging.info("Mean angular velocity norm: %.3f",
582                     np.linalg.norm(np.mean(ang_vel_arr, axis=0)))
583        """)
584    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
585    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
586
587  def testB33842726(self):
588    unformatted_code = textwrap.dedent("""\
589        class _():
590          def _():
591            hints.append(('hg tag -f -l -r %s %s # %s' % (short(ctx.node(
592            )), candidatetag, firstline))[:78])
593        """)
594    expected_formatted_code = textwrap.dedent("""\
595        class _():
596          def _():
597            hints.append(('hg tag -f -l -r %s %s # %s' % (short(
598                ctx.node()), candidatetag, firstline))[:78])
599        """)
600    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
601    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
602
603  def testB32931780(self):
604    unformatted_code = textwrap.dedent("""\
605        environments = {
606            'prod': {
607                # this is a comment before the first entry.
608                'entry one':
609                    'an entry.',
610                # this is the comment before the second entry.
611                'entry number 2.':
612                    'something',
613                # this is the comment before the third entry and it's a doozy. So big!
614                'who':
615                    'allin',
616                # This is an entry that has a dictionary in it. It's ugly
617                'something': {
618                    'page': ['this-is-a-page@xxxxxxxx.com', 'something-for-eml@xxxxxx.com'],
619                    'bug': ['bugs-go-here5300@xxxxxx.com'],
620                    'email': ['sometypeof-email@xxxxxx.com'],
621                },
622                # a short comment
623                'yolo!!!!!':
624                    'another-email-address@xxxxxx.com',
625                # this entry has an implicit string concatenation
626                'implicit':
627                    'https://this-is-very-long.url-addr.com/'
628                    '?something=something%20some%20more%20stuff..',
629                # A more normal entry.
630                '.....':
631                    'this is an entry',
632            }
633        }
634        """)
635    expected_formatted_code = textwrap.dedent("""\
636        environments = {
637            'prod': {
638                # this is a comment before the first entry.
639                'entry one': 'an entry.',
640                # this is the comment before the second entry.
641                'entry number 2.': 'something',
642                # this is the comment before the third entry and it's a doozy. So big!
643                'who': 'allin',
644                # This is an entry that has a dictionary in it. It's ugly
645                'something': {
646                    'page': [
647                        'this-is-a-page@xxxxxxxx.com', 'something-for-eml@xxxxxx.com'
648                    ],
649                    'bug': ['bugs-go-here5300@xxxxxx.com'],
650                    'email': ['sometypeof-email@xxxxxx.com'],
651                },
652                # a short comment
653                'yolo!!!!!': 'another-email-address@xxxxxx.com',
654                # this entry has an implicit string concatenation
655                'implicit': 'https://this-is-very-long.url-addr.com/'
656                            '?something=something%20some%20more%20stuff..',
657                # A more normal entry.
658                '.....': 'this is an entry',
659            }
660        }
661        """)
662    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
663    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
664
665  def testB33047408(self):
666    code = textwrap.dedent("""\
667        def _():
668          for sort in (sorts or []):
669            request['sorts'].append({
670                'field': {
671                    'user_field': sort
672                },
673                'order': 'ASCENDING'
674            })
675        """)
676    uwlines = yapf_test_helper.ParseAndUnwrap(code)
677    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
678
679  def testB32714745(self):
680    code = textwrap.dedent("""\
681        class _():
682
683          def _BlankDefinition():
684            '''Return a generic blank dictionary for a new field.'''
685            return {
686                'type': '',
687                'validation': '',
688                'name': 'fieldname',
689                'label': 'Field Label',
690                'help': '',
691                'initial': '',
692                'required': False,
693                'required_msg': 'Required',
694                'invalid_msg': 'Please enter a valid value',
695                'options': {
696                    'regex': '',
697                    'widget_attr': '',
698                    'choices_checked': '',
699                    'choices_count': '',
700                    'choices': {}
701                },
702                'isnew': True,
703                'dirty': False,
704            }
705        """)
706    uwlines = yapf_test_helper.ParseAndUnwrap(code)
707    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
708
709  def testB32737279(self):
710    unformatted_code = textwrap.dedent("""\
711        here_is_a_dict = {
712            'key':
713            # Comment.
714            'value'
715        }
716        """)
717    expected_formatted_code = textwrap.dedent("""\
718        here_is_a_dict = {
719            'key':  # Comment.
720                'value'
721        }
722        """)
723    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
724    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
725
726  def testB32570937(self):
727    code = textwrap.dedent("""\
728      def _():
729        if (job_message.ball not in ('*', ball) or
730            job_message.call not in ('*', call) or
731            job_message.mall not in ('*', job_name)):
732          return False
733        """)
734    uwlines = yapf_test_helper.ParseAndUnwrap(code)
735    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
736
737  def testB31937033(self):
738    code = textwrap.dedent("""\
739        class _():
740
741          def __init__(self, metric, fields_cb=None):
742            self._fields_cb = fields_cb or (lambda *unused_args, **unused_kwargs: {})
743        """)
744    uwlines = yapf_test_helper.ParseAndUnwrap(code)
745    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
746
747  def testB31911533(self):
748    code = """\
749class _():
750
751  @parameterized.NamedParameters(
752      ('IncludingModInfoWithHeaderList', AAAA, aaaa),
753      ('IncludingModInfoWithoutHeaderList', BBBB, bbbbb),
754      ('ExcludingModInfoWithHeaderList', CCCCC, cccc),
755      ('ExcludingModInfoWithoutHeaderList', DDDDD, ddddd),
756  )
757  def _():
758    pass
759"""
760    uwlines = yapf_test_helper.ParseAndUnwrap(code)
761    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
762
763  def testB31847238(self):
764    unformatted_code = textwrap.dedent("""\
765        class _():
766
767          def aaaaa(self, bbbbb, cccccccccccccc=None):  # TODO(who): pylint: disable=unused-argument
768            return 1
769
770          def xxxxx(self, yyyyy, zzzzzzzzzzzzzz=None):  # A normal comment that runs over the column limit.
771            return 1
772        """)
773    expected_formatted_code = textwrap.dedent("""\
774        class _():
775
776          def aaaaa(self, bbbbb, cccccccccccccc=None):  # TODO(who): pylint: disable=unused-argument
777            return 1
778
779          def xxxxx(
780              self, yyyyy,
781              zzzzzzzzzzzzzz=None):  # A normal comment that runs over the column limit.
782            return 1
783        """)
784    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
785    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
786
787  def testB30760569(self):
788    unformatted_code = textwrap.dedent("""\
789        {'1234567890123456789012345678901234567890123456789012345678901234567890':
790             '1234567890123456789012345678901234567890'}
791        """)
792    expected_formatted_code = textwrap.dedent("""\
793        {
794            '1234567890123456789012345678901234567890123456789012345678901234567890':
795                '1234567890123456789012345678901234567890'
796        }
797        """)
798    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
799    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
800
801  def testB26034238(self):
802    unformatted_code = textwrap.dedent("""\
803        class Thing:
804
805          def Function(self):
806            thing.Scrape('/aaaaaaaaa/bbbbbbbbbb/ccccc/dddd/eeeeeeeeeeeeee/ffffffffffffff').AndReturn(42)
807        """)
808    expected_formatted_code = textwrap.dedent("""\
809        class Thing:
810
811          def Function(self):
812            thing.Scrape(
813                '/aaaaaaaaa/bbbbbbbbbb/ccccc/dddd/eeeeeeeeeeeeee/ffffffffffffff'
814            ).AndReturn(42)
815        """)
816    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
817    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
818
819  def testB30536435(self):
820    unformatted_code = textwrap.dedent("""\
821        def main(unused_argv):
822          if True:
823            if True:
824              aaaaaaaaaaa.comment('import-from[{}] {} {}'.format(
825                  bbbbbbbbb.usage,
826                  ccccccccc.within,
827                  imports.ddddddddddddddddddd(name_item.ffffffffffffffff)))
828        """)
829    expected_formatted_code = textwrap.dedent("""\
830        def main(unused_argv):
831          if True:
832            if True:
833              aaaaaaaaaaa.comment('import-from[{}] {} {}'.format(
834                  bbbbbbbbb.usage, ccccccccc.within,
835                  imports.ddddddddddddddddddd(name_item.ffffffffffffffff)))
836        """)
837    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
838    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
839
840  def testB30442148(self):
841    unformatted_code = textwrap.dedent("""\
842        def lulz():
843          return (some_long_module_name.SomeLongClassName.
844                  some_long_attribute_name.some_long_method_name())
845        """)
846    expected_formatted_code = textwrap.dedent("""\
847        def lulz():
848          return (some_long_module_name.SomeLongClassName.some_long_attribute_name.
849                  some_long_method_name())
850        """)
851    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
852    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
853
854  def testB26868213(self):
855    unformatted_code = textwrap.dedent("""\
856      def _():
857        xxxxxxxxxxxxxxxxxxx = {
858            'ssssss': {'ddddd': 'qqqqq',
859                       'p90': aaaaaaaaaaaaaaaaa,
860                       'p99': bbbbbbbbbbbbbbbbb,
861                       'lllllllllllll': yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy(),},
862            'bbbbbbbbbbbbbbbbbbbbbbbbbbbb': {
863                'ddddd': 'bork bork bork bo',
864                'p90': wwwwwwwwwwwwwwwww,
865                'p99': wwwwwwwwwwwwwwwww,
866                'lllllllllllll': None,  # use the default
867            }
868        }
869        """)
870    expected_formatted_code = textwrap.dedent("""\
871      def _():
872        xxxxxxxxxxxxxxxxxxx = {
873            'ssssss': {
874                'ddddd': 'qqqqq',
875                'p90': aaaaaaaaaaaaaaaaa,
876                'p99': bbbbbbbbbbbbbbbbb,
877                'lllllllllllll': yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy(),
878            },
879            'bbbbbbbbbbbbbbbbbbbbbbbbbbbb': {
880                'ddddd': 'bork bork bork bo',
881                'p90': wwwwwwwwwwwwwwwww,
882                'p99': wwwwwwwwwwwwwwwww,
883                'lllllllllllll': None,  # use the default
884            }
885        }
886        """)
887    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
888    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
889
890  def testB30173198(self):
891    code = textwrap.dedent("""\
892        class _():
893
894          def _():
895            self.assertFalse(
896                evaluation_runner.get_larps_in_eval_set('these_arent_the_larps'))
897        """)
898    uwlines = yapf_test_helper.ParseAndUnwrap(code)
899    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
900
901  def testB29908765(self):
902    code = textwrap.dedent("""\
903        class _():
904
905          def __repr__(self):
906            return '<session %s on %s>' % (self._id,
907                                           self._stub._stub.rpc_channel().target())  # pylint:disable=protected-access
908        """)
909    uwlines = yapf_test_helper.ParseAndUnwrap(code)
910    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
911
912  def testB30087362(self):
913    code = textwrap.dedent("""\
914        def _():
915          for s in sorted(env['foo']):
916            bar()
917            # This is a comment
918
919          # This is another comment
920          foo()
921        """)
922    uwlines = yapf_test_helper.ParseAndUnwrap(code)
923    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
924
925  def testB30087363(self):
926    code = textwrap.dedent("""\
927        if False:
928          bar()
929          # This is a comment
930        # This is another comment
931        elif True:
932          foo()
933        """)
934    uwlines = yapf_test_helper.ParseAndUnwrap(code)
935    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
936
937  def testB29093579(self):
938    unformatted_code = textwrap.dedent("""\
939        def _():
940          _xxxxxxxxxxxxxxx(aaaaaaaa, bbbbbbbbbbbbbb.cccccccccc[
941              dddddddddddddddddddddddddddd.eeeeeeeeeeeeeeeeeeeeee.fffffffffffffffffffff])
942        """)
943    expected_formatted_code = textwrap.dedent("""\
944        def _():
945          _xxxxxxxxxxxxxxx(
946              aaaaaaaa,
947              bbbbbbbbbbbbbb.cccccccccc[dddddddddddddddddddddddddddd.
948                                        eeeeeeeeeeeeeeeeeeeeee.fffffffffffffffffffff])
949        """)
950    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
951    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
952
953  def testB26382315(self):
954    code = textwrap.dedent("""\
955        @hello_world
956        # This is a first comment
957
958        # Comment
959        def foo():
960          pass
961        """)
962    uwlines = yapf_test_helper.ParseAndUnwrap(code)
963    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
964
965  def testB27616132(self):
966    unformatted_code = textwrap.dedent("""\
967        if True:
968          query.fetch_page.assert_has_calls([
969              mock.call(100,
970                        start_cursor=None),
971              mock.call(100,
972                        start_cursor=cursor_1),
973              mock.call(100,
974                        start_cursor=cursor_2),
975          ])
976        """)
977    expected_formatted_code = textwrap.dedent("""\
978        if True:
979          query.fetch_page.assert_has_calls([
980              mock.call(100, start_cursor=None),
981              mock.call(100, start_cursor=cursor_1),
982              mock.call(100, start_cursor=cursor_2),
983          ])
984        """)
985    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
986    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
987
988  def testB27590179(self):
989    unformatted_code = textwrap.dedent("""\
990        if True:
991          if True:
992            self.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (
993                { True:
994                     self.bbb.cccccccccc(ddddddddddddddddddddddd.eeeeeeeeeeeeeeeeeeeeee),
995                 False:
996                     self.bbb.cccccccccc(ddddddddddddddddddddddd.eeeeeeeeeeeeeeeeeeeeee)
997                })
998        """)
999    expected_formatted_code = textwrap.dedent("""\
1000        if True:
1001          if True:
1002            self.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = ({
1003                True:
1004                    self.bbb.cccccccccc(ddddddddddddddddddddddd.eeeeeeeeeeeeeeeeeeeeee),
1005                False:
1006                    self.bbb.cccccccccc(ddddddddddddddddddddddd.eeeeeeeeeeeeeeeeeeeeee)
1007            })
1008        """)
1009    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1010    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1011
1012  def testB27266946(self):
1013    unformatted_code = textwrap.dedent("""\
1014        def _():
1015          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (self.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.cccccccccccccccccccccccccccccccccccc)
1016        """)
1017    expected_formatted_code = textwrap.dedent("""\
1018        def _():
1019          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (
1020              self.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.
1021              cccccccccccccccccccccccccccccccccccc)
1022        """)
1023    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1024    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1025
1026  def testB25505359(self):
1027    code = textwrap.dedent("""\
1028        _EXAMPLE = {
1029            'aaaaaaaaaaaaaa': [{
1030                'bbbb': 'cccccccccccccccccccccc',
1031                'dddddddddddd': []
1032            }, {
1033                'bbbb': 'ccccccccccccccccccc',
1034                'dddddddddddd': []
1035            }]
1036        }
1037        """)
1038    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1039    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1040
1041  def testB25324261(self):
1042    code = textwrap.dedent("""\
1043        aaaaaaaaa = set(bbbb.cccc
1044                        for ddd in eeeeee.fffffffffff.gggggggggggggggg
1045                        for cccc in ddd.specification)
1046        """)
1047    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1048    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1049
1050  def testB25136704(self):
1051    code = textwrap.dedent("""\
1052        class f:
1053
1054          def test(self):
1055            self.bbbbbbb[0]['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', {
1056                'xxxxxx': 'yyyyyy'
1057            }] = cccccc.ddd('1m', '10x1+1')
1058        """)
1059    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1060    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1061
1062  def testB25165602(self):
1063    code = textwrap.dedent("""\
1064        def f():
1065          ids = {u: i for u, i in zip(self.aaaaa, xrange(42, 42 + len(self.aaaaaa)))}
1066        """)
1067    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1068    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1069
1070  def testB25157123(self):
1071    code = textwrap.dedent("""\
1072        def ListArgs():
1073          FairlyLongMethodName([relatively_long_identifier_for_a_list],
1074                               another_argument_with_a_long_identifier)
1075        """)
1076    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1077    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1078
1079  def testB25136820(self):
1080    unformatted_code = textwrap.dedent("""\
1081        def foo():
1082          return collections.OrderedDict({
1083              # Preceding comment.
1084              'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa':
1085              '$bbbbbbbbbbbbbbbbbbbbbbbb',
1086          })
1087        """)
1088    expected_formatted_code = textwrap.dedent("""\
1089        def foo():
1090          return collections.OrderedDict({
1091              # Preceding comment.
1092              'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa':
1093                  '$bbbbbbbbbbbbbbbbbbbbbbbb',
1094          })
1095        """)
1096    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1097    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1098
1099  def testB25131481(self):
1100    unformatted_code = textwrap.dedent("""\
1101        APPARENT_ACTIONS = ('command_type', {
1102            'materialize': lambda x: some_type_of_function('materialize ' + x.command_def),
1103            '#': lambda x: x  # do nothing
1104        })
1105        """)
1106    expected_formatted_code = textwrap.dedent("""\
1107        APPARENT_ACTIONS = (
1108            'command_type',
1109            {
1110                'materialize':
1111                    lambda x: some_type_of_function('materialize ' + x.command_def),
1112                '#':
1113                    lambda x: x  # do nothing
1114            })
1115        """)
1116    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1117    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1118
1119  def testB23445244(self):
1120    unformatted_code = textwrap.dedent("""\
1121        def foo():
1122          if True:
1123            return xxxxxxxxxxxxxxxx(
1124                command,
1125                extra_env={
1126                    "OOOOOOOOOOOOOOOOOOOOO": FLAGS.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
1127                    "PPPPPPPPPPPPPPPPPPPPP":
1128                        FLAGS.aaaaaaaaaaaaaa + FLAGS.bbbbbbbbbbbbbbbbbbb,
1129                })
1130        """)
1131    expected_formatted_code = textwrap.dedent("""\
1132        def foo():
1133          if True:
1134            return xxxxxxxxxxxxxxxx(
1135                command,
1136                extra_env={
1137                    "OOOOOOOOOOOOOOOOOOOOO":
1138                        FLAGS.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
1139                    "PPPPPPPPPPPPPPPPPPPPP":
1140                        FLAGS.aaaaaaaaaaaaaa + FLAGS.bbbbbbbbbbbbbbbbbbb,
1141                })
1142        """)
1143    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1144    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1145
1146  def testB20559654(self):
1147    unformatted_code = textwrap.dedent("""\
1148      class A(object):
1149
1150        def foo(self):
1151          unused_error, result = server.Query(
1152              ['AA BBBB CCC DDD EEEEEEEE X YY ZZZZ FFF EEE AAAAAAAA'],
1153              aaaaaaaaaaa=True, bbbbbbbb=None)
1154        """)
1155    expected_formatted_code = textwrap.dedent("""\
1156      class A(object):
1157
1158        def foo(self):
1159          unused_error, result = server.Query(
1160              ['AA BBBB CCC DDD EEEEEEEE X YY ZZZZ FFF EEE AAAAAAAA'],
1161              aaaaaaaaaaa=True,
1162              bbbbbbbb=None)
1163        """)
1164    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1165    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1166
1167  def testB23943842(self):
1168    unformatted_code = textwrap.dedent("""\
1169        class F():
1170          def f():
1171            self.assertDictEqual(
1172                accounts, {
1173                    'foo':
1174                    {'account': 'foo',
1175                     'lines': 'l1\\nl2\\nl3\\n1 line(s) were elided.'},
1176                    'bar': {'account': 'bar',
1177                            'lines': 'l5\\nl6\\nl7'},
1178                    'wiz': {'account': 'wiz',
1179                            'lines': 'l8'}
1180                })
1181        """)
1182    expected_formatted_code = textwrap.dedent("""\
1183        class F():
1184
1185          def f():
1186            self.assertDictEqual(
1187                accounts, {
1188                    'foo': {
1189                        'account': 'foo',
1190                        'lines': 'l1\\nl2\\nl3\\n1 line(s) were elided.'
1191                    },
1192                    'bar': {
1193                        'account': 'bar',
1194                        'lines': 'l5\\nl6\\nl7'
1195                    },
1196                    'wiz': {
1197                        'account': 'wiz',
1198                        'lines': 'l8'
1199                    }
1200                })
1201        """)
1202    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1203    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1204
1205  def testB20551180(self):
1206    unformatted_code = textwrap.dedent("""\
1207        def foo():
1208          if True:
1209            return (struct.pack('aaaa', bbbbbbbbbb, ccccccccccccccc, dddddddd) + eeeeeee)
1210        """)
1211    expected_formatted_code = textwrap.dedent("""\
1212        def foo():
1213          if True:
1214            return (
1215                struct.pack('aaaa', bbbbbbbbbb, ccccccccccccccc, dddddddd) + eeeeeee)
1216        """)
1217    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1218    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1219
1220  def testB23944849(self):
1221    unformatted_code = textwrap.dedent("""\
1222        class A(object):
1223          def xxxxxxxxx(self, aaaaaaa, bbbbbbb=ccccccccccc, dddddd=300, eeeeeeeeeeeeee=None, fffffffffffffff=0):
1224            pass
1225        """)
1226    expected_formatted_code = textwrap.dedent("""\
1227        class A(object):
1228
1229          def xxxxxxxxx(self,
1230                        aaaaaaa,
1231                        bbbbbbb=ccccccccccc,
1232                        dddddd=300,
1233                        eeeeeeeeeeeeee=None,
1234                        fffffffffffffff=0):
1235            pass
1236        """)
1237    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1238    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1239
1240  def testB23935890(self):
1241    unformatted_code = textwrap.dedent("""\
1242        class F():
1243          def functioni(self, aaaaaaa, bbbbbbb, cccccc, dddddddddddddd, eeeeeeeeeeeeeee):
1244            pass
1245        """)
1246    expected_formatted_code = textwrap.dedent("""\
1247        class F():
1248
1249          def functioni(self, aaaaaaa, bbbbbbb, cccccc, dddddddddddddd,
1250                        eeeeeeeeeeeeeee):
1251            pass
1252        """)
1253    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1254    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1255
1256  def testB28414371(self):
1257    code = textwrap.dedent("""\
1258        def _():
1259          return ((m.fffff(
1260              m.rrr('mmmmmmmmmmmmmmmm', 'ssssssssssssssssssssssssss'), ffffffffffffffff)
1261                   | m.wwwwww(m.ddddd('1h'))
1262                   | m.ggggggg(bbbbbbbbbbbbbbb)
1263                   | m.ppppp(
1264                       (1 - m.ffffffffffffffff(llllllllllllllllllllll * 1000000, m.vvv))
1265                       * m.ddddddddddddddddd(m.vvv)),
1266                   m.fffff(
1267                       m.rrr('mmmmmmmmmmmmmmmm', 'sssssssssssssssssssssss'),
1268                       dict(
1269                           ffffffffffffffff, **{
1270                               'mmmmmm:ssssss':
1271                                   m.rrrrrrrrrrr('|'.join(iiiiiiiiiiiiii), iiiiii=True)
1272                           }))
1273                   | m.wwwwww(m.rrrr('1h'))
1274                   | m.ggggggg(bbbbbbbbbbbbbbb))
1275                  | m.jjjj()
1276                  | m.ppppp(m.vvv[0] + m.vvv[1]))
1277        """)
1278    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1279    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1280
1281  def testB20127686(self):
1282    code = textwrap.dedent("""\
1283        def f():
1284          if True:
1285            return ((m.fffff(
1286                m.rrr('xxxxxxxxxxxxxxxx',
1287                      'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'),
1288                mmmmmmmm)
1289                     | m.wwwwww(m.rrrr(self.tttttttttt, self.mmmmmmmmmmmmmmmmmmmmm))
1290                     | m.ggggggg(self.gggggggg, m.sss()), m.fffff('aaaaaaaaaaaaaaaa')
1291                     | m.wwwwww(m.ddddd(self.tttttttttt, self.mmmmmmmmmmmmmmmmmmmmm))
1292                     | m.ggggggg(self.gggggggg))
1293                    | m.jjjj()
1294                    | m.ppppp(m.VAL[0] / m.VAL[1]))
1295        """)
1296    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1297    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1298
1299  def testB20016122(self):
1300    try:
1301      style.SetGlobalStyle(
1302          style.CreateStyleFromConfig(
1303              '{based_on_style: pep8, split_penalty_import_names: 35}'))
1304      unformatted_code = textwrap.dedent("""\
1305          from a_very_long_or_indented_module_name_yada_yada import (long_argument_1,
1306                                                                     long_argument_2)
1307          """)
1308      expected_formatted_code = textwrap.dedent("""\
1309          from a_very_long_or_indented_module_name_yada_yada import (
1310              long_argument_1, long_argument_2)
1311          """)
1312      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1313      self.assertCodeEqual(expected_formatted_code,
1314                           reformatter.Reformat(uwlines))
1315    finally:
1316      style.SetGlobalStyle(style.CreatePEP8Style())
1317
1318    try:
1319      style.SetGlobalStyle(
1320          style.CreateStyleFromConfig('{based_on_style: chromium, '
1321                                      'split_before_logical_operator: True}'))
1322      code = textwrap.dedent("""\
1323          class foo():
1324
1325            def __eq__(self, other):
1326              return (isinstance(other, type(self))
1327                      and self.xxxxxxxxxxx == other.xxxxxxxxxxx
1328                      and self.xxxxxxxx == other.xxxxxxxx
1329                      and self.aaaaaaaaaaaa == other.aaaaaaaaaaaa
1330                      and self.bbbbbbbbbbb == other.bbbbbbbbbbb
1331                      and self.ccccccccccccccccc == other.ccccccccccccccccc
1332                      and self.ddddddddddddddddddddddd == other.ddddddddddddddddddddddd
1333                      and self.eeeeeeeeeeee == other.eeeeeeeeeeee
1334                      and self.ffffffffffffff == other.time_completed
1335                      and self.gggggg == other.gggggg and self.hhh == other.hhh
1336                      and len(self.iiiiiiii) == len(other.iiiiiiii)
1337                      and all(jjjjjjj in other.iiiiiiii for jjjjjjj in self.iiiiiiii))
1338          """)
1339      uwlines = yapf_test_helper.ParseAndUnwrap(code)
1340      self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1341    finally:
1342      style.SetGlobalStyle(style.CreateChromiumStyle())
1343
1344  def testB22527411(self):
1345    unformatted_code = textwrap.dedent("""\
1346        def f():
1347          if True:
1348            aaaaaa.bbbbbbbbbbbbbbbbbbbb[-1].cccccccccccccc.ddd().eeeeeeee(ffffffffffffff)
1349        """)
1350    expected_formatted_code = textwrap.dedent("""\
1351        def f():
1352          if True:
1353            aaaaaa.bbbbbbbbbbbbbbbbbbbb[-1].cccccccccccccc.ddd().eeeeeeee(
1354                ffffffffffffff)
1355        """)
1356    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1357    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1358
1359  def testB20849933(self):
1360    unformatted_code = textwrap.dedent("""\
1361        def main(unused_argv):
1362          if True:
1363            aaaaaaaa = {
1364                'xxx': '%s/cccccc/ddddddddddddddddddd.jar' %
1365                       (eeeeee.FFFFFFFFFFFFFFFFFF),
1366            }
1367        """)
1368    expected_formatted_code = textwrap.dedent("""\
1369        def main(unused_argv):
1370          if True:
1371            aaaaaaaa = {
1372                'xxx':
1373                    '%s/cccccc/ddddddddddddddddddd.jar' % (eeeeee.FFFFFFFFFFFFFFFFFF),
1374            }
1375        """)
1376    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1377    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1378
1379  def testB20813997(self):
1380    code = textwrap.dedent("""\
1381        def myfunc_1():
1382          myarray = numpy.zeros((2, 2, 2))
1383          print(myarray[:, 1, :])
1384        """)
1385    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1386    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1387
1388  def testB20605036(self):
1389    code = textwrap.dedent("""\
1390        foo = {
1391            'aaaa': {
1392                # A comment for no particular reason.
1393                'xxxxxxxx': 'bbbbbbbbb',
1394                'yyyyyyyyyyyyyyyyyy': 'cccccccccccccccccccccccccccccc'
1395                                      'dddddddddddddddddddddddddddddddddddddddddd',
1396            }
1397        }
1398        """)
1399    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1400    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1401
1402  def testB20562732(self):
1403    code = textwrap.dedent("""\
1404        foo = [
1405            # Comment about first list item
1406            'First item',
1407            # Comment about second list item
1408            'Second item',
1409        ]
1410        """)
1411    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1412    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1413
1414  def testB20128830(self):
1415    code = textwrap.dedent("""\
1416        a = {
1417            'xxxxxxxxxxxxxxxxxxxx': {
1418                'aaaa':
1419                    'mmmmmmm',
1420                'bbbbb':
1421                    'mmmmmmmmmmmmmmmmmmmmm',
1422                'cccccccccc': [
1423                    'nnnnnnnnnnn',
1424                    'ooooooooooo',
1425                    'ppppppppppp',
1426                    'qqqqqqqqqqq',
1427                ],
1428            },
1429        }
1430        """)
1431    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1432    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1433
1434  def testB20073838(self):
1435    code = textwrap.dedent("""\
1436        class DummyModel(object):
1437
1438          def do_nothing(self, class_1_count):
1439            if True:
1440              class_0_count = num_votes - class_1_count
1441              return ('{class_0_name}={class_0_count}, {class_1_name}={class_1_count}'
1442                      .format(
1443                          class_0_name=self.class_0_name,
1444                          class_0_count=class_0_count,
1445                          class_1_name=self.class_1_name,
1446                          class_1_count=class_1_count))
1447        """)
1448    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1449    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1450
1451  def testB19626808(self):
1452    code = textwrap.dedent("""\
1453        if True:
1454          aaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbb(
1455              'ccccccccccc', ddddddddd='eeeee').fffffffff([ggggggggggggggggggggg])
1456        """)
1457    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1458    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1459
1460  def testB19547210(self):
1461    code = textwrap.dedent("""\
1462        while True:
1463          if True:
1464            if True:
1465              if True:
1466                if xxxxxxxxxxxx.yyyyyyy(aa).zzzzzzz() not in (
1467                    xxxxxxxxxxxx.yyyyyyyyyyyyyy.zzzzzzzz,
1468                    xxxxxxxxxxxx.yyyyyyyyyyyyyy.zzzzzzzz):
1469                  continue
1470        """)
1471    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1472    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1473
1474  def testB19377034(self):
1475    code = textwrap.dedent("""\
1476        def f():
1477          if (aaaaaaaaaaaaaaa.start >= aaaaaaaaaaaaaaa.end or
1478              bbbbbbbbbbbbbbb.start >= bbbbbbbbbbbbbbb.end):
1479            return False
1480        """)
1481    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1482    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1483
1484  def testB19372573(self):
1485    code = textwrap.dedent("""\
1486        def f():
1487            if a: return 42
1488            while True:
1489                if b: continue
1490                if c: break
1491            return 0
1492        """)
1493    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1494    try:
1495      style.SetGlobalStyle(style.CreatePEP8Style())
1496      self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1497    finally:
1498      style.SetGlobalStyle(style.CreateChromiumStyle())
1499
1500  def testB19353268(self):
1501    code = textwrap.dedent("""\
1502        a = {1, 2, 3}[x]
1503        b = {'foo': 42, 'bar': 37}['foo']
1504        """)
1505    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1506    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1507
1508  def testB19287512(self):
1509    unformatted_code = textwrap.dedent("""\
1510        class Foo(object):
1511
1512          def bar(self):
1513            with xxxxxxxxxx.yyyyy(
1514                'aaaaaaa.bbbbbbbb.ccccccc.dddddddddddddddddddd.eeeeeeeeeee',
1515                fffffffffff=(aaaaaaa.bbbbbbbb.ccccccc.dddddddddddddddddddd
1516                             .Mmmmmmmmmmmmmmmmmm(-1, 'permission error'))):
1517              self.assertRaises(nnnnnnnnnnnnnnnn.ooooo, ppppp.qqqqqqqqqqqqqqqqq)
1518        """)
1519    expected_formatted_code = textwrap.dedent("""\
1520        class Foo(object):
1521
1522          def bar(self):
1523            with xxxxxxxxxx.yyyyy(
1524                'aaaaaaa.bbbbbbbb.ccccccc.dddddddddddddddddddd.eeeeeeeeeee',
1525                fffffffffff=(
1526                    aaaaaaa.bbbbbbbb.ccccccc.dddddddddddddddddddd.Mmmmmmmmmmmmmmmmmm(
1527                        -1, 'permission error'))):
1528              self.assertRaises(nnnnnnnnnnnnnnnn.ooooo, ppppp.qqqqqqqqqqqqqqqqq)
1529        """)
1530    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1531    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1532
1533  def testB19194420(self):
1534    code = textwrap.dedent("""\
1535        method.Set(
1536            'long argument goes here that causes the line to break',
1537            lambda arg2=0.5: arg2)
1538        """)
1539    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1540    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1541
1542  def testB19073499(self):
1543    code = """\
1544instance = (
1545    aaaaaaa.bbbbbbb().ccccccccccccccccc().ddddddddddd({
1546        'aa': 'context!'
1547    }).eeeeeeeeeeeeeeeeeee({  # Inline comment about why fnord has the value 6.
1548        'fnord': 6
1549    }))
1550"""
1551    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1552    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1553
1554  def testB18257115(self):
1555    code = textwrap.dedent("""\
1556        if True:
1557          if True:
1558            self._Test(aaaa, bbbbbbb.cccccccccc, dddddddd, eeeeeeeeeee,
1559                       [ffff, ggggggggggg, hhhhhhhhhhhh, iiiiii, jjjj])
1560        """)
1561    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1562    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1563
1564  def testB18256666(self):
1565    code = textwrap.dedent("""\
1566        class Foo(object):
1567
1568          def Bar(self):
1569            aaaaa.bbbbbbb(
1570                ccc='ddddddddddddddd',
1571                eeee='ffffffffffffffffffffff-%s-%s' % (gggg, int(time.time())),
1572                hhhhhh={
1573                    'iiiiiiiiiii': iiiiiiiiiii,
1574                    'jjjj': jjjj.jjjjj(),
1575                    'kkkkkkkkkkkk': kkkkkkkkkkkk,
1576                },
1577                llllllllll=mmmmmm.nnnnnnnnnnnnnnnn)
1578        """)
1579    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1580    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1581
1582  def testB18256826(self):
1583    code = textwrap.dedent("""\
1584        if True:
1585          pass
1586        # A multiline comment.
1587        # Line two.
1588        elif False:
1589          pass
1590
1591        if True:
1592          pass
1593          # A multiline comment.
1594          # Line two.
1595        elif False:
1596          pass
1597        """)
1598    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1599    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1600
1601  def testB18255697(self):
1602    code = textwrap.dedent("""\
1603        AAAAAAAAAAAAAAA = {
1604            'XXXXXXXXXXXXXX': 4242,  # Inline comment
1605            # Next comment
1606            'YYYYYYYYYYYYYYYY': ['zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'],
1607        }
1608        """)
1609    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1610    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1611
1612  def testB17534869(self):
1613    unformatted_code = textwrap.dedent("""\
1614        if True:
1615          self.assertLess(abs(time.time()-aaaa.bbbbbbbbbbb(
1616                              datetime.datetime.now())), 1)
1617        """)
1618    expected_formatted_code = textwrap.dedent("""\
1619        if True:
1620          self.assertLess(
1621              abs(time.time() - aaaa.bbbbbbbbbbb(datetime.datetime.now())), 1)
1622        """)
1623    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1624    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1625
1626  def testB17489866(self):
1627    unformatted_code = textwrap.dedent("""\
1628        def f():
1629          if True:
1630            if True:
1631              return aaaa.bbbbbbbbb(ccccccc=dddddddddddddd({('eeee', \
1632'ffffffff'): str(j)}))
1633        """)
1634    expected_formatted_code = textwrap.dedent("""\
1635        def f():
1636          if True:
1637            if True:
1638              return aaaa.bbbbbbbbb(
1639                  ccccccc=dddddddddddddd({
1640                      ('eeee', 'ffffffff'): str(j)
1641                  }))
1642        """)
1643    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1644    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1645
1646  def testB17133019(self):
1647    unformatted_code = textwrap.dedent("""\
1648        class aaaaaaaaaaaaaa(object):
1649
1650          def bbbbbbbbbb(self):
1651            with io.open("/dev/null", "rb"):
1652              with io.open(os.path.join(aaaaa.bbbbb.ccccccccccc,
1653                                        DDDDDDDDDDDDDDD,
1654                                        "eeeeeeeee ffffffffff"
1655                                       ), "rb") as gggggggggggggggggggg:
1656                print(gggggggggggggggggggg)
1657        """)
1658    expected_formatted_code = textwrap.dedent("""\
1659        class aaaaaaaaaaaaaa(object):
1660
1661          def bbbbbbbbbb(self):
1662            with io.open("/dev/null", "rb"):
1663              with io.open(
1664                  os.path.join(aaaaa.bbbbb.ccccccccccc, DDDDDDDDDDDDDDD,
1665                               "eeeeeeeee ffffffffff"), "rb") as gggggggggggggggggggg:
1666                print(gggggggggggggggggggg)
1667        """)
1668    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1669    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1670
1671  def testB17011869(self):
1672    unformatted_code = textwrap.dedent("""\
1673        '''blah......'''
1674
1675        class SomeClass(object):
1676          '''blah.'''
1677
1678          AAAAAAAAAAAA = {                        # Comment.
1679              'BBB': 1.0,
1680                'DDDDDDDD': 0.4811
1681                                      }
1682        """)
1683    expected_formatted_code = textwrap.dedent("""\
1684        '''blah......'''
1685
1686
1687        class SomeClass(object):
1688          '''blah.'''
1689
1690          AAAAAAAAAAAA = {  # Comment.
1691              'BBB': 1.0,
1692              'DDDDDDDD': 0.4811
1693          }
1694        """)
1695    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1696    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1697
1698  def testB16783631(self):
1699    unformatted_code = textwrap.dedent("""\
1700        if True:
1701          with aaaaaaaaaaaaaa.bbbbbbbbbbbbb.ccccccc(ddddddddddddd,
1702                                                      eeeeeeeee=self.fffffffffffff
1703                                                      )as gggg:
1704            pass
1705        """)
1706    expected_formatted_code = textwrap.dedent("""\
1707        if True:
1708          with aaaaaaaaaaaaaa.bbbbbbbbbbbbb.ccccccc(
1709              ddddddddddddd, eeeeeeeee=self.fffffffffffff) as gggg:
1710            pass
1711        """)
1712    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1713    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1714
1715  def testB16572361(self):
1716    unformatted_code = textwrap.dedent("""\
1717        def foo(self):
1718         def bar(my_dict_name):
1719          self.my_dict_name['foo-bar-baz-biz-boo-baa-baa'].IncrementBy.assert_called_once_with('foo_bar_baz_boo')
1720        """)
1721    expected_formatted_code = textwrap.dedent("""\
1722        def foo(self):
1723
1724          def bar(my_dict_name):
1725            self.my_dict_name[
1726                'foo-bar-baz-biz-boo-baa-baa'].IncrementBy.assert_called_once_with(
1727                    'foo_bar_baz_boo')
1728        """)
1729    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1730    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1731
1732  def testB15884241(self):
1733    unformatted_code = textwrap.dedent("""\
1734        if 1:
1735          if 1:
1736            for row in AAAA:
1737              self.create(aaaaaaaa="/aaa/bbbb/cccc/dddddd/eeeeeeeeeeeeeeeeeeeeeeeeee/%s" % row [0].replace(".foo", ".bar"), aaaaa=bbb[1], ccccc=bbb[2], dddd=bbb[3], eeeeeeeeeee=[s.strip() for s in bbb[4].split(",")], ffffffff=[s.strip() for s in bbb[5].split(",")], gggggg=bbb[6])
1738        """)
1739    expected_formatted_code = textwrap.dedent("""\
1740        if 1:
1741          if 1:
1742            for row in AAAA:
1743              self.create(
1744                  aaaaaaaa="/aaa/bbbb/cccc/dddddd/eeeeeeeeeeeeeeeeeeeeeeeeee/%s" %
1745                  row[0].replace(".foo", ".bar"),
1746                  aaaaa=bbb[1],
1747                  ccccc=bbb[2],
1748                  dddd=bbb[3],
1749                  eeeeeeeeeee=[s.strip() for s in bbb[4].split(",")],
1750                  ffffffff=[s.strip() for s in bbb[5].split(",")],
1751                  gggggg=bbb[6])
1752        """)
1753    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1754    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1755
1756  def testB15697268(self):
1757    unformatted_code = textwrap.dedent("""\
1758        def main(unused_argv):
1759          ARBITRARY_CONSTANT_A = 10
1760          an_array_with_an_exceedingly_long_name = range(ARBITRARY_CONSTANT_A + 1)
1761          ok = an_array_with_an_exceedingly_long_name[:ARBITRARY_CONSTANT_A]
1762          bad_slice = map(math.sqrt, an_array_with_an_exceedingly_long_name[:ARBITRARY_CONSTANT_A])
1763          a_long_name_slicing = an_array_with_an_exceedingly_long_name[:ARBITRARY_CONSTANT_A]
1764          bad_slice = ("I am a crazy, no good, string whats too long, etc." + " no really ")[:ARBITRARY_CONSTANT_A]
1765        """)
1766    expected_formatted_code = textwrap.dedent("""\
1767        def main(unused_argv):
1768          ARBITRARY_CONSTANT_A = 10
1769          an_array_with_an_exceedingly_long_name = range(ARBITRARY_CONSTANT_A + 1)
1770          ok = an_array_with_an_exceedingly_long_name[:ARBITRARY_CONSTANT_A]
1771          bad_slice = map(math.sqrt,
1772                          an_array_with_an_exceedingly_long_name[:ARBITRARY_CONSTANT_A])
1773          a_long_name_slicing = an_array_with_an_exceedingly_long_name[:
1774                                                                       ARBITRARY_CONSTANT_A]
1775          bad_slice = ("I am a crazy, no good, string whats too long, etc." +
1776                       " no really ")[:ARBITRARY_CONSTANT_A]
1777        """)
1778    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1779    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1780
1781  def testB15597568(self):
1782    unformatted_code = textwrap.dedent("""\
1783        if True:
1784          if True:
1785            if True:
1786              print(("Return code was %d" + (", and the process timed out." if did_time_out else ".")) % errorcode)
1787        """)
1788    expected_formatted_code = textwrap.dedent("""\
1789        if True:
1790          if True:
1791            if True:
1792              print(("Return code was %d" + (", and the process timed out."
1793                                             if did_time_out else ".")) % errorcode)
1794        """)
1795    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1796    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1797
1798  def testB15542157(self):
1799    unformatted_code = textwrap.dedent("""\
1800        aaaaaaaaaaaa = bbbb.ccccccccccccccc(dddddd.eeeeeeeeeeeeee, ffffffffffffffffff, gggggg.hhhhhhhhhhhhhhhhh)
1801        """)
1802    expected_formatted_code = textwrap.dedent("""\
1803        aaaaaaaaaaaa = bbbb.ccccccccccccccc(dddddd.eeeeeeeeeeeeee, ffffffffffffffffff,
1804                                            gggggg.hhhhhhhhhhhhhhhhh)
1805        """)
1806    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1807    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1808
1809  def testB15438132(self):
1810    unformatted_code = textwrap.dedent("""\
1811        if aaaaaaa.bbbbbbbbbb:
1812           cccccc.dddddddddd(eeeeeeeeeee=fffffffffffff.gggggggggggggggggg)
1813           if hhhhhh.iiiii.jjjjjjjjjjjjj:
1814             # This is a comment in the middle of it all.
1815             kkkkkkk.llllllllll.mmmmmmmmmmmmm = True
1816           if (aaaaaa.bbbbb.ccccccccccccc != ddddddd.eeeeeeeeee.fffffffffffff or
1817               eeeeee.fffff.ggggggggggggggggggggggggggg() != hhhhhhh.iiiiiiiiii.jjjjjjjjjjjj):
1818             aaaaaaaa.bbbbbbbbbbbb(
1819                 aaaaaa.bbbbb.cc,
1820                 dddddddddddd=eeeeeeeeeeeeeeeeeee.fffffffffffffffff(
1821                     gggggg.hh,
1822                     iiiiiiiiiiiiiiiiiii.jjjjjjjjjj.kkkkkkk,
1823                     lllll.mm),
1824                 nnnnnnnnnn=ooooooo.pppppppppp)
1825        """)
1826    expected_formatted_code = textwrap.dedent("""\
1827        if aaaaaaa.bbbbbbbbbb:
1828          cccccc.dddddddddd(eeeeeeeeeee=fffffffffffff.gggggggggggggggggg)
1829          if hhhhhh.iiiii.jjjjjjjjjjjjj:
1830            # This is a comment in the middle of it all.
1831            kkkkkkk.llllllllll.mmmmmmmmmmmmm = True
1832          if (aaaaaa.bbbbb.ccccccccccccc != ddddddd.eeeeeeeeee.fffffffffffff or
1833              eeeeee.fffff.ggggggggggggggggggggggggggg() !=
1834              hhhhhhh.iiiiiiiiii.jjjjjjjjjjjj):
1835            aaaaaaaa.bbbbbbbbbbbb(
1836                aaaaaa.bbbbb.cc,
1837                dddddddddddd=eeeeeeeeeeeeeeeeeee.fffffffffffffffff(
1838                    gggggg.hh, iiiiiiiiiiiiiiiiiii.jjjjjjjjjj.kkkkkkk, lllll.mm),
1839                nnnnnnnnnn=ooooooo.pppppppppp)
1840        """)
1841    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1842    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1843
1844  def testB14468247(self):
1845    unformatted_code = """\
1846call(a=1,
1847    b=2,
1848)
1849"""
1850    expected_formatted_code = """\
1851call(
1852    a=1,
1853    b=2,
1854)
1855"""
1856    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1857    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1858
1859  def testB14406499(self):
1860    unformatted_code = textwrap.dedent("""\
1861        def foo1(parameter_1, parameter_2, parameter_3, parameter_4, \
1862parameter_5, parameter_6): pass
1863        """)
1864    expected_formatted_code = textwrap.dedent("""\
1865        def foo1(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5,
1866                 parameter_6):
1867          pass
1868        """)
1869    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1870    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1871
1872  def testB13900309(self):
1873    unformatted_code = textwrap.dedent("""\
1874        self.aaaaaaaaaaa(  # A comment in the middle of it all.
1875               948.0/3600, self.bbb.ccccccccccccccccccccc(dddddddddddddddd.eeee, True))
1876        """)
1877    expected_formatted_code = textwrap.dedent("""\
1878        self.aaaaaaaaaaa(  # A comment in the middle of it all.
1879            948.0 / 3600, self.bbb.ccccccccccccccccccccc(dddddddddddddddd.eeee, True))
1880        """)
1881    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1882    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1883
1884    code = textwrap.dedent("""\
1885        aaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbb.cccccccccccccccccccccccccccccc(
1886            DC_1, (CL - 50, CL), AAAAAAAA, BBBBBBBBBBBBBBBB, 98.0,
1887            CCCCCCC).ddddddddd(  # Look! A comment is here.
1888                AAAAAAAA - (20 * 60 - 5))
1889        """)
1890    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1891    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1892
1893    unformatted_code = textwrap.dedent("""\
1894        aaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbb.ccccccccccccccccccccccccc().dddddddddddddddddddddddddd(1, 2, 3, 4)
1895        """)
1896    expected_formatted_code = textwrap.dedent("""\
1897        aaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbb.ccccccccccccccccccccccccc(
1898        ).dddddddddddddddddddddddddd(1, 2, 3, 4)
1899        """)
1900    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1901    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1902
1903    unformatted_code = textwrap.dedent("""\
1904        aaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbb.ccccccccccccccccccccccccc(x).dddddddddddddddddddddddddd(1, 2, 3, 4)
1905        """)
1906    expected_formatted_code = textwrap.dedent("""\
1907        aaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbb.ccccccccccccccccccccccccc(
1908            x).dddddddddddddddddddddddddd(1, 2, 3, 4)
1909        """)
1910    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1911    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1912
1913    unformatted_code = textwrap.dedent("""\
1914        aaaaaaaaaaaaaaaaaaaaaaaa(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx).dddddddddddddddddddddddddd(1, 2, 3, 4)
1915        """)
1916    expected_formatted_code = textwrap.dedent("""\
1917        aaaaaaaaaaaaaaaaaaaaaaaa(
1918            xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx).dddddddddddddddddddddddddd(1, 2, 3, 4)
1919        """)
1920    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1921    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1922
1923    unformatted_code = textwrap.dedent("""\
1924        aaaaaaaaaaaaaaaaaaaaaaaa().bbbbbbbbbbbbbbbbbbbbbbbb().ccccccccccccccccccc().\
1925dddddddddddddddddd().eeeeeeeeeeeeeeeeeeeee().fffffffffffffffff().gggggggggggggggggg()
1926        """)
1927    expected_formatted_code = textwrap.dedent("""\
1928        aaaaaaaaaaaaaaaaaaaaaaaa().bbbbbbbbbbbbbbbbbbbbbbbb().ccccccccccccccccccc(
1929        ).dddddddddddddddddd().eeeeeeeeeeeeeeeeeeeee().fffffffffffffffff(
1930        ).gggggggggggggggggg()
1931        """)
1932    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1933    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1934
1935  def testB67935687(self):
1936    code = textwrap.dedent("""\
1937        Fetch(
1938            Raw('monarch.BorgTask', '/union/row_operator_action_delay'),
1939            {'borg_user': self.borg_user})
1940    """)
1941    uwlines = yapf_test_helper.ParseAndUnwrap(code)
1942    self.assertCodeEqual(code, reformatter.Reformat(uwlines))
1943
1944    unformatted_code = textwrap.dedent("""\
1945        shelf_renderer.expand_text = text.translate_to_unicode(
1946            expand_text % {
1947                'creator': creator
1948            })
1949        """)
1950    expected_formatted_code = textwrap.dedent("""\
1951        shelf_renderer.expand_text = text.translate_to_unicode(
1952            expand_text % {'creator': creator})
1953        """)
1954    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
1955    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
1956
1957
1958if __name__ == '__main__':
1959  unittest.main()
1960