def testNoSplitBeforeFirstArgumentStyle2(self): try: pep8_no_split_before_first = style.CreatePEP8Style() pep8_no_split_before_first['SPLIT_BEFORE_FIRST_ARGUMENT'] = False pep8_no_split_before_first['SPLIT_BEFORE_NAMED_ASSIGNS'] = True style.SetGlobalStyle(pep8_no_split_before_first) formatted_code = textwrap.dedent("""\ # Examples Issue#556 i_take_a_lot_of_params(arg1, param1=very_long_expression1(), param2=very_long_expression2(), param3=very_long_expression3(), param4=very_long_expression4()) # Examples Issue#590 plt.plot(numpy.linspace(0, 1, 10), numpy.linspace(0, 1, 10), marker="x", color="r") plt.plot(veryverylongvariablename, veryverylongvariablename, marker="x", color="r") """) uwlines = yapf_test_helper.ParseAndUnwrap(formatted_code) self.assertCodeEqual(formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style()) style.DEFAULT_STYLE = self.current_style
def testSetGlobalStyle(self): try: style.SetGlobalStyle(style.CreateChromiumStyle()) unformatted_code = textwrap.dedent(u"""\ for i in range(5): print('bar') """) expected_formatted_code = textwrap.dedent(u"""\ for i in range(5): print('bar') """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style()) style.DEFAULT_STYLE = self.current_style unformatted_code = textwrap.dedent(u"""\ for i in range(5): print('bar') """) expected_formatted_code = textwrap.dedent(u"""\ for i in range(5): print('bar') """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
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) """) 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) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())
def testSpaceBetweenColonAndElipses(self): style.SetGlobalStyle(style.CreatePEP8Style()) code = textwrap.dedent("""\ class MyClass(ABC): place: ... """) llines = yapf_test_helper.ParseAndUnwrap(code) self.assertCodeEqual(code, reformatter.Reformat(llines, verify=False))
def testOperatorStyle(self): try: sympy_style = style.CreatePEP8Style() sympy_style['NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS'] = \ style._StringSetConverter('*,/') style.SetGlobalStyle(sympy_style) unformatted_code = textwrap.dedent("""\ a = 1+2 * 3 - 4 / 5 """) expected_formatted_code = textwrap.dedent("""\ a = 1 + 2*3 - 4/5 """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style()) style.DEFAULT_STYLE = self.current_style
def testOperatorPrecedenceStyle(self): try: pep8_with_precedence = style.CreatePEP8Style() pep8_with_precedence['ARITHMETIC_PRECEDENCE_INDICATION'] = True style.SetGlobalStyle(pep8_with_precedence) unformatted_code = textwrap.dedent("""\ 1+2 (1 + 2) * (3 - (4 / 5)) a = 1 * 2 + 3 / 4 b = 1 / 2 - 3 * 4 c = (1 + 2) * (3 - 4) d = (1 - 2) / (3 + 4) e = 1 * 2 - 3 f = 1 + 2 + 3 + 4 g = 1 * 2 * 3 * 4 h = 1 + 2 - 3 + 4 i = 1 * 2 / 3 * 4 j = (1 * 2 - 3) + 4 k = (1 * 2 * 3) + (4 * 5 * 6 * 7 * 8) """) expected_formatted_code = textwrap.dedent("""\ 1 + 2 (1+2) * (3 - (4/5)) a = 1*2 + 3/4 b = 1/2 - 3*4 c = (1+2) * (3-4) d = (1-2) / (3+4) e = 1*2 - 3 f = 1 + 2 + 3 + 4 g = 1 * 2 * 3 * 4 h = 1 + 2 - 3 + 4 i = 1 * 2 / 3 * 4 j = (1*2 - 3) + 4 k = (1*2*3) + (4*5*6*7*8) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style()) style.DEFAULT_STYLE = self.current_style
def testSpaceBetweenDictColonAndElipses(self): style.SetGlobalStyle(style.CreatePEP8Style()) unformatted_code = textwrap.dedent("""\ {0:"...", 1:...} """) expected_formatted_code = textwrap.dedent("""\ {0: "...", 1: ...} """) llines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
def testNoSplitBeforeFirstArgumentStyle1(self): try: pep8_no_split_before_first = style.CreatePEP8Style() pep8_no_split_before_first['SPLIT_BEFORE_FIRST_ARGUMENT'] = False pep8_no_split_before_first['SPLIT_BEFORE_NAMED_ASSIGNS'] = False style.SetGlobalStyle(pep8_no_split_before_first) formatted_code = textwrap.dedent("""\ # Example from in-code MustSplit comments foo = outer_function_call(fitting_inner_function_call(inner_arg1, inner_arg2), outer_arg1, outer_arg2) foo = outer_function_call( not_fitting_inner_function_call(inner_arg1, inner_arg2), outer_arg1, outer_arg2) # Examples Issue#424 a_super_long_version_of_print(argument1, argument2, argument3, argument4, argument5, argument6, argument7) CREDS_FILE = os.path.join(os.path.expanduser('~'), 'apis/super-secret-admin-creds.json') # Examples Issue#556 i_take_a_lot_of_params(arg1, param1=very_long_expression1(), param2=very_long_expression2(), param3=very_long_expression3(), param4=very_long_expression4()) # Examples Issue#590 plt.plot(numpy.linspace(0, 1, 10), numpy.linspace(0, 1, 10), marker="x", color="r") plt.plot(veryverylongvariablename, veryverylongvariablename, marker="x", color="r") """) uwlines = yapf_test_helper.ParseAndUnwrap(formatted_code) self.assertCodeEqual(formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style()) style.DEFAULT_STYLE = self.current_style
def testB19372573(self): code = textwrap.dedent("""\ def f(): if a: return 42 while True: if b: continue if c: break return 0 """) uwlines = yapf_test_helper.ParseAndUnwrap(code) try: style.SetGlobalStyle(style.CreatePEP8Style()) self.assertCodeEqual(code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreateChromiumStyle())
def testNoSpacesAroundPowerOparator(self): try: style.SetGlobalStyle( style.CreateStyleFromConfig( '{based_on_style: pep8, SPACES_AROUND_POWER_OPERATOR: True}')) unformatted_code = textwrap.dedent("""\ a**b """) expected_formatted_code = textwrap.dedent("""\ a ** b """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())
def testSpacesAroundDefaultOrNamedAssign(self): try: style.SetGlobalStyle( style.CreateStyleFromConfig( '{based_on_style: pep8, ' 'SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN: True}')) unformatted_code = textwrap.dedent("""\ f(a=5) """) expected_formatted_code = textwrap.dedent("""\ f(a = 5) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())
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] """) uwlines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
def testB20016122(self): try: style.SetGlobalStyle( style.CreateStyleFromConfig( '{based_on_style: pep8, split_penalty_import_names: 35}')) unformatted_code = textwrap.dedent("""\ from a_very_long_or_indented_module_name_yada_yada import (long_argument_1, long_argument_2) """) expected_formatted_code = textwrap.dedent("""\ from a_very_long_or_indented_module_name_yada_yada import ( long_argument_1, long_argument_2) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style()) try: style.SetGlobalStyle( style.CreateStyleFromConfig( '{based_on_style: chromium, ' 'split_before_logical_operator: True}')) code = textwrap.dedent("""\ class foo(): def __eq__(self, other): return (isinstance(other, type(self)) and self.xxxxxxxxxxx == other.xxxxxxxxxxx and self.xxxxxxxx == other.xxxxxxxx and self.aaaaaaaaaaaa == other.aaaaaaaaaaaa and self.bbbbbbbbbbb == other.bbbbbbbbbbb and self.ccccccccccccccccc == other.ccccccccccccccccc and self.ddddddddddddddddddddddd == other.ddddddddddddddddddddddd and self.eeeeeeeeeeee == other.eeeeeeeeeeee and self.ffffffffffffff == other.time_completed and self.gggggg == other.gggggg and self.hhh == other.hhh and len(self.iiiiiiii) == len(other.iiiiiiii) and all(jjjjjjj in other.iiiiiiii for jjjjjjj in self.iiiiiiii)) """) uwlines = yapf_test_helper.ParseAndUnwrap(code) self.assertCodeEqual(code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreateChromiumStyle())
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)) """ expected_formatted_code = """\ def _(): raise ValueError('This is a long message that ends with an argument: ' + str(42)) """ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())
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) """) 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) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())
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 ''' uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())
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] """) uwlines = yapf_test_helper.ParseAndUnwrap(self.unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
def _OwnStyle(): my_style = style.CreatePEP8Style() my_style['INDENT_WIDTH'] = 3 my_style['CONTINUATION_INDENT_WIDTH'] = 3 return my_style
def setUpClass(cls): # pylint: disable=g-missing-super-call style.SetGlobalStyle(style.CreatePEP8Style())
def setUpClass(cls): # pylint: disable=g-missing-super-call cls.test_tmpdir = tempfile.mkdtemp() style.SetGlobalStyle(style.CreatePEP8Style())
def setUpClass(cls): style.SetGlobalStyle(style.CreatePEP8Style())
def setUpClass(cls): cls.test_tmpdir = tempfile.mkdtemp() style.SetGlobalStyle(style.CreatePEP8Style())
def testSplittingArguments(self): if sys.version_info[1] < 5: return unformatted_code = """\ async def open_file(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): pass async def run_sync_in_worker_thread(sync_fn, *args, cancellable=False, limiter=None): pass def open_file(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): pass def run_sync_in_worker_thread(sync_fn, *args, cancellable=False, limiter=None): pass """ expected_formatted_code = """\ async def open_file( file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None ): pass async def run_sync_in_worker_thread( sync_fn, *args, cancellable=False, limiter=None ): pass def open_file( file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None ): pass def run_sync_in_worker_thread(sync_fn, *args, cancellable=False, limiter=None): pass """ try: style.SetGlobalStyle( style.CreateStyleFromConfig( '{based_on_style: pep8, ' 'dedent_closing_brackets: true, ' 'coalesce_brackets: false, ' 'space_between_ending_comma_and_closing_bracket: false, ' 'split_arguments_when_comma_terminated: true, ' 'split_before_first_argument: true}')) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())
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."), } """) 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." ), } """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) unformatted_code = textwrap.dedent("""\ X = {'a': 1, 'b': 2, 'key': this_is_a_function_call_that_goes_over_the_column_limit_im_pretty_sure()} """) 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() } """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) unformatted_code = textwrap.dedent("""\ attrs = { 'category': category, 'role': forms.ModelChoiceField(label=_("Role"), required=False, queryset=category_roles, initial=selected_role, empty_label=_("No access"),), } """) 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"), ), } """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) 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."), ) """) 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." ), ) """) uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code) self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines)) finally: style.SetGlobalStyle(style.CreatePEP8Style())