sys.stdout.getvalue

Here are the examples of the python api sys.stdout.getvalue taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: fabric
Source File: test_context_managers.py
View license
    @server()
    @mock_streams('both')
    def test_quiet_hides_all_output(self):
        # Sanity test - normally this is not empty
        run("ls /simple")
        ok_(sys.stdout.getvalue())
        # Reset
        sys.stdout = StringIO()
        # Real test
        with quiet():
            run("ls /simple")
        # Empty output
        ok_(not sys.stdout.getvalue())
        # Reset
        sys.stdout = StringIO()
        # Kwarg test
        run("ls /simple", quiet=True)
        ok_(not sys.stdout.getvalue())

Example 2

Project: vumi
Source File: test_vumi_list_messages.py
View license
    @inlineCallbacks
    def test_main(self):
        """
        The lister runs via `main()`.
        """
        msg_data = yield self.make_inbound("gingercookies", "12345")
        self.patch(sys, "stdout", StringIO())
        yield main(
            None, "name",
            "--batch", "gingercookies",
            "--direction", "inbound",
            "-b", self.riak_manager.bucket_prefix)
        self.assertEqual(
            sys.stdout.getvalue(),
            "%s\n" % (",".join(msg_data),))

Example 3

Project: unittest-xml-reporting
Source File: result.py
View license
    def _save_output_data(self):
        # Only try to get sys.stdout and sys.sterr as they not be
        # StringIO yet, e.g. when test fails during __call__
        try:
            self._stdout_data = sys.stdout.getvalue()
            self._stderr_data = sys.stderr.getvalue()
        except AttributeError:
            pass

Example 4

Project: guardonce
Source File: test_check.py
View license
def runCheckGuard(directory, exclusions=None):
	invokation = ['-r', directory]
	if exclusions is not None:
		invokation.append('--exclude=' + exclusions)
	checkguard.main(invokation)
	return Output(sys.stdout.getvalue(), sys.stderr.getvalue())

Example 5

Project: presto-admin
Source File: test_fabric_patches.py
View license
    def test_should_not_print_executing_line_for_singletons(self):
        """
        should not print "Executing" line for non-networked tasks
        """

        def task():
            pass
        with settings(hosts=[]):  # protect against really odd test bleed :(
            execute(task)
        self.assertEqual(sys.stdout.getvalue(), "")

Example 6

Project: pycodestyle
Source File: test_api.py
View license
    def test_styleguide_unmatched_triple_quotes(self):
        pycodestyle.register_check(DummyChecker, ['Z701'])
        lines = [
            'def foo():\n',
            '    """test docstring""\'\n',
        ]

        pep8style = pycodestyle.StyleGuide()
        pep8style.input_file('stdin', lines=lines)
        stdout = sys.stdout.getvalue()

        expected = 'stdin:2:5: E901 TokenError: EOF in multi-line string'
        self.assertTrue(expected in stdout)

Example 7

Project: django-extensions
Source File: test_runscript.py
View license
    def test_runs_appconfig(self):
        with self.modify_settings(INSTALLED_APPS={
            'append': 'tests.testapp.apps.TestAppConfig',
            'remove': 'tests.testapp',
        }):
            call_command('runscript', 'sample_script', verbosity=2)
            self.assertIn("Found script 'tests.testapp.scripts.sample_script'", sys.stdout.getvalue())
            self.assertIn("Running script 'tests.testapp.scripts.sample_script'", sys.stdout.getvalue())

Example 8

View license
    def test_runs(self):
        # lame test...does it run?
        n = Name(name='Gabriel')
        n.save()
        call_command('dumpscript', 'django_extensions')
        self.assertTrue('Gabriel' in sys.stdout.getvalue())

Example 9

