main_test.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tests for yapf.__init__.main."""
  16. import sys
  17. import unittest
  18. from contextlib import contextmanager
  19. from io import StringIO
  20. import yapf
  21. from yapftests import yapf_test_helper
  22. class IO(object):
  23. """IO is a thin wrapper around StringIO.
  24. This is strictly to wrap the Python 3 StringIO object so that it can supply a
  25. "buffer" attribute.
  26. """
  27. class Buffer(object):
  28. def __init__(self):
  29. self.string_io = StringIO()
  30. def write(self, s):
  31. if isinstance(s, bytes):
  32. s = str(s, 'utf-8')
  33. self.string_io.write(s)
  34. def getvalue(self):
  35. return self.string_io.getvalue()
  36. def __init__(self):
  37. self.buffer = self.Buffer()
  38. def write(self, s):
  39. self.buffer.write(s)
  40. def getvalue(self):
  41. return self.buffer.getvalue()
  42. @contextmanager
  43. def captured_output():
  44. new_out, new_err = IO(), IO()
  45. old_out, old_err = sys.stdout, sys.stderr
  46. try:
  47. sys.stdout, sys.stderr = new_out, new_err
  48. yield sys.stdout, sys.stderr
  49. finally:
  50. sys.stdout, sys.stderr = old_out, old_err
  51. @contextmanager
  52. def patched_input(code):
  53. """Monkey patch code as though it were coming from stdin."""
  54. def lines():
  55. for line in code.splitlines():
  56. yield line
  57. raise EOFError()
  58. def patch_raw_input(lines=lines()):
  59. return next(lines)
  60. try:
  61. orig_raw_import = yapf._raw_input
  62. yapf._raw_input = patch_raw_input
  63. yield
  64. finally:
  65. yapf._raw_input = orig_raw_import
  66. class RunMainTest(yapf_test_helper.YAPFTest):
  67. def testShouldHandleYapfError(self):
  68. """run_main should handle YapfError and sys.exit(1)."""
  69. expected_message = 'yapf: input filenames did not match any python files\n'
  70. sys.argv = ['yapf', 'foo.c']
  71. with captured_output() as (out, err):
  72. with self.assertRaises(SystemExit):
  73. yapf.run_main()
  74. self.assertEqual(out.getvalue(), '')
  75. self.assertEqual(err.getvalue(), expected_message)
  76. class MainTest(yapf_test_helper.YAPFTest):
  77. def testNoPythonFilesMatched(self):
  78. with self.assertRaisesRegex(yapf.errors.YapfError,
  79. 'did not match any python files'):
  80. yapf.main(['yapf', 'foo.c'])
  81. def testEchoInput(self):
  82. code = 'a = 1\nb = 2\n'
  83. with patched_input(code):
  84. with captured_output() as (out, _):
  85. ret = yapf.main([])
  86. self.assertEqual(ret, 0)
  87. self.assertEqual(out.getvalue(), code)
  88. def testEchoInputWithStyle(self):
  89. code = 'def f(a = 1\n\n):\n return 2*a\n'
  90. yapf_code = 'def f(a=1):\n return 2 * a\n'
  91. with patched_input(code):
  92. with captured_output() as (out, _):
  93. ret = yapf.main(['-', '--style=yapf'])
  94. self.assertEqual(ret, 0)
  95. self.assertEqual(out.getvalue(), yapf_code)
  96. def testEchoBadInput(self):
  97. bad_syntax = ' a = 1\n'
  98. with patched_input(bad_syntax):
  99. with captured_output() as (_, _):
  100. with self.assertRaisesRegex(yapf.errors.YapfError, 'unexpected indent'):
  101. yapf.main([])
  102. def testHelp(self):
  103. with captured_output() as (out, _):
  104. ret = yapf.main(['-', '--style-help', '--style=pep8'])
  105. self.assertEqual(ret, 0)
  106. help_message = out.getvalue()
  107. self.assertIn('indent_width=4', help_message)
  108. self.assertIn('The number of spaces required before a trailing comment.',
  109. help_message)