Пример #1
0
    def test_frozen(self):
        with captured_stdout() as stdout:
            try:
                import __hello__
            except ImportError as x:
                self.fail("import __hello__ failed:" + str(x))
            self.assertEqual(__hello__.initialized, True)
            expect = set(self.module_attrs)
            expect.add('initialized')
            self.assertEqual(set(dir(__hello__)), expect)
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')

        with captured_stdout() as stdout:
            try:
                import __phello__
            except ImportError as x:
                self.fail("import __phello__ failed:" + str(x))
            self.assertEqual(__phello__.initialized, True)
            expect = set(self.package_attrs)
            expect.add('initialized')
            if not "__phello__.spam" in sys.modules:
                self.assertEqual(set(dir(__phello__)), expect)
            else:
                expect.add('spam')
                self.assertEqual(set(dir(__phello__)), expect)
            self.assertEqual(__phello__.__path__, [__phello__.__name__])
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')

        with captured_stdout() as stdout:
            try:
                import __phello__.spam
            except ImportError as x:
                self.fail("import __phello__.spam failed:" + str(x))
            self.assertEqual(__phello__.spam.initialized, True)
            spam_expect = set(self.module_attrs)
            spam_expect.add('initialized')
            self.assertEqual(set(dir(__phello__.spam)), spam_expect)
            phello_expect = set(self.package_attrs)
            phello_expect.add('initialized')
            phello_expect.add('spam')
            self.assertEqual(set(dir(__phello__)), phello_expect)
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')

        try:
            import __phello__.foo
        except ImportError:
            pass
        else:
            self.fail("import __phello__.foo should have failed")

            try:
                import __phello__.foo
            except ImportError:
                pass
            else:
                self.fail("import __phello__.foo should have failed")

        del sys.modules['__hello__']
        del sys.modules['__phello__']
        del sys.modules['__phello__.spam']
Пример #2
0
    def test_debug_print(self):
        file_list = FileList()
        with captured_stdout() as stdout:
            file_list.debug_print('xxx')
        self.assertEqual(stdout.getvalue(), '')

        debug.DEBUG = True
        try:
            with captured_stdout() as stdout:
                file_list.debug_print('xxx')
            self.assertEqual(stdout.getvalue(), 'xxx\n')
        finally:
            debug.DEBUG = False
Пример #3
0
    def test_frozen(self):
        with captured_stdout() as stdout:
            try:
                import __hello__
            except ImportError as x:
                self.fail("import __hello__ failed:" + str(x))
            self.assertEqual(__hello__.initialized, True)
            self.assertEqual(len(dir(__hello__)), 7, dir(__hello__))
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')

        with captured_stdout() as stdout:
            try:
                import __phello__
            except ImportError as x:
                self.fail("import __phello__ failed:" + str(x))
            self.assertEqual(__phello__.initialized, True)
            if not "__phello__.spam" in sys.modules:
                self.assertEqual(len(dir(__phello__)), 8, dir(__phello__))
            else:
                self.assertEqual(len(dir(__phello__)), 9, dir(__phello__))
            self.assertEqual(__phello__.__path__, [__phello__.__name__])
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')

        with captured_stdout() as stdout:
            try:
                import __phello__.spam
            except ImportError as x:
                self.fail("import __phello__.spam failed:" + str(x))
            self.assertEqual(__phello__.spam.initialized, True)
            self.assertEqual(len(dir(__phello__.spam)), 7)
            self.assertEqual(len(dir(__phello__)), 9)
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')

        try:
            import __phello__.foo
        except ImportError:
            pass
        else:
            self.fail("import __phello__.foo should have failed")

            try:
                import __phello__.foo
            except ImportError:
                pass
            else:
                self.fail("import __phello__.foo should have failed")

        del sys.modules['__hello__']
        del sys.modules['__phello__']
        del sys.modules['__phello__.spam']
Пример #4
0
    def test_debug_print(self):
        cmd = self.cmd
        with captured_stdout() as stdout:
            cmd.debug_print('xxx')
        stdout.seek(0)
        self.assertEqual(stdout.read(), '')

        debug.DEBUG = True
        try:
            with captured_stdout() as stdout:
                cmd.debug_print('xxx')
            stdout.seek(0)
            self.assertEqual(stdout.read(), 'xxx\n')
        finally:
            debug.DEBUG = False
Пример #5
0
 def test_frozen(self):
     name = '__hello__'
     if name in sys.modules:
         del sys.modules[name]
     with captured_stdout() as out:
         import __hello__
     self.assertEqual(out.getvalue(), 'Hello world!\n')
Пример #6
0
 def test_help(self):
     for opt in '-h', '--help':
         with self.subTest(opt=opt):
             with support.captured_stdout() as out, \
                  self.assertRaises(SystemExit):
                 libregrtest._parse_args([opt])
             self.assertIn('Run Python regression tests.', out.getvalue())
Пример #7
0
 def test_module_reuse(self):
     with util.uncache('__hello__'), captured_stdout() as stdout:
         module1 = machinery.FrozenImporter.load_module('__hello__')
         module2 = machinery.FrozenImporter.load_module('__hello__')
         self.assertTrue(module1 is module2)
         self.assertEqual(stdout.getvalue(),
                          'Hello world!\nHello world!\n')
Пример #8
0
 def test_resolve_false(self):
     # Issue #23008: pydoc enum.{,Int}Enum failed
     # because bool(enum.Enum) is False.
     with captured_stdout() as help_io:
         pydoc.help('enum.Enum')
     helptext = help_io.getvalue()
     self.assertIn('class Enum', helptext)