Project: stor
Source File: test_cli.py
View license
    @mock.patch.object(S3Path, 'walkfiles', autospec=True)
    def test_walkfiles_s3(self, mock_walkfiles):
        mock_walkfiles.return_value = [
            's3://bucket/a/b.txt',
            's3://bucket/c.txt',
            's3://bucket/d.txt'
        ]
        self.parse_args('stor walkfiles -p=*.txt s3://bucket')
        self.assertEquals(sys.stdout.getvalue(),
                          's3://bucket/a/b.txt\n'
                          's3://bucket/c.txt\n'
                          's3://bucket/d.txt\n')
        mock_walkfiles.assert_called_once_with(S3Path('s3://bucket'), pattern='*.txt')

Example 10

Project: invoke
Source File: runners.py
View license
        @trap
        def honors_config(self):
            runner = self._runner(out='stuff', run={'hide': True})
            r = runner.run(_)
            eq_(r.stdout, 'stuff')
            eq_(sys.stdout.getvalue(), '')

Example 11

Project: mystic
Source File: test_solver_sanity.py
View license
def release_stdout(orig):
    "release stdout; return any trapped output as a string"
    out = sys.stdout.getvalue()
    sys.stdout.close()
    sys.stdout = orig
    return out

Example 12

Project: dusty
Source File: testcases.py
View license
    @property
    def stdout(self):
        """Returns any stdout that has been generated *since* the last time
        clear_stdout was called."""
        out = sys.stdout.getvalue()[self.stdout_start:].strip()
        if isinstance(out, unicode):
            out = out.encode('utf-8')
        return out

Example 13

Project: fabric
Source File: test_tasks.py
View license
    @mock_streams('stdout')
    def test_should_not_print_executing_line_for_singletons(self):
        """
        should not print "Executing" line for non-networked tasks
        """
        def task():
            pass
        with settings(hosts=[]): # protect against really odd test bleed :(
            execute(task)
        eq_(sys.stdout.getvalue(), "")

Example 14

Project: imagrium
Source File: __init__.py
View license
    def _report_output(test_runner, xml_testsuite, xml_document):
        """Appends the system-out and system-err sections to the XML document.
        """
        systemout = xml_document.createElement('system-out')
        xml_testsuite.appendChild(systemout)

        systemout_text = xml_document.createCDATASection(sys.stdout.getvalue())
        systemout.appendChild(systemout_text)

        systemerr = xml_document.createElement('system-err')
        xml_testsuite.appendChild(systemerr)

        systemerr_text = xml_document.createCDATASection(sys.stderr.getvalue())
        systemerr.appendChild(systemerr_text)

Example 15

Project: fabric
Source File: test_network.py
View license
    @mock_streams('stdout')
    @server()
    def test_trailing_newline_line_drop(self):
        """
        Trailing newlines shouldn't cause last line to be dropped.
        """
        # Multiline output with trailing newline
        cmd = "ls /"
        output_string = RESPONSES[cmd]
        # TODO: fix below lines, duplicates inner workings of tested code
        prefix = "[%s] out: " % env.host_string
        expected = prefix + ('\n' + prefix).join(output_string.split('\n'))
        # Create, tie off thread
        with settings(show('everything'), hide('running')):
            result = run(cmd)
            # Test equivalence of expected, received output
            eq_(expected, sys.stdout.getvalue())
            # Also test that the captured value matches, too.
            eq_(output_string, result)

Example 16

View license
    def test_print(self):
        self.redirect_stdout()
        try:
            self.add_exec('print("output")')
            eq_(sys.stdout.getvalue(), 'output\n')
        finally:
            self.restore_stdout()

Example 17

View license
    def testQuestionMark_1(self):
        self.redirect_stdout()
        try:
            self.add_exec('?')
            assert len(sys.stdout.getvalue()) > 1000, 'IPython help should be pretty big'
        finally:
            self.restore_stdout()

Example 18

