| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872 |
- # Copyright 2016 Google Inc. All Rights Reserved.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- """PEP8 tests for yapf.reformatter."""
- import textwrap
- import unittest
- from yapf.yapflib import reformatter
- from yapf.yapflib import style
- from yapftests import yapf_test_helper
- class TestsForPEP8Style(yapf_test_helper.YAPFTest):
- @classmethod
- def setUpClass(cls): # pylint: disable=g-missing-super-call
- style.SetGlobalStyle(style.CreatePEP8Style())
- def testIndent4(self):
- unformatted_code = textwrap.dedent("""\
- if a+b:
- pass
- """)
- expected_formatted_code = textwrap.dedent("""\
- if a + b:
- pass
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testSingleLineIfStatements(self):
- code = textwrap.dedent("""\
- if True: a = 42
- elif False: b = 42
- else: c = 42
- """)
- llines = yapf_test_helper.ParseAndUnwrap(code)
- self.assertCodeEqual(code, reformatter.Reformat(llines))
- def testBlankBetweenClassAndDef(self):
- unformatted_code = textwrap.dedent("""\
- class Foo:
- def joe():
- pass
- """)
- expected_formatted_code = textwrap.dedent("""\
- class Foo:
- def joe():
- pass
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testBlankBetweenDefsInClass(self):
- unformatted_code = textwrap.dedent('''\
- class TestClass:
- def __init__(self):
- self.running = False
- def run(self):
- """Override in subclass"""
- def is_running(self):
- return self.running
- ''')
- expected_formatted_code = textwrap.dedent('''\
- class TestClass:
- def __init__(self):
- self.running = False
- def run(self):
- """Override in subclass"""
- def is_running(self):
- return self.running
- ''')
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testSingleWhiteBeforeTrailingComment(self):
- unformatted_code = textwrap.dedent("""\
- if a+b: # comment
- pass
- """)
- expected_formatted_code = textwrap.dedent("""\
- if a + b: # comment
- pass
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testSpaceBetweenEndingCommandAndClosingBracket(self):
- unformatted_code = textwrap.dedent("""\
- a = (
- 1,
- )
- """)
- expected_formatted_code = textwrap.dedent("""\
- a = (1, )
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testContinuedNonOutdentedLine(self):
- code = textwrap.dedent("""\
- class eld(d):
- if str(geom.geom_type).upper(
- ) != self.geom_type and not self.geom_type == 'GEOMETRY':
- ror(code='om_type')
- """)
- llines = yapf_test_helper.ParseAndUnwrap(code)
- self.assertCodeEqual(code, reformatter.Reformat(llines))
- def testWrappingPercentExpressions(self):
- unformatted_code = textwrap.dedent("""\
- def f():
- if True:
- zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxx.yyy + 1)
- zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxx.yyy + 1)
- zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxxxxxx + 1)
- zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxx + 1, xxxxxxxxxxxxxxxxxxxxx + 1)
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- def f():
- if True:
- zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxxxxx + 1,
- xxxxxxxxxxxxxxxxx.yyy + 1)
- zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxxxxx + 1,
- xxxxxxxxxxxxxxxxx.yyy + 1)
- zzzzz = '%s-%s' % (xxxxxxxxxxxxxxxxxxxxxxx + 1,
- xxxxxxxxxxxxxxxxxxxxx + 1)
- zzzzz = '%s-%s'.ww(xxxxxxxxxxxxxxxxxxxxxxx + 1,
- xxxxxxxxxxxxxxxxxxxxx + 1)
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testAlignClosingBracketWithVisualIndentation(self):
- unformatted_code = textwrap.dedent("""\
- TEST_LIST = ('foo', 'bar', # first comment
- 'baz' # second comment
- )
- """)
- expected_formatted_code = textwrap.dedent("""\
- TEST_LIST = (
- 'foo',
- 'bar', # first comment
- 'baz' # second comment
- )
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- unformatted_code = textwrap.dedent("""\
- def f():
- def g():
- while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa' and
- xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'
- ):
- pass
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- def f():
- def g():
- while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa'
- and xxxxxxxxxxxxxxxxxxxx(
- yyyyyyyyyyyyy[zzzzz].aaaaaaaa[0]) == 'bbbbbbb'):
- pass
- """) # noqa
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testIndentSizeChanging(self):
- unformatted_code = textwrap.dedent("""\
- if True:
- runtime_mins = (program_end_time - program_start_time).total_seconds() / 60.0
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- if True:
- runtime_mins = (program_end_time -
- program_start_time).total_seconds() / 60.0
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testHangingIndentCollision(self):
- unformatted_code = textwrap.dedent("""\
- if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx or yyyyyyyyyyyyyyyyy):
- pass
- elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa, bbbbbbbbbbbbbb, cccccccccccc, dddddddddd=None)):
- pass
- def h():
- if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
- pass
- for connection in itertools.chain(branch.contact, branch.address, morestuff.andmore.andmore.andmore.andmore.andmore.andmore.andmore):
- dosomething(connection)
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx
- or yyyyyyyyyyyyyyyyy):
- pass
- elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa,
- bbbbbbbbbbbbbb,
- cccccccccccc,
- dddddddddd=None)):
- pass
- def h():
- if (xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0]) == 'aaaaaaaaaaa' and
- xxxxxxxxxxxx.yyyyyyyy(zzzzzzzzzzzzz[0].mmmmmmmm[0]) == 'bbbbbbb'):
- pass
- for connection in itertools.chain(
- branch.contact, branch.address,
- morestuff.andmore.andmore.andmore.andmore.andmore.andmore.andmore):
- dosomething(connection)
- """) # noqa
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testSplittingBeforeLogicalOperator(self):
- try:
- style.SetGlobalStyle(
- style.CreateStyleFromConfig(
- '{based_on_style: pep8, split_before_logical_operator: True}'))
- unformatted_code = textwrap.dedent("""\
- def foo():
- return bool(update.message.new_chat_member or update.message.left_chat_member or
- update.message.new_chat_title or update.message.new_chat_photo or
- update.message.delete_chat_photo or update.message.group_chat_created or
- update.message.supergroup_chat_created or update.message.channel_chat_created
- or update.message.migrate_to_chat_id or update.message.migrate_from_chat_id or
- update.message.pinned_message)
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- def foo():
- return bool(
- update.message.new_chat_member or update.message.left_chat_member
- or update.message.new_chat_title or update.message.new_chat_photo
- or update.message.delete_chat_photo
- or update.message.group_chat_created
- or update.message.supergroup_chat_created
- or update.message.channel_chat_created
- or update.message.migrate_to_chat_id
- or update.message.migrate_from_chat_id
- or update.message.pinned_message)
- """) # noqa
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- finally:
- style.SetGlobalStyle(style.CreatePEP8Style())
- def testContiguousListEndingWithComment(self):
- unformatted_code = textwrap.dedent("""\
- if True:
- if True:
- keys.append(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) # may be unassigned.
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- if True:
- if True:
- keys.append(
- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) # may be unassigned.
- """) # noqa
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testSplittingBeforeFirstArgument(self):
- try:
- style.SetGlobalStyle(
- style.CreateStyleFromConfig(
- '{based_on_style: pep8, split_before_first_argument: True}'))
- unformatted_code = textwrap.dedent("""\
- a_very_long_function_name(long_argument_name_1=1, long_argument_name_2=2,
- long_argument_name_3=3, long_argument_name_4=4)
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- a_very_long_function_name(
- long_argument_name_1=1,
- long_argument_name_2=2,
- long_argument_name_3=3,
- long_argument_name_4=4)
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- finally:
- style.SetGlobalStyle(style.CreatePEP8Style())
- def testSplittingExpressionsInsideSubscripts(self):
- unformatted_code = textwrap.dedent("""\
- def foo():
- df = df[(df['campaign_status'] == 'LIVE') & (df['action_status'] == 'LIVE')]
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- def foo():
- df = df[(df['campaign_status'] == 'LIVE')
- & (df['action_status'] == 'LIVE')]
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testSplitListsAndDictSetMakersIfCommaTerminated(self):
- unformatted_code = textwrap.dedent("""\
- DJANGO_TEMPLATES_OPTIONS = {"context_processors": []}
- DJANGO_TEMPLATES_OPTIONS = {"context_processors": [],}
- x = ["context_processors"]
- x = ["context_processors",]
- """)
- expected_formatted_code = textwrap.dedent("""\
- DJANGO_TEMPLATES_OPTIONS = {"context_processors": []}
- DJANGO_TEMPLATES_OPTIONS = {
- "context_processors": [],
- }
- x = ["context_processors"]
- x = [
- "context_processors",
- ]
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testSplitAroundNamedAssigns(self):
- unformatted_code = textwrap.dedent("""\
- class a():
- def a(): return a(
- aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)
- """)
- expected_formatted_code = textwrap.dedent("""\
- class a():
- def a():
- return a(
- aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- )
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testUnaryOperator(self):
- unformatted_code = textwrap.dedent("""\
- if not -3 < x < 3:
- pass
- if -3 < x < 3:
- pass
- """)
- expected_formatted_code = textwrap.dedent("""\
- if not -3 < x < 3:
- pass
- if -3 < x < 3:
- pass
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testNoSplitBeforeDictValue(self):
- try:
- style.SetGlobalStyle(
- style.CreateStyleFromConfig('{based_on_style: pep8, '
- 'allow_split_before_dict_value: false, '
- 'coalesce_brackets: true, '
- 'dedent_closing_brackets: true, '
- 'each_dict_entry_on_separate_line: true, '
- 'split_before_logical_operator: true}'))
- unformatted_code = textwrap.dedent("""\
- some_dict = {
- 'title': _("I am example data"),
- 'description': _("Lorem ipsum dolor met sit amet elit, si vis pacem para bellum "
- "elites nihi very long string."),
- }
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- some_dict = {
- 'title': _("I am example data"),
- 'description': _(
- "Lorem ipsum dolor met sit amet elit, si vis pacem para bellum "
- "elites nihi very long string."
- ),
- }
- """) # noqa
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- unformatted_code = textwrap.dedent("""\
- X = {'a': 1, 'b': 2, 'key': this_is_a_function_call_that_goes_over_the_column_limit_im_pretty_sure()}
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- X = {
- 'a': 1,
- 'b': 2,
- 'key': this_is_a_function_call_that_goes_over_the_column_limit_im_pretty_sure()
- }
- """) # noqa
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- unformatted_code = textwrap.dedent("""\
- attrs = {
- 'category': category,
- 'role': forms.ModelChoiceField(label=_("Role"), required=False, queryset=category_roles, initial=selected_role, empty_label=_("No access"),),
- }
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- attrs = {
- 'category': category,
- 'role': forms.ModelChoiceField(
- label=_("Role"),
- required=False,
- queryset=category_roles,
- initial=selected_role,
- empty_label=_("No access"),
- ),
- }
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- unformatted_code = textwrap.dedent("""\
- css_class = forms.CharField(
- label=_("CSS class"),
- required=False,
- help_text=_("Optional CSS class used to customize this category appearance from templates."),
- )
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- css_class = forms.CharField(
- label=_("CSS class"),
- required=False,
- help_text=_(
- "Optional CSS class used to customize this category appearance from templates."
- ),
- )
- """) # noqa
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- finally:
- style.SetGlobalStyle(style.CreatePEP8Style())
- def testBitwiseOperandSplitting(self):
- unformatted_code = """\
- def _():
- include_values = np.where(
- (cdffile['Quality_Flag'][:] >= 5) & (
- cdffile['Day_Night_Flag'][:] == 1) & (
- cdffile['Longitude'][:] >= select_lon - radius) & (
- cdffile['Longitude'][:] <= select_lon + radius) & (
- cdffile['Latitude'][:] >= select_lat - radius) & (
- cdffile['Latitude'][:] <= select_lat + radius))
- """
- expected_code = """\
- def _():
- include_values = np.where(
- (cdffile['Quality_Flag'][:] >= 5) & (cdffile['Day_Night_Flag'][:] == 1)
- & (cdffile['Longitude'][:] >= select_lon - radius)
- & (cdffile['Longitude'][:] <= select_lon + radius)
- & (cdffile['Latitude'][:] >= select_lat - radius)
- & (cdffile['Latitude'][:] <= select_lat + radius))
- """
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertEqual(expected_code, reformatter.Reformat(llines))
- def testNoBlankLinesOnlyForFirstNestedObject(self):
- unformatted_code = '''\
- class Demo:
- """
- Demo docs
- """
- def foo(self):
- """
- foo docs
- """
- def bar(self):
- """
- bar docs
- """
- '''
- expected_code = '''\
- class Demo:
- """
- Demo docs
- """
- def foo(self):
- """
- foo docs
- """
- def bar(self):
- """
- bar docs
- """
- '''
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertEqual(expected_code, reformatter.Reformat(llines))
- def testSplitBeforeArithmeticOperators(self):
- try:
- style.SetGlobalStyle(
- style.CreateStyleFromConfig(
- '{based_on_style: pep8, split_before_arithmetic_operator: true}'))
- unformatted_code = """\
- def _():
- raise ValueError('This is a long message that ends with an argument: ' + str(42))
- """ # noqa
- expected_formatted_code = """\
- def _():
- raise ValueError('This is a long message that ends with an argument: '
- + str(42))
- """
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- finally:
- style.SetGlobalStyle(style.CreatePEP8Style())
- def testListSplitting(self):
- unformatted_code = """\
- foo([(1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
- (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
- (1,10), (1,11), (1, 10), (1,11), (10,11)])
- """
- expected_code = """\
- foo([(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1),
- (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 10), (1, 11), (1, 10),
- (1, 11), (10, 11)])
- """
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_code, reformatter.Reformat(llines))
- def testNoBlankLineBeforeNestedFuncOrClass(self):
- try:
- style.SetGlobalStyle(
- style.CreateStyleFromConfig(
- '{based_on_style: pep8, '
- 'blank_line_before_nested_class_or_def: false}'))
- unformatted_code = '''\
- def normal_function():
- """Return the nested function."""
- def nested_function():
- """Do nothing just nest within."""
- @nested(klass)
- class nested_class():
- pass
- pass
- return nested_function
- '''
- expected_formatted_code = '''\
- def normal_function():
- """Return the nested function."""
- def nested_function():
- """Do nothing just nest within."""
- @nested(klass)
- class nested_class():
- pass
- pass
- return nested_function
- '''
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code,
- reformatter.Reformat(llines))
- finally:
- style.SetGlobalStyle(style.CreatePEP8Style())
- def testParamListIndentationCollision1(self):
- unformatted_code = textwrap.dedent("""\
- class _():
- def __init__(self, title: Optional[str], diffs: Collection[BinaryDiff] = (), charset: Union[Type[AsciiCharset], Type[LineCharset]] = AsciiCharset, preprocess: Callable[[str], str] = identity,
- # TODO(somebody): Make this a Literal type.
- justify: str = 'rjust'):
- self._cs = charset
- self._preprocess = preprocess
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- class _():
- def __init__(
- self,
- title: Optional[str],
- diffs: Collection[BinaryDiff] = (),
- charset: Union[Type[AsciiCharset],
- Type[LineCharset]] = AsciiCharset,
- preprocess: Callable[[str], str] = identity,
- # TODO(somebody): Make this a Literal type.
- justify: str = 'rjust'):
- self._cs = charset
- self._preprocess = preprocess
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testParamListIndentationCollision2(self):
- code = textwrap.dedent("""\
- def simple_pass_function_with_an_extremely_long_name_and_some_arguments(
- argument0, argument1):
- pass
- """)
- llines = yapf_test_helper.ParseAndUnwrap(code)
- self.assertCodeEqual(code, reformatter.Reformat(llines))
- def testParamListIndentationCollision3(self):
- code = textwrap.dedent("""\
- def func1(
- arg1,
- arg2,
- ) -> None:
- pass
- def func2(
- arg1,
- arg2,
- ):
- pass
- """)
- llines = yapf_test_helper.ParseAndUnwrap(code)
- self.assertCodeEqual(code, reformatter.Reformat(llines))
- def testTwoWordComparisonOperators(self):
- unformatted_code = textwrap.dedent("""\
- _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
- _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
- is not ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj)
- _ = (klsdfjdklsfjksdlfjdklsfjdslkfjsdkl
- not in {ksldfjsdklfjdklsfjdklsfjdklsfjdsklfjdklsfj})
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testStableInlinedDictionaryFormatting(self):
- unformatted_code = textwrap.dedent("""\
- def _():
- url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
- value, urllib.urlencode({'action': 'update', 'parameter': value}))
- """) # noqa
- expected_formatted_code = textwrap.dedent("""\
- def _():
- url = "http://{0}/axis-cgi/admin/param.cgi?{1}".format(
- value, urllib.urlencode({
- 'action': 'update',
- 'parameter': value
- }))
- """)
- llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
- reformatted_code = reformatter.Reformat(llines)
- self.assertCodeEqual(expected_formatted_code, reformatted_code)
- llines = yapf_test_helper.ParseAndUnwrap(reformatted_code)
- reformatted_code = reformatter.Reformat(llines)
- self.assertCodeEqual(expected_formatted_code, reformatted_code)
- class TestsForSpacesInsideBrackets(yapf_test_helper.YAPFTest):
- """Test the SPACE_INSIDE_BRACKETS style option."""
- unformatted_code = textwrap.dedent("""\
- foo()
- foo(1)
- foo(1,2)
- foo((1,))
- foo((1, 2))
- foo((1, 2,))
- foo(bar['baz'][0])
- set1 = {1, 2, 3}
- dict1 = {1: 1, foo: 2, 3: bar}
- dict2 = {
- 1: 1,
- foo: 2,
- 3: bar,
- }
- dict3[3][1][get_index(*args,**kwargs)]
- dict4[3][1][get_index(**kwargs)]
- x = dict5[4](foo(*args))
- a = list1[:]
- b = list2[slice_start:]
- c = list3[slice_start:slice_end]
- d = list4[slice_start:slice_end:]
- e = list5[slice_start:slice_end:slice_step]
- # Print gets special handling
- print(set2)
- compound = ((10+3)/(5-2**(6+x)))
- string_idx = "mystring"[3]
- """)
- def testEnabled(self):
- style.SetGlobalStyle(
- style.CreateStyleFromConfig('{space_inside_brackets: True}'))
- expected_formatted_code = textwrap.dedent("""\
- foo()
- foo( 1 )
- foo( 1, 2 )
- foo( ( 1, ) )
- foo( ( 1, 2 ) )
- foo( (
- 1,
- 2,
- ) )
- foo( bar[ 'baz' ][ 0 ] )
- set1 = { 1, 2, 3 }
- dict1 = { 1: 1, foo: 2, 3: bar }
- dict2 = {
- 1: 1,
- foo: 2,
- 3: bar,
- }
- dict3[ 3 ][ 1 ][ get_index( *args, **kwargs ) ]
- dict4[ 3 ][ 1 ][ get_index( **kwargs ) ]
- x = dict5[ 4 ]( foo( *args ) )
- a = list1[ : ]
- b = list2[ slice_start: ]
- c = list3[ slice_start:slice_end ]
- d = list4[ slice_start:slice_end: ]
- e = list5[ slice_start:slice_end:slice_step ]
- # Print gets special handling
- print( set2 )
- compound = ( ( 10 + 3 ) / ( 5 - 2**( 6 + x ) ) )
- string_idx = "mystring"[ 3 ]
- """)
- llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testDefault(self):
- style.SetGlobalStyle(style.CreatePEP8Style())
- expected_formatted_code = textwrap.dedent("""\
- foo()
- foo(1)
- foo(1, 2)
- foo((1, ))
- foo((1, 2))
- foo((
- 1,
- 2,
- ))
- foo(bar['baz'][0])
- set1 = {1, 2, 3}
- dict1 = {1: 1, foo: 2, 3: bar}
- dict2 = {
- 1: 1,
- foo: 2,
- 3: bar,
- }
- dict3[3][1][get_index(*args, **kwargs)]
- dict4[3][1][get_index(**kwargs)]
- x = dict5[4](foo(*args))
- a = list1[:]
- b = list2[slice_start:]
- c = list3[slice_start:slice_end]
- d = list4[slice_start:slice_end:]
- e = list5[slice_start:slice_end:slice_step]
- # Print gets special handling
- print(set2)
- compound = ((10 + 3) / (5 - 2**(6 + x)))
- string_idx = "mystring"[3]
- """)
- llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- class TestsForSpacesAroundSubscriptColon(yapf_test_helper.YAPFTest):
- """Test the SPACES_AROUND_SUBSCRIPT_COLON style option."""
- unformatted_code = textwrap.dedent("""\
- a = list1[ : ]
- b = list2[ slice_start: ]
- c = list3[ slice_start:slice_end ]
- d = list4[ slice_start:slice_end: ]
- e = list5[ slice_start:slice_end:slice_step ]
- a1 = list1[ : ]
- b1 = list2[ 1: ]
- c1 = list3[ 1:20 ]
- d1 = list4[ 1:20: ]
- e1 = list5[ 1:20:3 ]
- """)
- def testEnabled(self):
- style.SetGlobalStyle(
- style.CreateStyleFromConfig('{spaces_around_subscript_colon: True}'))
- expected_formatted_code = textwrap.dedent("""\
- a = list1[:]
- b = list2[slice_start :]
- c = list3[slice_start : slice_end]
- d = list4[slice_start : slice_end :]
- e = list5[slice_start : slice_end : slice_step]
- a1 = list1[:]
- b1 = list2[1 :]
- c1 = list3[1 : 20]
- d1 = list4[1 : 20 :]
- e1 = list5[1 : 20 : 3]
- """)
- llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testWithSpaceInsideBrackets(self):
- style.SetGlobalStyle(
- style.CreateStyleFromConfig('{'
- 'spaces_around_subscript_colon: true, '
- 'space_inside_brackets: true,'
- '}'))
- expected_formatted_code = textwrap.dedent("""\
- a = list1[ : ]
- b = list2[ slice_start : ]
- c = list3[ slice_start : slice_end ]
- d = list4[ slice_start : slice_end : ]
- e = list5[ slice_start : slice_end : slice_step ]
- a1 = list1[ : ]
- b1 = list2[ 1 : ]
- c1 = list3[ 1 : 20 ]
- d1 = list4[ 1 : 20 : ]
- e1 = list5[ 1 : 20 : 3 ]
- """)
- llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- def testDefault(self):
- style.SetGlobalStyle(style.CreatePEP8Style())
- expected_formatted_code = textwrap.dedent("""\
- a = list1[:]
- b = list2[slice_start:]
- c = list3[slice_start:slice_end]
- d = list4[slice_start:slice_end:]
- e = list5[slice_start:slice_end:slice_step]
- a1 = list1[:]
- b1 = list2[1:]
- c1 = list3[1:20]
- d1 = list4[1:20:]
- e1 = list5[1:20:3]
- """)
- llines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code)
- self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
- if __name__ == '__main__':
- unittest.main()
|