Пример #9
0
 def run_test(self, leftovers=False, dump=False, verbose=False):
     """Parse the input buffer prepared through the 'add_' functions
     and compare the results to the expected output.  `leftovers`
     should be `True` if the input buffer is expected to have excess
     data in it.  If `dump` is `True`, the state of the mock socket
     will be dumped after parsing."""
     if verbose:
         print("Initial state of socket")
         self.sock.dump()
     self.expected_output.append("")
     with contextlib.ExitStack() as stack:
         for parse_error in self.expected_parse_errors:
             stack.enter_context(self.assertRaises(ParseError,
                                                   msg=parse_error))
         with support.captured_stdout() as stdout:
             mtapi = mtcmds.MTAPI(self.sock)
             mtapi()
             while mtapi.state != mtapi.read_sof:
                 mtapi()
     if dump:
         print("Final state of socket")
         self.sock.dump()
     if leftovers:
         self.assertFalse(self.sock.eof())
     else:
         self.assertTrue(self.sock.eof())
     if verbose:
         print("Parse output:")
         print(stdout.getvalue())
     actual_output = stdout.getvalue().split("\n")
     for (expected, actual) in zip(self.expected_output, actual_output):
         self.assertEqual(expected, actual)
Пример #10
0
 def report(self, pat):
     grep.engine._pat = pat
     with captured_stdout() as s:
         grep.grep_it(re.compile(pat), __file__)
     lines = s.getvalue().split('\n')
     lines.pop()  # remove bogus '' after last \n
     return lines
Пример #11
0
 def test_compile_dir_pathlike(self):
     self.assertFalse(os.path.isfile(self.bc_path))
     with support.captured_stdout() as stdout:
         compileall.compile_dir(pathlib.Path(self.directory))
     line = stdout.getvalue().splitlines()[0]
     self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
     self.assertTrue(os.path.isfile(self.bc_path))
Пример #12
0
 def test_compile_file_pathlike(self):
     self.assertFalse(os.path.isfile(self.bc_path))
     # we should also test the output
     with support.captured_stdout() as stdout:
         self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
     self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
     self.assertTrue(os.path.isfile(self.bc_path))
Пример #13
0
    def test_show_formats(self):
        with captured_stdout() as stdout:
            show_formats()

        # the output should be a header line + one line per format
        num_formats = len(ARCHIVE_FORMATS.keys())
        output = [line for line in stdout.getvalue().split("\n") if line.strip().startswith("--formats=")]
        self.assertEqual(len(output), num_formats)
Пример #14
0
 def test_repr(self):
     with support.captured_stdout() as template:
         A = namedtuple('A', 'x', verbose=True)
     self.assertEqual(repr(A(1)), 'A(x=1)')
     # repr should show the name of the subclass
     class B(A):
         pass
     self.assertEqual(repr(B(1)), 'B(x=1)')
Пример #15
0
 def test_repr(self):
     with support.captured_stdout() as template:
         A = recordclass('A', 'x')
     self.assertEqual(repr(A(1)), 'A(x=1)')
     # repr should show the name of the subclass
     class B(A):
         pass
     self.assertEqual(repr(B(1)), 'B(x=1)')
Пример #16
0
 def test_module(self):
     with util.uncache('__hello__'), captured_stdout() as stdout:
         module = machinery.FrozenImporter.load_module('__hello__')
         check = {'__name__': '__hello__', '__file__': '<frozen>',
                 '__package__': '', '__loader__': machinery.FrozenImporter}
         for attr, value in check.items():
             self.assertEqual(getattr(module, attr), value)
         self.assertEqual(stdout.getvalue(), 'Hello world!\n')
Пример #17
0
 def test_namedtuple_public_underscore(self):
     NT = namedtuple('NT', ['abc', 'def'], rename=True)
     with captured_stdout() as help_io:
         help(NT)
     helptext = help_io.getvalue()
     self.assertIn('_1', helptext)
     self.assertIn('_replace', helptext)
     self.assertIn('_asdict', helptext)
Пример #18
0
    def test_debug_mode(self):
        # this covers the code called when DEBUG is set
        sys.argv = ['setup.py', '--name']
        with captured_stdout() as stdout:
            distutils.core.setup(name='bar')
        stdout.seek(0)
        self.assertEqual(stdout.read(), 'bar\n')

        distutils.core.DEBUG = True
        try:
            with captured_stdout() as stdout:
                distutils.core.setup(name='bar')
        finally:
            distutils.core.DEBUG = False
        stdout.seek(0)
        wanted = "options (after parsing config files):\n"
        self.assertEqual(stdout.readlines()[0], wanted)
Пример #19
0
 def test_module_repr(self):
     with util.uncache('__hello__'), captured_stdout():
         with warnings.catch_warnings():
             warnings.simplefilter('ignore', DeprecationWarning)
             module = self.machinery.FrozenImporter.load_module('__hello__')
             repr_str = self.machinery.FrozenImporter.module_repr(module)
         self.assertEqual(repr_str,
                          "<module '__hello__' (frozen)>")
Пример #20
0
 def test_eval(self):
     with open(_fname + '.dir', 'w') as stream:
         stream.write("str(print('Hacked!')), 0\n")
     with support.captured_stdout() as stdout:
         with self.assertRaises(ValueError):
             with dumbdbm.open(_fname) as f:
                 pass
         self.assertEqual(stdout.getvalue(), '')