Project: Flask-Script
Source File: tests.py
View license
    def test_simple_command_decorator_with_pos_arg(self):

        manager = Manager(self.app)
        
        @manager.command
        def hello(name):
            print "hello", name
        

        assert 'hello' in manager._commands

        manager.handle("manage.py", "hello", ["joe"])
        assert 'hello joe' in sys.stdout.getvalue()

Example 19

Project: simple-db-migrate
Source File: run_test.py
View license
    @patch.object(simple_db_migrate.main.Main, 'labels', return_value=["v1", "foo", "v3"])
    def test_it_should_print_labels_on_database_and_exit(self, labels_mock):
        try:
            simple_db_migrate.run_from_argv(["--info", "labels", "-c", os.path.abspath('sample.conf')])
        except SystemExit as e:
            self.assertEqual(0, e.code)

        self.assertEqual('v1\nfoo\nv3\n\n', sys.stdout.getvalue())

Example 20

Project: guardonce
Source File: test_conversion.py
View license
def runScript(script,inputFile,recursive=False):
	dirName, baseName = os.path.split(inputFile)
	checkDir = setupDangerZone(dirName)
	transformFile = os.path.join(checkDir, baseName)

	invokation = [transformFile]
	if recursive:
		invokation.append('-r')
	script.main(invokation)
	return Output(sys.stdout.getvalue(), sys.stderr.getvalue())

Example 21

Project: stor
Source File: test_cli.py
View license
    @mock.patch.object(SwiftPath, 'walkfiles', autospec=True)
    def test_walkfiles_swift(self, mock_walkfiles):
        mock_walkfiles.return_value = [
            'swift://t/c/a/b.txt',
            'swift://t/c/c.txt',
            'swift://t/c/d.txt'
        ]
        self.parse_args('stor walkfiles -p=*.txt swift://bucket')
        self.assertEquals(sys.stdout.getvalue(),
                          'swift://t/c/a/b.txt\n'
                          'swift://t/c/c.txt\n'
                          'swift://t/c/d.txt\n')
        mock_walkfiles.assert_called_once_with(SwiftPath('swift://bucket'), pattern='*.txt')

Example 22

Project: vumi
Source File: test_vumi_model_migrator.py
View license
    @inlineCallbacks
    def test_main(self):
        yield self.mk_simple_models_old(3)
        self.patch(sys, "stdout", StringIO())
        yield main(
            None, "name",
            "-m", self.model_cls_path,
            "-b", self.riak_manager.bucket_prefix)
        self.assertEqual(
            sys.stdout.getvalue(),
            "Migrating ...\nDone, 3 objects migrated.\n")

Example 23

Project: stor
Source File: test_cli.py
View license
    @mock.patch.object(SwiftPath, 'read_object', autospec=True)
    def test_cat_swift(self, mock_read):
        mock_read.return_value = 'hello world'
        self.parse_args('stor cat swift://some/test/file')
        self.assertEquals(sys.stdout.getvalue(), 'hello world\n')
        mock_read.assert_called_once_with(SwiftPath('swift://some/test/file'))

Example 24

Project: eliot
Source File: test_filter.py
View license
    def test_stdinOut(self):
        """
        L{main} reads from the C{stdin} attribute of the given C{sys} equivalent,
        and writes rendered expressions to the C{stdout} attribute.
        """
        sys = FakeSys(["eliotfilter", "J[0]"], b"[1, 2]\n[4, 5]\n")
        main(sys)
        self.assertEqual(sys.stdout.getvalue(), b"1\n4\n")

Example 25

Project: invoke
Source File: program.py
View license
        @trap
        def use_binary_basename_when_invoked_absolutely(self):
            Program().run("/usr/local/bin/myapp --help", exit=False)
            stdout = sys.stdout.getvalue()
            assert_contains(stdout, "myapp [--core-opts]")
            assert_not_contains(stdout, "/usr/local/bin")

Example 26

Project: invoke
Source File: runners.py
View license
        @trap
        def kwarg_beats_config(self):
            runner = self._runner(out='stuff')
            r = runner.run(_, hide=True)
            eq_(r.stdout, 'stuff')
            eq_(sys.stdout.getvalue(), '')

