Example #1
0
    def testFormatFileLinesSelection(self):
        unformatted_code = textwrap.dedent(u"""\
        if a:    b

        if f:    g

        if h:    i
        """)
        expected_formatted_code_lines1and2 = textwrap.dedent(u"""\
        if a: b

        if f:    g

        if h:    i
        """)
        expected_formatted_code_lines3 = textwrap.dedent(u"""\
        if a:    b

        if f: g

        if h:    i
        """)
        with utils.TempFileContents(self.test_tmpdir,
                                    unformatted_code) as filepath:
            formatted_code, _, _ = yapf_api.FormatFile(filepath,
                                                       style_config='pep8',
                                                       lines=[(1, 2)])
            self.assertCodeEqual(expected_formatted_code_lines1and2,
                                 formatted_code)
            formatted_code, _, _ = yapf_api.FormatFile(filepath,
                                                       style_config='pep8',
                                                       lines=[(3, 3)])
            self.assertCodeEqual(expected_formatted_code_lines3,
                                 formatted_code)
Example #2
0
    def testUseTabsContinuationAlignStyleVAlignRight(self):
        unformatted_code = """\
def foo_function(arg1, arg2, arg3):
  return ['hello', 'world',]
"""
        expected_formatted_code = """\
def foo_function(arg1, arg2,
					arg3):
	return [
			'hello',
			'world',
	]
"""
        style_contents = u"""\
[style]
based_on_style = chromium
USE_TABS = true
COLUMN_LIMIT=32
INDENT_WIDTH=4
CONTINUATION_INDENT_WIDTH=8
CONTINUATION_ALIGN_STYLE = valign-right
"""
        with utils.TempFileContents(self.test_tmpdir,
                                    style_contents) as stylepath:
            self.assertYapfReformats(
                unformatted_code,
                expected_formatted_code,
                extra_options=['--style={0}'.format(stylepath)])
Example #3
0
 def testDisabledSemiColonSeparatedStatements(self):
   code = textwrap.dedent(u"""\
       # yapf: disable
       if True: a ; b
       """)
   with utils.TempFileContents(self.test_tmpdir, code) as filepath:
     formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8')
     self.assertCodeEqual(code, formatted_code)
Example #4
0
 def testFormatFileDiff(self):
   unformatted_code = textwrap.dedent(u"""\
       if True:
        pass
       """)
   with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath:
     diff, _, _ = yapf_api.FormatFile(filepath, print_diff=True)
     self.assertTrue(u'+  pass' in diff)
Example #5
0
    def testDisablePartOfMultilineComment(self):
        unformatted_code = textwrap.dedent(u"""\
        if a:    b

        # This is a multiline comment that disables YAPF.
        # yapf: disable
        if f:    g
        # yapf: enable
        # This is a multiline comment that enables YAPF.

        if h:    i
        """)

        expected_formatted_code = textwrap.dedent(u"""\
        if a: b

        # This is a multiline comment that disables YAPF.
        # yapf: disable
        if f:    g
        # yapf: enable
        # This is a multiline comment that enables YAPF.

        if h: i
        """)
        with utils.TempFileContents(self.test_tmpdir,
                                    unformatted_code) as filepath:
            formatted_code, _, _ = yapf_api.FormatFile(filepath,
                                                       style_config='pep8')
            self.assertCodeEqual(expected_formatted_code, formatted_code)

        code = textwrap.dedent(u"""\
      def foo_function():
          # some comment
          # yapf: disable

          foo(
          bar,
          baz
          )

          # yapf: enable
      """)
        with utils.TempFileContents(self.test_tmpdir, code) as filepath:
            formatted_code, _, _ = yapf_api.FormatFile(filepath,
                                                       style_config='pep8')
            self.assertCodeEqual(code, formatted_code)
