Python test.support.captured_stdout() Examples

The following are 30 code examples of test.support.captured_stdout(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module test.support , or try the search function .
Example #1
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_listen_config_10_ok(self):
        with support.captured_stdout() as output:
            self.setup_via_listener(json.dumps(self.config10))
            logger = logging.getLogger("compiler.parser")
            logger.warning(self.next_message())
            logger = logging.getLogger('compiler')
            #Not output, because filtered
            logger.warning(self.next_message())
            logger = logging.getLogger('compiler.lexer')
            #Not output, because filtered
            logger.warning(self.next_message())
            logger = logging.getLogger("compiler.parser.codegen")
            #Output, as not filtered
            logger.error(self.next_message())
            self.assert_log_lines([
                ('WARNING', '1'),
                ('ERROR', '4'),
            ], stream=output) 
Example #2
Source File: test_core.py    From Imogen with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_config0_using_cp_ok(self):
        # A simple config file which overrides the default settings.
        with support.captured_stdout() as output:
            file = io.StringIO(textwrap.dedent(self.config0))
            cp = configparser.ConfigParser()
            cp.read_file(file)
            logging.config.fileConfig(cp)
            logger = logging.getLogger()
            # Won't output anything
            logger.info(self.next_message())
            # Outputs a message
            logger.error(self.next_message())
            self.assert_log_lines([
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example #4
Source File: test_core.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: test_smtpd.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_process_SMTPUTF8_message_with_enable_SMTPUTF8_true(self):
        server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0),
                                       enable_SMTPUTF8=True)
        conn, addr = server.accept()
        channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True)
        with support.captured_stdout() as s:
            self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n',
                           enable_SMTPUTF8=True)
        stdout = s.getvalue()
        self.assertEqual(stdout, textwrap.dedent("""\
             ---------- MESSAGE FOLLOWS ----------
             mail options: ['BODY=8BITMIME', 'SMTPUTF8']
             b'From: test'
             b'X-Peer: peer-address'
             b''
             b'h\\xc3\\xa9llo\\xff'
             ------------ END MESSAGE ------------
             """)) 
Example #6
Source File: test_smtpd.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_process_message_with_enable_SMTPUTF8_true(self):
        server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0),
                                       enable_SMTPUTF8=True)
        conn, addr = server.accept()
        channel = smtpd.SMTPChannel(server, conn, addr, enable_SMTPUTF8=True)
        with support.captured_stdout() as s:
            self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n')
        stdout = s.getvalue()
        self.assertEqual(stdout, textwrap.dedent("""\
             ---------- MESSAGE FOLLOWS ----------
             b'From: test'
             b'X-Peer: peer-address'
             b''
             b'h\\xc3\\xa9llo\\xff'
             ------------ END MESSAGE ------------
             """)) 
Example #7
Source File: test_smtpd.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_process_message_with_decode_data_false(self):
        server = smtpd.DebuggingServer((support.HOST, 0), ('b', 0),
                                       decode_data=False)
        conn, addr = server.accept()
        channel = smtpd.SMTPChannel(server, conn, addr, decode_data=False)
        with support.captured_stdout() as s:
            self.send_data(channel, b'From: test\n\nh\xc3\xa9llo\xff\n')
        stdout = s.getvalue()
        self.assertEqual(stdout, textwrap.dedent("""\
             ---------- MESSAGE FOLLOWS ----------
             b'From: test'
             b'X-Peer: peer-address'
             b''
             b'h\\xc3\\xa9llo\\xff'
             ------------ END MESSAGE ------------
             """)) 
Example #8
Source File: test_loader.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_lacking_parent(self):
        with util.uncache('__phello__', '__phello__.spam'), \
             captured_stdout() as stdout:
            with warnings.catch_warnings():
                warnings.simplefilter('ignore', DeprecationWarning)
                module = self.machinery.FrozenImporter.load_module('__phello__.spam')
            check = {'__name__': '__phello__.spam',
                    '__package__': '__phello__',
                    '__loader__': self.machinery.FrozenImporter,
                    }
            for attr, value in check.items():
                attr_value = getattr(module, attr)
                self.assertEqual(attr_value, value,
                                 "for __phello__.spam.%s, %r != %r" %
                                 (attr, attr_value, value))
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')
            self.assertFalse(hasattr(module, '__file__')) 