Example 27

Project: stetl
Source File: test_standard_output.py
View license
    def test_execute(self):
        # Read content of input file
        chain = StetlTestCase.get_chain(self.etl)
        section = StetlTestCase.get_section(chain)
        fn = self.etl.configdict.get(section, 'file_path')
        with open(fn, 'r') as f:
            contents = f.read()
        
        self.etl.run()
        
        self.assertGreater(sys.stdout.getvalue(), 0)
        # Assert includes last linebreak from stdout, due to print function
        self.assertEqual(sys.stdout.getvalue(), contents + '\n')

Example 28

Project: crunch.io-dashboard
Source File: tests.py
View license
    def __exit__(self, type, value, traceback):
        # Restore state
        self.stdoutvalue = sys.stdout.getvalue()
        sys.stdout = self.stdout

        # Check the output only if no exception occured (to avoid "eating" test failures)
        if type:
            return
        
        if self.fail_if_different:
            self.test.assertEquals(self.expected_stdout, self.stdoutvalue)

Example 29

Project: fabric
Source File: test_tasks.py
View license
    @mock_streams('stdout')
    def test_should_print_executing_line_per_host(self):
        """
        should print "Executing" line once per host
        """
        def task():
            pass
        execute(task, hosts=['host1', 'host2'])
        eq_(sys.stdout.getvalue(), """[host1] Executing task 'task'
[host2] Executing task 'task'
""")

Example 30

Project: sublime-config
Source File: tests.py
View license
    def test_executable_path_path_not_string(self):
        shell = '/bin/bash'
        env = {
            'PATH': '/bin'
        }
        view_settings = {
            'PATH': 1
        }
        with GolangConfigMock(shell, env, view_settings, None, {'debug': True}) as mock_context:
            self.assertEquals((None, None), golangconfig.executable_path('go', mock_context.view, mock_context.window))
            self.assertTrue('is not a string' in sys.stdout.getvalue())

Example 31

Project: vumi
Source File: test_vumi_count_models.py
View license
    @inlineCallbacks
    def test_main(self):
        """
        The counter runs via `main()`.
        """
        yield self.mk_simple_models(3)
        self.patch(sys, "stdout", StringIO())
        yield main(
            None, "name",
            "-m", self.model_cls_path,
            "-b", self.riak_manager.bucket_prefix)
        self.assertEqual(
            sys.stdout.getvalue(),
            "Counting all keys ...\nDone, 3 objects found.\n")

Example 32

Project: fabric
Source File: test_decorators.py
View license
@mock_streams('stdout')
def test_global_parallel_honors_runs_once():
    """
    fab -P (or env.parallel) should honor @runs_once
    """
    @decorators.runs_once
    def mytask():
        print("yolo") # 'Carpe diem' for stupid people!
    with settings(hide('everything'), parallel=True):
        execute(mytask, hosts=['localhost', '127.0.0.1'])
    result = sys.stdout.getvalue()
    eq_(result, "yolo\n")
    assert result != "yolo\nyolo\n"

Example 33

View license
    def _restore_std_streams(self):
        stdout = sys.stdout.getvalue()
        stderr = sys.stderr.getvalue()
        close = [sys.stdout, sys.stderr]
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        for stream in close:
            stream.close()
        if stdout and stderr:
            if not stderr.startswith(('*TRACE*', '*DEBUG*', '*INFO*', '*HTML*',
                                      '*WARN*')):
                stderr = '*INFO* %s' % stderr
            if not stdout.endswith('\n'):
                stdout += '\n'
        return self._handle_binary_result(stdout + stderr)

Example 34