Example #6
0
 def testDefaultBasedOnStyle(self):
     cfg = textwrap.dedent(u'''\
     [style]
     continuation_indent_width = 20
     ''')
     with utils.TempFileContents(self.test_tmpdir, cfg) as filepath:
         cfg = style.CreateStyleFromConfig(filepath)
         self.assertTrue(_LooksLikePEP8Style(cfg))
         self.assertEqual(cfg['CONTINUATION_INDENT_WIDTH'], 20)
Example #7
0
 def testErrorNoStyleSection(self):
     cfg = textwrap.dedent(u'''\
     [s]
     indent_width=2
     ''')
     with utils.TempFileContents(self.test_tmpdir, cfg) as filepath:
         with self.assertRaisesRegexp(style.StyleConfigError,
                                      'Unable to find section'):
             style.CreateStyleFromConfig(filepath)
Example #8
0
 def testDisabledHorizontalFormattingOnNewLine(self):
   code = textwrap.dedent(u"""\
       # yapf: disable
       a = [
       1]
       # yapf: enable
       """)
   with utils.TempFileContents(self.test_tmpdir, code) as filepath:
     formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8')
     self.assertCodeEqual(code, formatted_code)
Example #9
0
 def testUnicodeEncodingPipedToFile(self):
   unformatted_code = textwrap.dedent(u"""\
       def foo():
           print('⇒')
       """)
   with utils.NamedTempFile(
       dirname=self.test_tmpdir, suffix='.py') as (out, _):
     with utils.TempFileContents(
         self.test_tmpdir, unformatted_code, suffix='.py') as filepath:
       subprocess.check_call(YAPF_BINARY + ['--diff', filepath], stdout=out)
Example #10
0
 def testErrorUnknownStyleOption(self):
     cfg = textwrap.dedent(u'''\
     [style]
     indent_width=2
     hummus=2
     ''')
     with utils.TempFileContents(self.test_tmpdir, cfg) as filepath:
         with self.assertRaisesRegexp(style.StyleConfigError,
                                      'Unknown style option'):
             style.CreateStyleFromConfig(filepath)
Example #11
0
 def testInPlaceReformattingEmpty(self):
   unformatted_code = u''
   expected_formatted_code = u''
   with utils.TempFileContents(
       self.test_tmpdir, unformatted_code, suffix='.py') as filepath:
     p = subprocess.Popen(YAPF_BINARY + ['--in-place', filepath])
     p.wait()
     with io.open(filepath, mode='r', encoding='utf-8', newline='') as fd:
       reformatted_code = fd.read()
   self.assertEqual(reformatted_code, expected_formatted_code)
Example #12
0
 def testStringListOptionValue(self):
     cfg = textwrap.dedent(u'''\
     [style]
     based_on_style = pep8
     I18N_FUNCTION_CALL = N_, V_, T_
     ''')
     with utils.TempFileContents(self.test_tmpdir, cfg) as filepath:
         cfg = style.CreateStyleFromConfig(filepath)
         self.assertTrue(_LooksLikePEP8Style(cfg))
         self.assertEqual(cfg['I18N_FUNCTION_CALL'], ['N_', 'V_', 'T_'])
Example #13
0
 def testCommentsUnformatted(self):
   code = textwrap.dedent(u"""\
       foo = [# A list of things
              # bork
           'one',
           # quark
           'two'] # yapf: disable
       """)
   with utils.TempFileContents(self.test_tmpdir, code) as filepath:
     formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8')
     self.assertCodeEqual(code, formatted_code)
Example #14
0
 def testBoolOptionValue(self):
     cfg = textwrap.dedent(u'''\
     [style]
     based_on_style = pep8
     SPLIT_BEFORE_NAMED_ASSIGNS=False
     split_before_logical_operator = true
     ''')
     with utils.TempFileContents(self.test_tmpdir, cfg) as filepath:
         cfg = style.CreateStyleFromConfig(filepath)
         self.assertTrue(_LooksLikePEP8Style(cfg))
         self.assertEqual(cfg['SPLIT_BEFORE_NAMED_ASSIGNS'], False)
         self.assertEqual(cfg['SPLIT_BEFORE_LOGICAL_OPERATOR'], True)