Example #9
Source File: test_print.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def check(self, expected, args,
              sep=NotDefined, end=NotDefined, file=NotDefined):
        # Capture sys.stdout in a StringIO.  Call print with args,
        # and with sep, end, and file, if they're defined.  Result
        # must match expected.

        # Look up the actual function to call, based on if sep, end,
        # and file are defined.
        fn = dispatch[(sep is not NotDefined,
                       end is not NotDefined,
                       file is not NotDefined)]

        with support.captured_stdout() as t:
            fn(args, sep, end, file)

        self.assertEqual(t.getvalue(), expected) 
Example #10
Source File: test_loader.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_package(self):
        with util.uncache('__phello__'),  captured_stdout() as stdout:
            with warnings.catch_warnings():
                warnings.simplefilter('ignore', DeprecationWarning)
                module = self.machinery.FrozenImporter.load_module('__phello__')
            check = {'__name__': '__phello__',
                     '__package__': '__phello__',
                     '__path__': [],
                     '__loader__': self.machinery.FrozenImporter,
                     }
            for attr, value in check.items():
                attr_value = getattr(module, attr)
                self.assertEqual(attr_value, value,
                                 "for __phello__.%s, %r != %r" %
                                 (attr, attr_value, value))
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')
            self.assertFalse(hasattr(module, '__file__')) 
Example #11
Source File: test_trace.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_issue9936(self):
        tracer = trace.Trace(trace=0, count=1)
        modname = 'test.tracedmodules.testmod'
        # Ensure that the module is executed in import
        if modname in sys.modules:
            del sys.modules[modname]
        cmd = ("import test.tracedmodules.testmod as t;"
               "t.func(0); t.func2();")
        with captured_stdout() as stdout:
            self._coverage(tracer, cmd)
        stdout.seek(0)
        stdout.readline()
        coverage = {}
        for line in stdout:
            lines, cov, module = line.split()[:3]
            coverage[module] = (int(lines), int(cov[:-1]))
        # XXX This is needed to run regrtest.py as a script
        modname = trace._fullmodname(sys.modules[modname].__file__)
        self.assertIn(modname, coverage)
        self.assertEqual(coverage[modname], (5, 100))

### Tests that don't mess with sys.settrace and can be traced
### themselves TODO: Skip tests that do mess with sys.settrace when
### regrtest is invoked with -T option. 
Example #12
Source File: test_xmlrpc.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_cgi_get(self):
        with support.EnvironmentVarGuard() as env:
            env['REQUEST_METHOD'] = 'GET'
            # if the method is GET and no request_text is given, it runs handle_get
            # get sysout output
            with captured_stdout(encoding=self.cgi.encoding) as data_out:
                self.cgi.handle_request()

            # parse Status header
            data_out.seek(0)
            handle = data_out.read()
            status = handle.split()[1]
            message = ' '.join(handle.split()[2:4])

            self.assertEqual(status, '400')
            self.assertEqual(message, 'Bad Request') 
Example #13
Source File: test_print.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def check(self, expected, args,
              sep=NotDefined, end=NotDefined, file=NotDefined):
        # Capture sys.stdout in a StringIO.  Call print with args,
        # and with sep, end, and file, if they're defined.  Result
        # must match expected.

        # Look up the actual function to call, based on if sep, end,
        # and file are defined.
        fn = dispatch[(sep is not NotDefined,
                       end is not NotDefined,
                       file is not NotDefined)]

        with support.captured_stdout() as t:
            fn(args, sep, end, file)

        self.assertEqual(t.getvalue(), expected) 
Example #14
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_config_10_ok(self):
        with support.captured_stdout() as output:
            self.apply_config(self.config10)
            logger = logging.getLogger("compiler.parser")
            logger.warning(self.next_message())
            logger = logging.getLogger('compiler')
            #Not output, because filtered
            logger.warning(self.next_message())
            logger = logging.getLogger('compiler.lexer')
            #Not output, because filtered
            logger.warning(self.next_message())
            logger = logging.getLogger("compiler.parser.codegen")
            #Output, as not filtered
            logger.error(self.next_message())
            self.assert_log_lines([
                ('WARNING', '1'),
                ('ERROR', '4'),
            ], stream=output) 