Пример #21
0
 def test_namedtuple_public_underscore(self):
     NT = namedtuple("NT", ["abc", "def"], rename=True)
     with captured_stdout() as help_io:
         pydoc.help(NT)
     helptext = help_io.getvalue()
     self.assertIn("_1", helptext)
     self.assertIn("_replace", helptext)
     self.assertIn("_asdict", helptext)
Пример #22
0
 def test_show_code(self):
     self.maxDiff = 1000
     for x, expected in self.test_pairs:
         with captured_stdout() as output:
             dis.show_code(x)
         self.assertRegex(output.getvalue(), expected+"\n")
         output = io.StringIO()
         dis.show_code(x, file=output)
         self.assertRegex(output.getvalue(), expected)
Пример #23
0
 def test_read_comm_kludge_compname_odd(self):
     b = b'FORM' + struct.pack('>L', 4) + b'AIFC'
     b += b'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0)
     b += b'NONE' + struct.pack('B', 3) + b'odd'
     b += b'SSND' + struct.pack('>L', 8) + b'\x00' * 8
     with captured_stdout() as s:
         f = aifc.open(io.BytesIO(b))
     self.assertEqual(s.getvalue(), 'Warning: bad COMM chunk size\n')
     self.assertEqual(f.getcompname(), b'odd')
Пример #24
0
 def test_module_reuse(self):
     with util.uncache('__hello__'), captured_stdout() as stdout:
         with warnings.catch_warnings():
             warnings.simplefilter('ignore', DeprecationWarning)
             module1 = self.machinery.FrozenImporter.load_module('__hello__')
             module2 = self.machinery.FrozenImporter.load_module('__hello__')
         self.assertIs(module1, module2)
         self.assertEqual(stdout.getvalue(),
                          'Hello world!\nHello world!\n')
Пример #25
0
 def test_get_code(self):
     # Make sure that the code object is good.
     name = '__hello__'
     with captured_stdout() as stdout:
         code = self.machinery.FrozenImporter.get_code(name)
         mod = types.ModuleType(name)
         exec(code, mod.__dict__)
         self.assertTrue(hasattr(mod, 'initialized'))
         self.assertEqual(stdout.getvalue(), 'Hello world!\n')
 def test_replace_paths(self):
     old_path = os.path.join(TEST_DIR, 'a', 'module.py')
     new_path = os.path.join(TEST_DIR, 'a', 'spam.py')
     with support.captured_stdout() as output:
         self._do_test(maybe_test, debug=2,
                       replace_paths=[(old_path, new_path)])
     output = output.getvalue()
     expected = "co_filename %r changed to %r" % (old_path, new_path)
     self.assertIn(expected, output)
Пример #27
0
 def test_coverage(self):
     tracer = trace.Trace(trace=0, count=1)
     with captured_stdout() as stdout:
         self._coverage(tracer)
     stdout = stdout.getvalue()
     self.assertTrue("pprint.py" in stdout)
     self.assertTrue("case.py" in stdout)   # from unittest
     files = os.listdir(TESTFN)
     self.assertTrue("pprint.cover" in files)
     self.assertTrue("unittest.case.cover" in files)
Пример #28
0
 def test_debug_mode(self):
     # this covers the code called when DEBUG is set
     old_logs_len = len(self.logs)
     install_module.DEBUG = True
     try:
         with captured_stdout():
             self.test_record()
     finally:
         install_module.DEBUG = False
     self.assertTrue(len(self.logs) > old_logs_len)
Пример #29
0
    def test_scaffolding(self):
        # test repr on special values
        self.assertEqual(repr(clinic.unspecified), '<Unspecified>')
        self.assertEqual(repr(clinic.NULL), '<Null>')

        # test that fail fails
        with support.captured_stdout() as stdout:
            with self.assertRaises(SystemExit):
                clinic.fail('The igloos are melting!', filename='clown.txt', line_number=69)
        self.assertEqual(stdout.getvalue(), 'Error in file "clown.txt" on line 69:\nThe igloos are melting!\n')
Пример #30
0
 def test_coverage_ignore(self):
     # Ignore all files, nothing should be traced nor printed
     libpath = os.path.normpath(os.path.dirname(os.__file__))
     # sys.prefix does not work when running from a checkout
     tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix, libpath], trace=0, count=1)
     with captured_stdout() as stdout:
         self._coverage(tracer)
     if os.path.exists(TESTFN):
         files = os.listdir(TESTFN)
         self.assertEqual(files, ["_importlib.cover"])  # Ignore __import__
Пример #31
0
 def msg(self, msg, *args):
     with support.captured_stdout() as out:
         telnetlib.Telnet.msg(self, msg, *args)
     self._messages += out.getvalue()
     return