Example #15
0
  def testEncodingVerification(self):
    unformatted_code = textwrap.dedent(u"""\
        '''The module docstring.'''
        # -*- coding: utf-8 -*-
        def f():
            x = 37
        """)

    with utils.NamedTempFile(
        suffix='.py', dirname=self.test_tmpdir) as (out, _):
      with utils.TempFileContents(
          self.test_tmpdir, unformatted_code, suffix='.py') as filepath:
        subprocess.check_call(YAPF_BINARY + ['--diff', filepath], stdout=out)
Example #16
0
  def testEncodingVerification(self):
    unformatted_code = textwrap.dedent(u"""\
        '''The module docstring.'''
        # -*- coding: utf-8 -*-
        def f():
            x = 37
        """)

    with utils.NamedTempFile(
        suffix='.py', dirname=self.test_tmpdir) as (out, _):
      with utils.TempFileContents(
          self.test_tmpdir, unformatted_code, suffix='.py') as filepath:
        try:
          subprocess.check_call(YAPF_BINARY + ['--diff', filepath], stdout=out)
        except subprocess.CalledProcessError as e:
          self.assertEqual(e.returncode, 1)  # Indicates the text changed.
Example #17
0
 def testInPlaceReformatting(self):
   unformatted_code = textwrap.dedent(u"""\
       def foo():
         x = 37
       """)
   expected_formatted_code = textwrap.dedent("""\
       def foo():
           x = 37
       """)
   with utils.TempFileContents(
       self.test_tmpdir, unformatted_code, suffix='.py') as filepath:
     p = subprocess.Popen(YAPF_BINARY + ['--in-place', filepath])
     p.wait()
     with io.open(filepath, mode='r', newline='') as fd:
       reformatted_code = fd.read()
   self.assertEqual(reformatted_code, expected_formatted_code)
Example #18
0
 def testSemicolonStatementsDisabled(self):
   unformatted_code = textwrap.dedent(u"""\
       def f():
         x = y + 42 ; z = n * 42  # yapf: disable
         if True: a += 1 ; b += 1; c += 1
       """)
   expected_formatted_code = textwrap.dedent(u"""\
       def f():
           x = y + 42 ; z = n * 42  # yapf: disable
           if True:
               a += 1
               b += 1
               c += 1
       """)
   with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath:
     formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8')
     self.assertCodeEqual(expected_formatted_code, formatted_code)
Example #19
0
  def testFormatFileInPlace(self):
    unformatted_code = u'True==False\n'
    formatted_code = u'True == False\n'
    with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath:
      result, _, _ = yapf_api.FormatFile(filepath, in_place=True)
      self.assertEqual(result, None)
      with open(filepath) as fd:
        if sys.version_info[0] <= 2:
          self.assertCodeEqual(formatted_code, fd.read().decode('ascii'))
        else:
          self.assertCodeEqual(formatted_code, fd.read())

      self.assertRaises(
          ValueError,
          yapf_api.FormatFile,
          filepath,
          in_place=True,
          print_diff=True)
Example #20
0
 def testSetCustomStyleBasedOnChromium(self):
     unformatted_code = textwrap.dedent("""\
     def foo(): # trail
         x = 37
     """)
     expected_formatted_code = textwrap.dedent("""\
     def foo():    # trail
       x = 37
     """)
     style_file = textwrap.dedent(u'''\
     [style]
     based_on_style = chromium
     SPACES_BEFORE_COMMENT = 4
     ''')
     with utils.TempFileContents(self.test_tmpdir, style_file) as stylepath:
         self.assertYapfReformats(
             unformatted_code,
             expected_formatted_code,
             extra_options=['--style={0}'.format(stylepath)])