Example #15
Source File: test_trace.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_issue9936(self):
        tracer = trace.Trace(trace=0, count=1)
        modname = 'test.tracedmodules.testmod'
        # Ensure that the module is executed in import
        if modname in sys.modules:
            del sys.modules[modname]
        cmd = ("import test.tracedmodules.testmod as t;"
               "t.func(0); t.func2();")
        with captured_stdout() as stdout:
            self._coverage(tracer, cmd)
        stdout.seek(0)
        stdout.readline()
        coverage = {}
        for line in stdout:
            lines, cov, module = line.split()[:3]
            coverage[module] = (int(lines), int(cov[:-1]))
        # XXX This is needed to run regrtest.py as a script
        modname = trace._fullmodname(sys.modules[modname].__file__)
        self.assertIn(modname, coverage)
        self.assertEqual(coverage[modname], (5, 100))

### Tests that don't mess with sys.settrace and can be traced
### themselves TODO: Skip tests that do mess with sys.settrace when
### regrtest is invoked with -T option. 
Example #16
Source File: test_core.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #17
Source File: test_loader.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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)>") 
Example #18
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #19
Source File: test_support.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_captured_stdout(self):
        with support.captured_stdout() as stdout:
            print("hello")
        self.assertEqual(stdout.getvalue(), "hello\n") 
Example #20
Source File: test_dis.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #21
Source File: test_filelist.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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 
Example #22
Source File: test_sdist.py    From Imogen with MIT License 5 votes vote down vote up
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) 
Example #23
Source File: test_grep.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #24
Source File: test_loader.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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') 
Example #25
Source File: test_logging.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_stringtemplatestyle(self):
        with support.captured_stdout() as output:
            logging.basicConfig(stream=sys.stdout, style="$")
            logging.error("Log an error")
            sys.stdout.seek(0)
            self.assertEqual(output.getvalue().strip(),
                "ERROR:root:Log an error") 
Example #26
Source File: test_loader.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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') 
Example #27
Source File: test_xml_etree.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bug_xmltoolkitX1(self):
        # dump() doesn't flush the output buffer

        tree = ET.XML("<doc><table><tbody/></table></doc>")
        with support.captured_stdout() as stdout:
            ET.dump(tree)
            self.assertEqual(stdout.getvalue(), '<doc><table><tbody /></table></doc>\n') 
Example #28
Source File: test_xmlrpc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def captured_stdout(encoding='utf-8'):
    """A variation on support.captured_stdout() which gives a text stream
    having a `buffer` attribute.
    """
    import io
    orig_stdout = sys.stdout
    sys.stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding)
    try:
        yield sys.stdout
    finally:
        sys.stdout = orig_stdout 
Example #29
Source File: test_xmlrpc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_cgi_xmlrpc_response(self):
        data = """<?xml version='1.0'?>
        <methodCall>
            <methodName>test_method</methodName>
            <params>
                <param>
                    <value><string>foo</string></value>
                </param>
                <param>
                    <value><string>bar</string></value>
                </param>
            </params>
        </methodCall>
        """

        with support.EnvironmentVarGuard() as env, \
             captured_stdout(encoding=self.cgi.encoding) as data_out, \
             support.captured_stdin() as data_in:
            data_in.write(data)
            data_in.seek(0)
            env['CONTENT_LENGTH'] = str(len(data))
            self.cgi.handle_request()
        data_out.seek(0)

        # will respond exception, if so, our goal is achieved ;)
        handle = data_out.read()

        # start with 44th char so as not to get http header, we just
        # need only xml
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])

        # Also test the content-length returned  by handle_request
        # Using the same test method inorder to avoid all the datapassing
        # boilerplate code.
        # Test for bug: http://bugs.python.org/issue5040

        content = handle[handle.find("<?xml"):]

        self.assertEqual(
            int(re.search('Content-Length: (\d+)', handle).group(1)),
            len(content)) 
Example #30
Source File: test_loader.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_module(self):
        with util.uncache('__hello__'), captured_stdout() as stdout:
            with warnings.catch_warnings():
                warnings.simplefilter('ignore', DeprecationWarning)
                module = self.machinery.FrozenImporter.load_module('__hello__')
            check = {'__name__': '__hello__',
                    '__package__': '',
                    '__loader__': self.machinery.FrozenImporter,
                    }
            for attr, value in check.items():
                self.assertEqual(getattr(module, attr), value)
            self.assertEqual(stdout.getvalue(), 'Hello world!\n')
            self.assertFalse(hasattr(module, '__file__'))