Пример #32
0
    def test_reversic__menu(self):
        app = Reversic()
        app.players_info = {'black': 'BLACK', 'white': 'WHITE'}
        app._get_board_size = lambda: 26
        app._get_player = lambda x: x

        # play
        app.state = None
        with captured_stdout() as stdout:
            with captured_stdin() as stdin:
                stdin.write('\n')
                stdin.seek(0)
                app._Reversic__menu()

        lines = stdout.getvalue().splitlines()

        def check_header(self, lines):
            self.assertEqual(lines[0], 'press any key')
            self.assertEqual(lines[1], '-----------------------------')
            self.assertEqual(lines[2], ' enter  : start game')
            self.assertEqual(lines[3], ' s      : change board size')
            self.assertEqual(lines[4], ' b      : change black player')
            self.assertEqual(lines[5], ' w      : change white player')
            self.assertEqual(lines[6], ' q      : quit')
            self.assertEqual(lines[7], '-----------------------------')

        check_header(self, lines)
        self.assertEqual(lines[8], '>> ')
        with self.assertRaises(IndexError):
            print(lines[9])

        self.assertEqual(app.state, Reversic.PLAY)

        # size
        app.state = None
        with captured_stdout() as stdout:
            with captured_stdin() as stdin:
                stdin.write('s')
                stdin.seek(0)
                app._Reversic__menu()

        lines = stdout.getvalue().splitlines()
        check_header(self, lines)
        self.assertEqual(lines[8], '>> ')
        with self.assertRaises(IndexError):
            print(lines[9])

        self.assertEqual(app.board_size, 26)
        self.assertEqual(app.state, Reversic.START)

        # black
        app.state = None
        with captured_stdout() as stdout:
            with captured_stdin() as stdin:
                stdin.write('b')
                stdin.seek(0)
                app._Reversic__menu()

        lines = stdout.getvalue().splitlines()
        check_header(self, lines)
        self.assertEqual(lines[8], '>> ')
        with self.assertRaises(IndexError):
            print(lines[9])

        self.assertEqual(app.player_names['black'], 'BLACK')
        self.assertEqual(app.state, Reversic.START)

        # white
        app.state = None
        with captured_stdout() as stdout:
            with captured_stdin() as stdin:
                stdin.write('w')
                stdin.seek(0)
                app._Reversic__menu()

        lines = stdout.getvalue().splitlines()
        check_header(self, lines)
        self.assertEqual(lines[8], '>> ')
        with self.assertRaises(IndexError):
            print(lines[9])

        self.assertEqual(app.player_names['white'], 'WHITE')
        self.assertEqual(app.state, Reversic.START)

        # invalid keyword & quit
        app.state = None
        ret = False
        with captured_stdout() as stdout:
            with captured_stdin() as stdin:
                stdin.write('invalid keyword\nq')
                stdin.seek(0)
                ret = app._Reversic__menu()

        lines = stdout.getvalue().splitlines()
        check_header(self, lines)
        self.assertEqual(lines[8], '>> >> See you!')
        with self.assertRaises(IndexError):
            print(lines[9])

        self.assertTrue(ret)
        self.assertIsNone(app.state)
Пример #33
0
 def f(ime):
     with captured_stdout() as stdout:
         izpis_imen_v_rodbini(ime)
     return stdout.getvalue().splitlines()
Пример #34
0
 def test_100より多い場合はプリントしない(self):
     with captured_stdout() as stdout:
         execute(count=101)
         self.lines = stdout.getvalue().splitlines()
     self.assertEqual(f"回数は{MAX_COUNT}までです", self.lines[0])
Пример #35
0
 def test_printer(self):
     with support.captured_stdout() as stdout:
         queryset = worklogdb.name_query('chico buarque')
         worklogdb.printer(queryset, paginated=False)
         assert "Chico" in stdout.getvalue()
Пример #36
0
 def _assert_report(self, dircmp_report, expected_report_lines):
     with support.captured_stdout() as stdout:
         dircmp_report()
         report_lines = stdout.getvalue().strip().split('\n')
         self.assertEqual(report_lines, expected_report_lines)
Пример #37
0
 def test_format(self):
     with support.captured_stdout() as out:
         calendar.format(["1", "2", "3"], colwidth=3, spacing=1)
         self.assertEqual(out.getvalue().strip(), "1   2   3")
Пример #38
0
    def test_reversi_setting_changed(self):
        class TestWindow:
            def __init__(self):
                class Menu:
                    def __init__(self):
                        class Event:
                            def is_set(self):
                                return False

                            def clear(self):
                                print('clear')

                        self.event = Event()
                        self.size = 8
                        self.black_player = 'BLACK2'
                        self.white_player = 'WHITE2'
                        self.assist = True
                        self.language = 'Japanese'

                self.menu = Menu()

                self.size = 4
                self.player = {'black': 'BLACK', 'white': 'WHITE'}
                self.assist = False
                self.language = 'English'

        app = Reversi()
        app.window = TestWindow()

        # return False
        with captured_stdout() as stdout:
            ret = app._setting_changed()

        lines = stdout.getvalue().splitlines()

        with self.assertRaises(IndexError):
            print(lines[0])

        self.assertEqual(app.window.size, 4)
        self.assertEqual(app.window.player['black'], 'BLACK')
        self.assertEqual(app.window.player['white'], 'WHITE')
        self.assertEqual(app.window.assist, False)
        self.assertEqual(app.window.language, 'English')
        self.assertEqual(ret, False)

        # return True
        app.window.menu.event.is_set = lambda: True

        with captured_stdout() as stdout:
            ret = app._setting_changed()

        lines = stdout.getvalue().splitlines()
        self.assertEqual(lines[0], 'clear')

        with self.assertRaises(IndexError):
            print(lines[1])

        self.assertEqual(app.window.size, 8)
        self.assertEqual(app.window.player['black'], 'BLACK2')
        self.assertEqual(app.window.player['white'], 'WHITE2')
        self.assertEqual(app.window.assist, True)
        self.assertEqual(app.window.language, 'Japanese')
        self.assertEqual(ret, True)
Пример #39
0
 def parse_function_should_fail(self, s):
     with support.captured_stdout() as stdout:
         with self.assertRaises(SystemExit):
             self.parse_function(s)
     return stdout.getvalue()
Пример #40
0
 def test_main(self):
     with captured_stdout() as output:
         _main()
     self.assertTrue(len(output.getvalue().split('\n')) > 0)