Example #21
0
    def testDisabledWithPrecedingText(self):
        code = textwrap.dedent(u"""\
        # TODO(fix formatting): yapf: disable

        A = [
            {
                "aaaaaaaaaaaaaaaaaaa": '''
        bbbbbbbbbbb: "ccccccccccc"
        dddddddddddddd: 1
        eeeeeeee: 0
        ffffffffff: "ggggggg"
        ''',
            },
        ]
        """)
        with utils.TempFileContents(self.test_tmpdir, code) as filepath:
            formatted_code, _, _ = yapf_api.FormatFile(filepath,
                                                       style_config='chromium')
            self.assertCodeEqual(code, formatted_code)
Example #22
0
    def testDisabledMultilineStringInDictionary(self):
        code = textwrap.dedent(u"""\
        # yapf: disable

        A = [
            {
                "aaaaaaaaaaaaaaaaaaa": '''
        bbbbbbbbbbb: "ccccccccccc"
        dddddddddddddd: 1
        eeeeeeee: 0
        ffffffffff: "ggggggg"
        ''',
            },
        ]
        """)
        with utils.TempFileContents(self.test_tmpdir, code) as filepath:
            formatted_code, _, _ = yapf_api.FormatFile(filepath,
                                                       style_config='chromium')
            self.assertCodeEqual(code, formatted_code)
Example #23
0
  def testFormatFile(self):
    unformatted_code = textwrap.dedent(u"""\
        if True:
         pass
        """)
    expected_formatted_code_pep8 = textwrap.dedent(u"""\
        if True:
            pass
        """)
    expected_formatted_code_chromium = textwrap.dedent(u"""\
        if True:
          pass
        """)
    with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath:
      formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8')
      self.assertCodeEqual(expected_formatted_code_pep8, formatted_code)

      formatted_code, _, _ = yapf_api.FormatFile(
          filepath, style_config='chromium')
      self.assertCodeEqual(expected_formatted_code_chromium, formatted_code)
Example #24
0
  def testDisableLinesPattern(self):
    unformatted_code = textwrap.dedent(u"""\
        if a:    b

        # yapf: disable
        if f:    g

        if h:    i
        """)
    expected_formatted_code = textwrap.dedent(u"""\
        if a: b

        # yapf: disable
        if f:    g

        if h:    i
        """)
    with utils.TempFileContents(self.test_tmpdir, unformatted_code) as filepath:
      formatted_code, _, _ = yapf_api.FormatFile(filepath, style_config='pep8')
      self.assertCodeEqual(expected_formatted_code, formatted_code)
Example #25
0
 def testUseTabs(self):
   unformatted_code = textwrap.dedent("""\
       def foo_function():
        if True:
         pass
       """)
   expected_formatted_code = textwrap.dedent("""\
       def foo_function():
       	if True:
       		pass
       """)
   style_contents = textwrap.dedent(u'''\
       [style]
       based_on_style = chromium
       USE_TABS = true
       INDENT_WIDTH=1
       ''')
   with utils.TempFileContents(self.test_tmpdir, style_contents) as stylepath:
     self.assertYapfReformats(
         unformatted_code,
         expected_formatted_code,
         extra_options=['--style={0}'.format(stylepath)])
Example #26
0
    def testUseTabsWith(self):
        unformatted_code = """\
def f():
  return ['hello', 'world',]
"""
        expected_formatted_code = """\
def f():
	return [
	    'hello',
	    'world',
	]
"""
        style_contents = u"""\
[style]
based_on_style = chromium
USE_TABS = true
INDENT_WIDTH=1
"""
        with utils.TempFileContents(self.test_tmpdir,
                                    style_contents) as stylepath:
            self.assertYapfReformats(
                unformatted_code,
                expected_formatted_code,
                extra_options=['--style={0}'.format(stylepath)])
Example #27
0
 def testCRLFLineEnding(self):
     code = u'class _():\r\n  pass\r\n'
     with utils.TempFileContents(self.test_tmpdir, code) as filepath:
         formatted_code, _, _ = yapf_api.FormatFile(filepath,
                                                    style_config='chromium')
         self.assertCodeEqual(code, formatted_code)