Project: sublime-config
Source File: tests.py
View license
    @data('setting_value_gopath_data', True)
    def setting_value_gopath(self, shell, env, view_settings, window_settings, sublime_settings, setting, result):

        with GolangConfigMock(shell, env, view_settings, window_settings, sublime_settings) as mock_context:
            self.assertEquals(result, golangconfig.setting_value(setting, mock_context.view, mock_context.window))
            self.assertEqual('', sys.stdout.getvalue())

Example 35

Project: stango
Source File: test_main.py
View license
    def test_no_files_in_config(self):
        self.write_config('')
        self.set_argv('stango', 'generate', 'out')
        exc = self.assert_raises(SystemExit, stango.main.run)
        self.eq(exc.args[0], 1)
        self.eq(sys.stdout.getvalue(), '')
        self.eq(sys.stderr.getvalue(), "conf.py doesn't define the 'files' variable\n")

Example 36

Project: invoke
Source File: runners.py
View license
        @trap
        def out_can_be_overridden(self):
            "out_stream can be overridden"
            out = StringIO()
            self._runner(out="sup").run(_, out_stream=out)
            eq_(out.getvalue(), "sup")
            eq_(sys.stdout.getvalue(), "")

Example 37

Project: mpyq
Source File: test_mpqarchive.py
View license
    def test_print_block_table(self):
        self.archive.print_block_table()
        self.assertEqual(sys.stdout.getvalue(),
                         "MPQ archive block table\n"
                         "-----------------------\n"
                         " Offset  ArchSize RealSize  Flags\n"
                         "0000002C      727      890 81000200\n"
                         "00000303      801     1257 81000200\n"
                         "00000624   194096   479869 81000200\n"
                         "0002FC54      226      334 81000200\n"
                         "0002FD36       97       97 81000200\n"
                         "0002FD97     1323     1970 81000200\n"
                         "000302C2     6407    12431 81000200\n"
                         "00031BC9      533     2400 81000200\n"
                         "00031DDE      120      164 81000200\n"
                         "00031E56      254      288 81000200\n"
                         "\n")

Example 38

Project: sublime-config
Source File: tests.py
View license
    def test_setting_value_multiple_gopath(self):
        shell = '/bin/bash'
        env = {
            'GOPATH': '{tempdir}bin%s{tempdir}usr/bin' % os.pathsep
        }
        with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
            mock_context.replace_tempdir_env()
            mock_context.make_dirs(['bin', 'usr/bin'])
            self.assertEquals(
                (env['GOPATH'], shell),
                golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
            )
            self.assertEqual('', sys.stdout.getvalue())

Example 39

Project: stor
Source File: test_cli.py
View license
    @mock.patch.object(S3Path, 'read_object', autospec=True)
    def test_cat_s3(self, mock_read):
        mock_read.return_value = 'hello world\n'
        self.parse_args('stor cat s3://test/file')
        self.assertEquals(sys.stdout.getvalue(), 'hello world\n')
        mock_read.assert_called_once_with(S3Path('s3://test/file'))

Example 40

Project: Flask-Script
Source File: tests.py
View license
    def test_run_existing_command(self):
        
        manager = Manager(self.app)
        manager.add_command("simple", SimpleCommand())
        manager.handle("manage.py", "simple")
        assert 'OK' in sys.stdout.getvalue()

Example 41

Project: invoke
Source File: context.py
View license
        @trap
        @patch('invoke.context.getpass')
        @mock_subprocess()
        def echo_hides_extra_sudo_flags(self, getpass):
            skip() # see TODO in sudo() re: clean output display
            config = Config(overrides={'runner': _Dummy})
            Context(config=config).sudo('nope', echo=True)
            output = sys.stdout.getvalue()
            sys.__stderr__.write(repr(output) + "\n")
            ok_("-S" not in output)
            ok_(Context().sudo.prompt not in output)
            ok_("sudo nope" in output)

Example 42

