Add tests for stdin, --style-help and --version.
Increases test coverage.
...because context managers.
diff --git a/yapftests/main_test.py b/yapftests/main_test.py
index 2a19bd6..4175de6 100644
--- a/yapftests/main_test.py
+++ b/yapftests/main_test.py
@@ -14,9 +14,43 @@
# limitations under the License.
"""Tests for yapf.__init__.main."""
+from contextlib import contextmanager
+import sys
import unittest
import yapf
+try:
+ from StringIO import StringIO
+except ImportError: # Python 3
+ # Note: io.StringIO is different in Python 2, so try for python 2 first.
+ from io import StringIO
+
+@contextmanager
+def captured_output():
+ new_out, new_err = StringIO(), StringIO()
+ old_out, old_err = sys.stdout, sys.stderr
+ try:
+ sys.stdout, sys.stderr = new_out, new_err
+ yield sys.stdout, sys.stderr
+ finally:
+ sys.stdout, sys.stderr = old_out, old_err
+
+@contextmanager
+def patch_input(code):
+ "Monkey patch code as raw_input."
+ def lines():
+ for line in code.splitlines():
+ yield line
+ raise EOFError()
+ def patch_raw_input(lines=lines()):
+ return next(lines)
+ try:
+ raw_input = yapf.py3compat.raw_input
+ yapf.py3compat.raw_input = patch_raw_input
+ yield
+ finally:
+ yapf.py3compat.raw_input = raw_input
+
class MainTest(unittest.TestCase):
@@ -24,3 +58,44 @@
with self.assertRaisesRegexp(yapf.YapfError,
'did not match any python files'):
yapf.main(['yapf', 'foo.c'])
+
+ def testEchoInput(self):
+ code = "a = 1\nb = 2\n"
+ with patch_input(code):
+ with captured_output() as (out, err):
+ ret = yapf.main([])
+ self.assertEqual(ret, 0)
+ self.assertEqual(out.getvalue(), code)
+
+ def testEchoInputWithStyle(self):
+ code = "def f(a = 1):\n return 2*a\n"
+ chromium_code = "def f(a=1):\n return 2 * a\n"
+ with patch_input(code):
+ with captured_output() as (out, err):
+ ret = yapf.main(['-', '--style=chromium'])
+ self.assertEqual(ret, 0)
+ self.assertEqual(out.getvalue(), chromium_code)
+
+
+ def testEchoBadInput(self):
+ bad_syntax = " a = 1\n"
+ with patch_input(bad_syntax):
+ with captured_output() as (out, err):
+ with self.assertRaisesRegexp(SyntaxError, "unexpected indent"):
+ ret = yapf.main([])
+
+ def testHelp(self):
+ with captured_output() as (out, err):
+ ret = yapf.main(['-', '--style-help', '--style=pep8'])
+ self.assertEqual(ret, 0)
+ help_message = out.getvalue()
+ self.assertIn("INDENT_WIDTH=4", help_message)
+ self.assertIn("The number of spaces required before a trailing comment.",
+ help_message)
+
+ def testVersion(self):
+ with captured_output() as (out, err):
+ ret = yapf.main(['-', '--version'])
+ self.assertEqual(ret, 0)
+ version = 'yapf {}\n'.format(yapf.__version__)
+ self.assertEqual(version, out.getvalue())