Пример #41
0
 def test_nested(self):
     with captured_stdout():
         f = outer()
     actual = dis.get_instructions(f, first_line=expected_f_line)
     self.assertEqual(list(actual), expected_opinfo_f)
Пример #42
0
 def run_with_capture(self, func, *args, **kwargs):
     with captured_stdout() as output:
         with captured_stderr() as error:
             func(*args, **kwargs)
     return output.getvalue(), error.getvalue()
Пример #43
0
 def test_module_repr_indirect(self):
     with util.uncache('__hello__'), captured_stdout():
         module = self.machinery.FrozenImporter.load_module('__hello__')
     self.assertEqual(repr(module), "<module '__hello__' (frozen)>")
Пример #44
0
 def test_captured_stdout(self):
     with support.captured_stdout() as stdout:
         print("hello")
     self.assertEqual(stdout.getvalue(), "hello\n")
Пример #45
0
 def setUp(self):
     with captured_stdout() as stdout:
         execute()
         self.lines = stdout.getvalue().splitlines()
Пример #46
0
 def test_main(self):
     # just making sure _main() runs and returns things in the stdout
     with captured_stdout() as output:
         _main()
     self.assertTrue(len(output.getvalue().split('\n')) > 0)
Пример #47
0
 def test_module_reuse(self):
     with util.uncache('__hello__'), captured_stdout() as stdout:
         module1 = machinery.FrozenImporter.load_module('__hello__')
         module2 = machinery.FrozenImporter.load_module('__hello__')
         self.assertIs(module1, module2)
         self.assertEqual(stdout.getvalue(), 'Hello world!\nHello world!\n')
 def test_prweek(self):
     with support.captured_stdout() as out:
         week = [(1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6)]
         calendar.TextCalendar().prweek(week, 1)
         self.assertEqual(out.getvalue().strip(), "1  2  3  4  5  6  7")
Пример #49
0
 def test_1から10まで数をプリントする(self):
     with captured_stdout() as stdout:
         execute(count=10)
         self.lines = stdout.getvalue().splitlines()
     self.assertNotIn("11", self.lines)
     self.assertEqual("Buzz", self.lines[10])
Пример #50
0
 def mimetypes_cmd(self, *args, **kwargs):
     support.patch(self, sys, "argv", [sys.executable, *args])
     with support.captured_stdout() as output:
         mimetypes._main()
         return output.getvalue().strip()
Пример #51
0
    def test_reversic_get_player(self):
        app = Reversic()
        test_players = {'Test1': None, 'Test2': None}

        # normal pattern
        for i in range(1, 3):
            with captured_stdout() as stdout:
                with captured_stdin() as stdin:
                    stdin.write(str(i))
                    stdin.seek(0)
                    ret = app._get_player(test_players)

            lines = stdout.getvalue().splitlines()
            self.assertEqual(lines[0], 'select number for player')
            self.assertEqual(lines[1], '-----------------------------')
            self.assertEqual(lines[2], '  1 : Test1')
            self.assertEqual(lines[3], '  2 : Test2')
            self.assertEqual(lines[4], '-----------------------------')
            self.assertEqual(lines[5], '>> ')
            with self.assertRaises(IndexError):
                print(lines[6])

            self.assertEqual(ret, list(test_players.keys())[i - 1])

        # illegal pattern
        for i in range(0, 4, 3):
            with captured_stdout() as stdout:
                with captured_stdin() as stdin:
                    stdin.write(str(i) + '\n' + str(1))
                    stdin.seek(0)
                    ret = app._get_player(test_players)

            lines = stdout.getvalue().splitlines()
            self.assertEqual(lines[0], 'select number for player')
            self.assertEqual(lines[1], '-----------------------------')
            self.assertEqual(lines[2], '  1 : Test1')
            self.assertEqual(lines[3], '  2 : Test2')
            self.assertEqual(lines[4], '-----------------------------')
            self.assertEqual(lines[5], '>> >> ')
            with self.assertRaises(IndexError):
                print(lines[6])

            self.assertEqual(ret, 'Test1')

        with captured_stdout() as stdout:
            with captured_stdin() as stdin:
                stdin.write('a\n08\n1\nあ\n' + str(2))
                stdin.seek(0)
                ret = app._get_player(test_players)

        lines = stdout.getvalue().splitlines()
        self.assertEqual(lines[0], 'select number for player')
        self.assertEqual(lines[1], '-----------------------------')
        self.assertEqual(lines[2], '  1 : Test1')
        self.assertEqual(lines[3], '  2 : Test2')
        self.assertEqual(lines[4], '-----------------------------')
        self.assertEqual(lines[5], '>> >> >> >> >> ')
        with self.assertRaises(IndexError):
            print(lines[6])

        self.assertEqual(ret, 'Test2')