Project: simple-db-migrate
Source File: run_test.py
View license
    @patch.object(simple_db_migrate.main.Main, 'labels', return_value=[])
    def test_it_should_print_none_when_there_are_no_labels_on_database_and_exit(self, labels_mock):
        try:
            simple_db_migrate.run_from_argv(["--info", "labels", "-c", os.path.abspath('sample.conf')])
        except SystemExit as e:
            self.assertEqual(0, e.code)

        self.assertEqual('NONE\n\n', sys.stdout.getvalue())

Example 43

Project: guardonce
Source File: test_check.py
View license
def runCheckGuardOnFile(inputFile):
	dirName, baseName = os.path.split(inputFile)
	checkFile = os.path.join(dirName, baseName)

	invokation = [checkFile]
	checkguard.main(invokation)
	return Output(sys.stdout.getvalue(), sys.stderr.getvalue())

Example 44

Project: stor
Source File: test_cli.py
View license
    @mock.patch.object(PosixPath, 'walkfiles', autospec=True)
    def test_walkfiles_no_pattern(self, mock_walkfiles):
        mock_walkfiles.return_value = [
            './a/b.txt',
            './c.txt',
            './d.txt',
            './file'
        ]
        self.parse_args('stor walkfiles .')
        self.assertEquals(sys.stdout.getvalue(),
                          './a/b.txt\n'
                          './c.txt\n'
                          './d.txt\n'
                          './file\n')
        mock_walkfiles.assert_called_once_with(PosixPath('.'))

Example 45

Project: simple-db-migrate
Source File: run_test.py
View license
    @patch.object(simple_db_migrate.main.Main, 'last_label', return_value=None)
    def test_it_should_print_none_as_last_label_when_there_are_no_labels_on_database_and_exit(self, last_label_mock):
        try:
            simple_db_migrate.run_from_argv(["--info", "last_label", "-c", os.path.abspath('sample.conf')])
        except SystemExit as e:
            self.assertEqual(0, e.code)

        self.assertEqual('NONE\n\n', sys.stdout.getvalue())

Example 46

Project: simple-db-migrate
Source File: run_test.py
View license
    @patch.object(simple_db_migrate.main.Main, 'last_label', return_value="v3")
    def test_it_should_print_last_label_on_database_and_exit(self, last_label_mock):
        try:
            simple_db_migrate.run_from_argv(["--info", "last_label", "-c", os.path.abspath('sample.conf')])
        except SystemExit as e:
            self.assertEqual(0, e.code)

        self.assertEqual('v3\n\n', sys.stdout.getvalue())

Example 47

Project: golismero
Source File: doctest_driver.py
View license
    def _check_output(self, example):
        want = example.want
        optionflags = self._get_optionflags(example)
        got = sys.stdout.getvalue()
        sys.stdout.truncate(0)
        if not self.checker.check_output(want, got, optionflags):
            self.runner.report_failure(self.save_stdout.write,
                                       self.test, example, got)
            return False
        else:
            return True

Example 48

Project: Flask-Script
Source File: tests.py
View license
    def test_simple_command_decorator(self):

        manager = Manager(self.app)
        
        @manager.command
        def hello():
            print "hello"

        assert 'hello' in manager._commands

        manager.handle("manage.py", "hello")
        assert 'hello' in sys.stdout.getvalue()

Example 49

Project: vcs
Source File: test_cli.py
View license
    def test_default_stdout(self):
        stream = StringIO()
        with mock.patch.object(sys, 'stdout', stream):
            command = BaseCommand()
            command.stdout.write(u'foobar')
            self.assertEqual(sys.stdout.getvalue(), u'foobar')

Example 50

Project: presto-admin
Source File: test_fabric_patches.py
View license
    def test_should_print_executing_line_per_host(self):
        """
        should print "Executing" line once per host
        """
        state.output.running = True

        def task():
            pass
        execute(task, hosts=['host1', 'host2'])
        self.assertEqual(sys.stdout.getvalue(),
                         """[host1] Executing task 'task'
[host2] Executing task 'task'
""")