Пример #52
0
    def test_reversi_demo_animation(self):
        class TestWindow:
            def __init__(self):
                class Board:
                    def __init__(self):
                        self.size = 8

                    def remove_disc(self, color, x, y):
                        print('remove_disc', color, x, y)

                    def put_disc(self, color, x, y):
                        print('put_disc', color, x, y)

                self.board = Board()

        app = Reversi(turn_disc_wait=0.001)
        app.window = TestWindow()

        # setting_changed Falase
        app._setting_changed = lambda: False
        with captured_stdout() as stdout:
            ret = app._demo_animation()

        lines = stdout.getvalue().splitlines()

        self.assertEqual(lines[0], 'remove_disc black 4 3')
        self.assertEqual(lines[1], 'put_disc turnblack 4 3')
        self.assertEqual(lines[2], 'remove_disc turnblack 4 3')
        self.assertEqual(lines[3], 'put_disc white 4 3')
        self.assertEqual(lines[4], 'remove_disc white 4 3')
        self.assertEqual(lines[5], 'put_disc turnwhite 4 3')
        self.assertEqual(lines[6], 'remove_disc turnwhite 4 3')
        self.assertEqual(lines[7], 'put_disc black 4 3')
        self.assertEqual(lines[8], 'remove_disc black 3 4')
        self.assertEqual(lines[9], 'put_disc turnblack 3 4')
        self.assertEqual(lines[10], 'remove_disc turnblack 3 4')
        self.assertEqual(lines[11], 'put_disc white 3 4')
        self.assertEqual(lines[12], 'remove_disc white 3 4')
        self.assertEqual(lines[13], 'put_disc turnwhite 3 4')
        self.assertEqual(lines[14], 'remove_disc turnwhite 3 4')
        self.assertEqual(lines[15], 'put_disc black 3 4')
        self.assertEqual(lines[16], 'remove_disc white 3 3')
        self.assertEqual(lines[17], 'put_disc turnwhite 3 3')
        self.assertEqual(lines[18], 'remove_disc turnwhite 3 3')
        self.assertEqual(lines[19], 'put_disc black 3 3')
        self.assertEqual(lines[20], 'remove_disc black 3 3')
        self.assertEqual(lines[21], 'put_disc turnblack 3 3')
        self.assertEqual(lines[22], 'remove_disc turnblack 3 3')
        self.assertEqual(lines[23], 'put_disc white 3 3')
        self.assertEqual(lines[24], 'remove_disc white 4 4')
        self.assertEqual(lines[25], 'put_disc turnwhite 4 4')
        self.assertEqual(lines[26], 'remove_disc turnwhite 4 4')
        self.assertEqual(lines[27], 'put_disc black 4 4')
        self.assertEqual(lines[28], 'remove_disc black 4 4')
        self.assertEqual(lines[29], 'put_disc turnblack 4 4')
        self.assertEqual(lines[30], 'remove_disc turnblack 4 4')
        self.assertEqual(lines[31], 'put_disc white 4 4')

        with self.assertRaises(IndexError):
            print(lines[32])

        self.assertEqual(ret, True)

        # setting_changed True
        app._setting_changed = lambda: True
        with captured_stdout() as stdout:
            ret = app._demo_animation()

        lines = stdout.getvalue().splitlines()

        with self.assertRaises(IndexError):
            print(lines[0])

        self.assertEqual(ret, False)
Пример #53
0
 def test_all_error(self):
     """test method for do_all method errors"""
     cli = self.create()
     with captured_stdout() as stdout, captured_stderr() as stderr:
         self.assertFalse(cli.onecmd("all PeterPans"))
         self.assertEqual(TestConsole.no_class, stdout.getvalue())
Пример #54
0
 def test_prmonth(self):
     with support.captured_stdout() as out:
         calendar.TextCalendar().prmonth(2004, 1)
         output = out.getvalue().strip()
         self.assertEqual(output, result_2004_01_text.strip())
Пример #55
0
 def test_empty(self):
     """test method for empty line"""
     cli = self.create()
     with captured_stdout() as stdout, captured_stderr() as stderr:
         self.assertFalse(cli.onecmd(""))
         self.assertEqual("", stdout.getvalue())
Пример #56
0
 def check_script_output(self, src, expected):
     with captured_stdout() as stdout:
         exec(src)
     out = stdout.getvalue().encode('latin1')
     self.assertEqual(out.rstrip(), expected)
Пример #57
0
 def test_show_code(self):
     self.maxDiff = 1000
     for x, expected in self.test_pairs:
         with captured_stdout() as output:
             dis.show_code(x)
         self.assertRegex(output.getvalue(), expected + "\n")
Пример #58
0
 def test_pryear(self):
     with support.captured_stdout() as out:
         calendar.TextCalendar().pryear(2004)
         self.assertEqual(out.getvalue(), result_2004_text)
Пример #59
0
 def test_doubly_nested(self):
     with captured_stdout():
         inner = outer()()
     actual = dis.get_instructions(inner, first_line=expected_inner_line)
     self.assertEqual(list(actual), expected_opinfo_inner)
Пример #60
0
    def test_reversi__play(self):
        class TestWindow:
            def __init__(self):
                class Board:
                    def __init__(self):
                        self.size = 4

                    def enable_moves(self, moves):
                        print('enable_moves', moves)

                    def disable_moves(self, moves):
                        print('disable_moves', moves)

                    def enable_move(self, x, y):
                        print('enable_move', x, y)

                    def disable_move(self, x, y):
                        print('disable_move', x, y)

                    def put_disc(self, color, x, y):
                        print('put_disc', color, x, y)

                    def turn_disc(self, color, captures):
                        print('put_disc', color, captures)

                class Menu:
                    def __init__(self):
                        class Event:
                            def is_set(self):
                                return False

                        self.event = Event()

                class Info:
                    def set_text(self, color, text, score):
                        print('set_text', color, text, score)

                    def set_turn_text_on(self, color):
                        print('set_turn_text_on', color)

                    def set_turn_text_off(self, color):
                        print('set_turn_text_off', color)

                    def set_move_text_on(self, color, x, y):
                        print('set_move_text_on', color, x, y)

                    def set_move_text_off(self, color):
                        print('set_move_text_off', color)

                    def set_win_text_on(self, color):
                        print('set_win_text_on', color)

                    def set_lose_text_on(self, color):
                        print('set_lose_text_on', color)

                self.board = Board()
                self.menu = Menu()
                self.player = {'black': 'WhiteWin', 'white': 'WhiteWin'}
                self.cputime = 0.1
                self.info = Info()

            def set_state(self, state):
                print(state)

        class WhiteWin(AbstractStrategy):
            def next_move(self, color, board):
                depth = board._black_score + board._white_score - 4
                move = None
                if depth == 0:
                    move = (1, 0)
                elif depth == 1:
                    move = (0, 0)
                elif depth == 2:
                    move = (0, 1)
                elif depth == 3:
                    move = (2, 0)
                elif depth == 4:
                    move = (3, 0)
                elif depth == 5:
                    move = (0, 2)
                elif depth == 6:
                    move = (0, 3)
                elif depth == 7:
                    move = (3, 2)
                elif depth == 8:
                    move = (2, 3)

                return move

        app = Reversi(sleep_time_play=0.001,
                      sleep_time_turn=0.001,
                      sleep_time_move=0.001)
        app.window = TestWindow()
        app.players_info = {'WhiteWin': WhiteWin()}

        with captured_stdout() as stdout:
            app._Reversi__play()

        lines = stdout.getvalue().splitlines()

        self.assertEqual(lines[0], 'disable')
        self.assertEqual(lines[1], 'set_text black score 2')
        self.assertEqual(lines[2], 'set_text white score 2')
        self.assertEqual(lines[3], 'set_turn_text_on black')
        self.assertEqual(lines[4],
                         'enable_moves [(1, 0), (0, 1), (3, 2), (2, 3)]')
        self.assertEqual(lines[5], 'set_turn_text_off black')
        self.assertEqual(lines[6], 'set_move_text_off black')
        self.assertEqual(lines[7], 'set_turn_text_off white')
        self.assertEqual(lines[8], 'set_move_text_off white')
        self.assertEqual(lines[9],
                         'disable_moves [(1, 0), (0, 1), (3, 2), (2, 3)]')
        self.assertEqual(lines[10], 'enable_move 1 0')
        self.assertEqual(lines[11], 'put_disc black 1 0')
        self.assertEqual(lines[12], 'set_move_text_on black b 1')
        self.assertEqual(lines[13], 'put_disc black [(1, 1)]')
        self.assertEqual(lines[14], 'set_text black score 4')
        self.assertEqual(lines[15], 'set_text white score 1')
        self.assertEqual(lines[16], 'set_turn_text_on white')
        self.assertEqual(lines[17], 'enable_moves [(0, 0), (2, 0), (0, 2)]')
        self.assertEqual(lines[18], 'set_turn_text_off black')
        self.assertEqual(lines[19], 'set_move_text_off black')
        self.assertEqual(lines[20], 'set_turn_text_off white')
        self.assertEqual(lines[21], 'set_move_text_off white')
        self.assertEqual(lines[22], 'disable_moves [(0, 0), (2, 0), (0, 2)]')
        self.assertEqual(lines[23], 'disable_move 1 0')
        self.assertEqual(lines[24], 'enable_move 0 0')
        self.assertEqual(lines[25], 'put_disc white 0 0')
        self.assertEqual(lines[26], 'set_move_text_on white a 1')
        self.assertEqual(lines[27], 'put_disc white [(1, 1)]')
        self.assertEqual(lines[28], 'set_text black score 3')
        self.assertEqual(lines[29], 'set_text white score 3')
        self.assertEqual(lines[30], 'set_turn_text_on black')
        self.assertEqual(lines[31], 'enable_moves [(0, 1), (3, 2), (2, 3)]')
        self.assertEqual(lines[32], 'set_turn_text_off black')
        self.assertEqual(lines[33], 'set_move_text_off black')
        self.assertEqual(lines[34], 'set_turn_text_off white')
        self.assertEqual(lines[35], 'set_move_text_off white')
        self.assertEqual(lines[36], 'disable_moves [(0, 1), (3, 2), (2, 3)]')
        self.assertEqual(lines[37], 'disable_move 0 0')
        self.assertEqual(lines[38], 'enable_move 0 1')
        self.assertEqual(lines[39], 'put_disc black 0 1')
        self.assertEqual(lines[40], 'set_move_text_on black a 2')
        self.assertEqual(lines[41], 'put_disc black [(1, 1)]')
        self.assertEqual(lines[42], 'set_text black score 5')
        self.assertEqual(lines[43], 'set_text white score 2')
        self.assertEqual(lines[44], 'set_turn_text_on white')
        self.assertEqual(lines[45], 'enable_moves [(2, 0), (0, 2)]')
        self.assertEqual(lines[46], 'set_turn_text_off black')
        self.assertEqual(lines[47], 'set_move_text_off black')
        self.assertEqual(lines[48], 'set_turn_text_off white')
        self.assertEqual(lines[49], 'set_move_text_off white')
        self.assertEqual(lines[50], 'disable_moves [(2, 0), (0, 2)]')
        self.assertEqual(lines[51], 'disable_move 0 1')
        self.assertEqual(lines[52], 'enable_move 2 0')
        self.assertEqual(lines[53], 'put_disc white 2 0')
        self.assertEqual(lines[54], 'set_move_text_on white c 1')
        self.assertEqual(lines[55], 'put_disc white [(1, 0), (2, 1)]')
        self.assertEqual(lines[56], 'set_text black score 3')
        self.assertEqual(lines[57], 'set_text white score 5')
        self.assertEqual(lines[58], 'set_turn_text_on black')
        self.assertEqual(lines[59],
                         'enable_moves [(3, 0), (3, 1), (3, 2), (3, 3)]')
        self.assertEqual(lines[60], 'set_turn_text_off black')
        self.assertEqual(lines[61], 'set_move_text_off black')
        self.assertEqual(lines[62], 'set_turn_text_off white')
        self.assertEqual(lines[63], 'set_move_text_off white')
        self.assertEqual(lines[64],
                         'disable_moves [(3, 0), (3, 1), (3, 2), (3, 3)]')
        self.assertEqual(lines[65], 'disable_move 2 0')
        self.assertEqual(lines[66], 'enable_move 3 0')
        self.assertEqual(lines[67], 'put_disc black 3 0')
        self.assertEqual(lines[68], 'set_move_text_on black d 1')
        self.assertEqual(lines[69], 'put_disc black [(2, 1)]')
        self.assertEqual(lines[70], 'set_text black score 5')
        self.assertEqual(lines[71], 'set_text white score 4')
        self.assertEqual(lines[72], 'set_turn_text_on white')
        self.assertEqual(lines[73], 'enable_moves [(0, 2), (3, 2), (1, 3)]')
        self.assertEqual(lines[74], 'set_turn_text_off black')
        self.assertEqual(lines[75], 'set_move_text_off black')
        self.assertEqual(lines[76], 'set_turn_text_off white')
        self.assertEqual(lines[77], 'set_move_text_off white')
        self.assertEqual(lines[78], 'disable_moves [(0, 2), (3, 2), (1, 3)]')
        self.assertEqual(lines[79], 'disable_move 3 0')
        self.assertEqual(lines[80], 'enable_move 0 2')
        self.assertEqual(lines[81], 'put_disc white 0 2')
        self.assertEqual(lines[82], 'set_move_text_on white a 3')
        self.assertEqual(lines[83], 'put_disc white [(0, 1), (1, 1), (1, 2)]')
        self.assertEqual(lines[84], 'set_text black score 2')
        self.assertEqual(lines[85], 'set_text white score 8')
        self.assertEqual(lines[86], 'set_turn_text_on black')
        self.assertEqual(lines[87], 'enable_moves [(0, 3), (2, 3)]')
        self.assertEqual(lines[88], 'set_turn_text_off black')
        self.assertEqual(lines[89], 'set_move_text_off black')
        self.assertEqual(lines[90], 'set_turn_text_off white')
        self.assertEqual(lines[91], 'set_move_text_off white')
        self.assertEqual(lines[92], 'disable_moves [(0, 3), (2, 3)]')
        self.assertEqual(lines[93], 'disable_move 0 2')
        self.assertEqual(lines[94], 'enable_move 0 3')
        self.assertEqual(lines[95], 'put_disc black 0 3')
        self.assertEqual(lines[96], 'set_move_text_on black a 4')
        self.assertEqual(lines[97], 'put_disc black [(1, 2)]')
        self.assertEqual(lines[98], 'set_text black score 4')
        self.assertEqual(lines[99], 'set_text white score 7')
        self.assertEqual(lines[100], 'set_turn_text_on white')
        self.assertEqual(lines[101],
                         'enable_moves [(3, 1), (3, 2), (1, 3), (2, 3)]')
        self.assertEqual(lines[102], 'set_turn_text_off black')
        self.assertEqual(lines[103], 'set_move_text_off black')
        self.assertEqual(lines[104], 'set_turn_text_off white')
        self.assertEqual(lines[105], 'set_move_text_off white')
        self.assertEqual(lines[106],
                         'disable_moves [(3, 1), (3, 2), (1, 3), (2, 3)]')
        self.assertEqual(lines[107], 'disable_move 0 3')
        self.assertEqual(lines[108], 'enable_move 3 2')
        self.assertEqual(lines[109], 'put_disc white 3 2')
        self.assertEqual(lines[110], 'set_move_text_on white d 3')
        self.assertEqual(lines[111], 'put_disc white [(2, 1)]')
        self.assertEqual(lines[112], 'set_text black score 3')
        self.assertEqual(lines[113], 'set_text white score 9')
        self.assertEqual(lines[114], 'set_turn_text_on white')
        self.assertEqual(lines[115], 'enable_moves [(1, 3), (2, 3)]')
        self.assertEqual(lines[116], 'set_turn_text_off black')
        self.assertEqual(lines[117], 'set_move_text_off black')
        self.assertEqual(lines[118], 'set_turn_text_off white')
        self.assertEqual(lines[119], 'set_move_text_off white')
        self.assertEqual(lines[120], 'disable_moves [(1, 3), (2, 3)]')
        self.assertEqual(lines[121], 'disable_move 3 2')
        self.assertEqual(lines[122], 'enable_move 2 3')
        self.assertEqual(lines[123], 'put_disc white 2 3')
        self.assertEqual(lines[124], 'set_move_text_on white c 4')
        self.assertEqual(lines[125], 'put_disc white [(1, 2)]')
        self.assertEqual(lines[126], 'set_text black score 2')
        self.assertEqual(lines[127], 'set_text white score 11')
        self.assertEqual(lines[128], 'set_win_text_on white')
        self.assertEqual(lines[129], 'set_lose_text_on black')

        with self.assertRaises(IndexError):
            print(lines[131])

        self.assertEqual(app.state, Reversi.END)