当前位置: 首页>>代码示例>>Python>>正文


Python StringIO.getvalue方法代码示例

本文整理汇总了Python中six.moves.StringIO.getvalue方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.getvalue方法的具体用法?Python StringIO.getvalue怎么用?Python StringIO.getvalue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在six.moves.StringIO的用法示例。


在下文中一共展示了StringIO.getvalue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_grid_01

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
    def test_grid_01(self):
        nid = 1
        cp = 2
        cd = 0
        ps = ''
        seid = 0
        card_count = {'GRID': 1,}

        model = BDF()
        model.allocate(card_count)
        data1 = BDFCard(['GRID', nid, cp, 0., 0., 0., cd, ps, seid])

        nodes = model.grid
        nodes.add(data1)

        #print n1
        f = StringIO()
        nodes.write_bdf(f, size=8, write_header=False)
        nodes.write_bdf(f, size=16, write_header=False)
        nodes.write_bdf(f, size=16, is_double=True, write_header=False)

        # small field
        f = StringIO()
        nodes.write_bdf(f, size=8, write_header=False)
        msg = f.getvalue()
        card = 'GRID           1       2      0.      0.      0.\n'
        self.assertCardEqual(msg, card)

        # large field
        f = StringIO()
        nodes.write_bdf(f, size=16, write_header=False)
        card = ('GRID*                  1               2              0.              0.\n'
                '*                     0.\n')
        msg = f.getvalue()
        self.assertCardEqual(msg, card)
开发者ID:umvarma,项目名称:pynastran,代码行数:37,代码来源:test_nodes.py

示例2: test_question_choices

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
def test_question_choices():

    # TODO: come up with a reusable fixture for testing here

    choices = {
        'a': '[a], b, cc',
        'b': 'a, [b], cc',
        'cc': 'a, b, [cc]'
    }

    for default_value in ['a', 'b']:
        choices_str = choices[default_value]
        for entered_value, expected_value in [(default_value, default_value),
                                              ('', default_value),
                                              ('cc', 'cc')]:
            with patch_getpass(return_value=entered_value), \
                patch_getpass(return_value=entered_value):
                out = StringIO()
                response = DialogUI(out=out).question("prompt", choices=sorted(choices), default=default_value)
                eq_(response, expected_value)
                # getpass doesn't use out -- goes straight to the terminal
                eq_(out.getvalue(), '')
                # TODO: may be test that the prompt was passed as a part of the getpass arg
                #eq_(out.getvalue(), 'prompt (choices: %s): ' % choices_str)

    # check some expected exceptions to be thrown
    out = StringIO()
    ui = DialogUI(out=out)
    assert_raises(ValueError, ui.question, "prompt", choices=['a'], default='b')
    eq_(out.getvalue(), '')

    with patch_getpass(return_value='incorrect'):
        assert_raises(RuntimeError, ui.question, "prompt", choices=['a', 'b'])
    assert_re_in(".*ERROR: .incorrect. is not among choices.*", out.getvalue())
开发者ID:debanjum,项目名称:datalad,代码行数:36,代码来源:test_dialog.py

示例3: _test_progress_bar

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
def _test_progress_bar(backend, len, increment):
    out = StringIO()
    fill_str = ('123456890' * (len//10))[:len]
    pb = DialogUI(out).get_progressbar(
        'label', fill_str, total=10, backend=backend)
    pb.start()
    # we can't increment 11 times
    for x in range(11):
        if not (increment and x == 0):
            # do not increment on 0
            pb.update(x if not increment else 1, increment=increment)
        #out.flush()  # needed atm... no longer?
        # Progress bar is having 0.1 sec between updates by default, so
        # we could either sleep:
        #import time; time.sleep(0.1)
        # or just force the refresh
        pb.refresh()
        pstr = out.getvalue()
        if backend not in ('annex-remote', 'silent'):  # no str repr
            ok_startswith(pstr.lstrip('\r'), 'label:')
            assert_re_in(r'.*\b%d%%.*' % (10*x), pstr)
        if backend == 'progressbar':
            assert_in('ETA', pstr)
    pb.finish()
    if backend not in ('annex-remote', 'silent'):
        # returns back and there is no spurious newline
        ok_endswith(out.getvalue(), '\r')
开发者ID:hanke,项目名称:datalad,代码行数:29,代码来源:test_dialog.py

示例4: test_fail_with_short_help

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
def test_fail_with_short_help():
    out = StringIO()
    with assert_raises(SystemExit) as cme:
        fail_with_short_help(exit_code=3, out=out)
    assert_equal(cme.exception.code, 3)
    assert_equal(out.getvalue(), "")

    out = StringIO()
    with assert_raises(SystemExit) as cme:
        fail_with_short_help(msg="Failed badly", out=out)
    assert_equal(cme.exception.code, 1)
    assert_equal(out.getvalue(), "error: Failed badly\n")

    # Suggestions, hint, etc
    out = StringIO()
    with assert_raises(SystemExit) as cme:
        fail_with_short_help(
            msg="Failed badly",
            known=["mother", "mutter", "father", "son"],
            provided="muther",
            hint="You can become one",
            exit_code=0,  # noone forbids
            what="parent",
            out=out)
    assert_equal(cme.exception.code, 0)
    assert_equal(out.getvalue(),
                 "error: Failed badly\n"
                 "datalad: Unknown parent 'muther'.  See 'datalad --help'.\n\n"
                 "Did you mean any of these?\n"
                 "        mutter\n"
                 "        mother\n"
                 "        father\n"
                 "Hint: You can become one\n")
开发者ID:datalad,项目名称:datalad,代码行数:35,代码来源:test_main.py

示例5: UpdateAppsAndBackendsTest

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
class UpdateAppsAndBackendsTest(TestCase):

    def setUp(self):
        self.output = StringIO()
        # BASE_APPS are needed for the managment commands to load successfully
        self.BASE_APPS = [
            'rapidsms',
            'django.contrib.auth',
            'django.contrib.contenttypes',
        ]

    def test_no_apps_then_none_added(self):
        with self.settings(INSTALLED_APPS=self.BASE_APPS):
            call_command('update_apps', stdout=self.output)
        self.assertEqual(self.output.getvalue(), '')

    def test_adds_app(self):
        # Add an app that has a RapidSMS app
        APPS = self.BASE_APPS + ['rapidsms.contrib.handlers']
        with self.settings(INSTALLED_APPS=APPS):
            call_command('update_apps', stdout=self.output)
        self.assertEqual(self.output.getvalue(), 'Added persistent app rapidsms.contrib.handlers\n')

    def test_no_backends_then_none_added(self):
        with self.settings(INSTALLED_BACKENDS={}):
            call_command('update_backends', stdout=self.output)
        self.assertEqual(self.output.getvalue(), '')

    def test_adds_backend(self):
        INSTALLED_BACKENDS = {
            "message_tester": {"ENGINE": "rapidsms.backends.database.DatabaseBackend"},
        }
        with self.settings(INSTALLED_BACKENDS=INSTALLED_BACKENDS):
            call_command('update_backends', stdout=self.output)
        self.assertEqual(self.output.getvalue(), 'Added persistent backend message_tester\n')
开发者ID:0xD3ADB33F,项目名称:rapidsms,代码行数:37,代码来源:test_management.py

示例6: test_deqatn_10

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
    def test_deqatn_10(self):
        """
        per nast/tpl/ptdmi1.dat
        """
        model = BDF(debug=None)
        model.cards_to_read.add('DEQATN')
        model.test_deqatn = True
        card = [
            'deqatn  2       f(x,y,z)= 1.;',
            '        L=x+y',
        ]
        model.add_card(card, 'DEQATN', is_list=False)
        model.cross_reference()

        s = StringIO()
        model.write_bdf(s, close=False)
        s.getvalue()
        s.close()
        eq = model.dequations[2]
        x = zeros(10., dtype='float32')
        y = zeros(11., dtype='float32')
        z = zeros(12., dtype='float32')
        #out = eq.func(x, y, z)
        out = eq.func(1.0, 2.0)
        print(out)
开发者ID:saullocastro,项目名称:pyNastran,代码行数:27,代码来源:test_dequatn.py

示例7: test_deqatn_9

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
    def test_deqatn_9(self):
        """
        per nast/tpl/ptdmi1.dat
        """
        model = BDF(debug=None)
        model.cards_to_read.add('DEQATN')
        model.test_deqatn = True
        card = [
            'deqatn  2       f(x,y,z)= 1.;',
            '        L=1+2+3+',
            '        + 4/min(1,2);',
            '        b= 4.;',
            '        h= 2.;',
            '        t1= 200.;',
            '        t2= 300.;',
            '        t=t1*(L-x)/L+t2*x/L',
            '        +4'
        ]
        model.add_card(card, 'DEQATN', is_list=False)
        model.cross_reference()

        s = StringIO()
        model.write_bdf(s, close=False)
        s.getvalue()
        s.close()
开发者ID:saullocastro,项目名称:pyNastran,代码行数:27,代码来源:test_dequatn.py

示例8: test_text_output

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
def test_text_output():
    entry = BibTeX(_sample_bibtex)
    entry2 = BibTeX(_sample_bibtex2)

    # in this case, since we're not citing any module or method, we shouldn't
    # output anything
    collector = DueCreditCollector()
    collector.cite(entry, path='package')

    strio = StringIO()
    TextOutput(strio, collector).dump(tags=['*'])
    value = strio.getvalue()
    assert "0 packages cited" in value, "value was %s" % value
    assert "0 modules cited" in value, "value was %s" % value
    assert "0 functions cited" in value, "value was %s" % value

    # but it should be cited if cite_module=True
    collector = DueCreditCollector()
    collector.cite(entry, path='package', cite_module=True)

    strio = StringIO()
    TextOutput(strio, collector).dump(tags=['*'])
    value = strio.getvalue()
    assert "1 package cited" in value, "value was %s" % value
    assert "0 modules cited" in value, "value was %s" % value
    assert "0 functions cited" in value, "value was %s" % value

    # in this case, we should be citing the package since we are also citing a
    # submodule
    collector = DueCreditCollector()
    collector.cite(entry, path='package')
    collector.cite(entry, path='package.module')

    strio = StringIO()
    TextOutput(strio, collector).dump(tags=['*'])
    value = strio.getvalue()
    assert "1 package cited" in value, "value was %s" % value
    assert "1 module cited" in value, "value was %s" % value
    assert "0 functions cited" in value, "value was %s" % value
    assert "Halchenko, Y.O." in value, "value was %s" % value
    assert value.strip().endswith("Frontiers in Neuroinformatics, 6(22).")


    # in this case, we should be citing the package since we are also citing a
    # submodule
    collector = DueCreditCollector()
    collector.cite(entry, path='package')
    collector.cite(entry2, path='package')
    collector.cite(entry, path='package.module')

    strio = StringIO()
    TextOutput(strio, collector).dump(tags=['*'])
    value = strio.getvalue()
    assert "1 package cited" in value, "value was %s" % value
    assert "1 module cited" in value, "value was %s" % value
    assert "0 functions cited" in value, "value was %s" % value
    assert "Halchenko, Y.O." in value, "value was %s" % value
    assert '[1, 2]' in value, "value was %s" %value
    assert '[3]' not in value, "value was %s" %value
开发者ID:duecredit,项目名称:duecredit,代码行数:61,代码来源:test_io.py

示例9: BaseProxyTestCase

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
class BaseProxyTestCase(test.NoDBTestCase):

    def setUp(self):
        super(BaseProxyTestCase, self).setUp()
        self.stderr = StringIO()
        self.useFixture(fixtures.MonkeyPatch('sys.stderr', self.stderr))

    @mock.patch('os.path.exists', return_value=False)
    # NOTE(mriedem): sys.exit raises TestingException so we can actually exit
    # the test normally.
    @mock.patch('sys.exit', side_effect=test.TestingException)
    def test_proxy_ssl_without_cert(self, mock_exit, mock_exists):
        self.flags(ssl_only=True)
        self.assertRaises(test.TestingException, baseproxy.proxy,
                          '0.0.0.0', '6080')
        mock_exit.assert_called_once_with(-1)
        self.assertEqual(self.stderr.getvalue(),
                         "SSL only and self.pem not found\n")

    @mock.patch('os.path.exists', return_value=False)
    @mock.patch('sys.exit', side_effect=test.TestingException)
    def test_proxy_web_dir_does_not_exist(self, mock_exit, mock_exists):
        self.flags(web='/my/fake/webserver/')
        self.assertRaises(test.TestingException, baseproxy.proxy,
                          '0.0.0.0', '6080')
        mock_exit.assert_called_once_with(-1)

    @mock.patch('os.path.exists', return_value=True)
    @mock.patch.object(logging, 'setup')
    @mock.patch.object(gmr.TextGuruMeditation, 'setup_autorun')
    @mock.patch('nova.console.websocketproxy.NovaWebSocketProxy.__init__',
                       return_value=None)
    @mock.patch('nova.console.websocketproxy.NovaWebSocketProxy.start_server')
    def test_proxy(self, mock_start, mock_init, mock_gmr, mock_log,
                   mock_exists):
        baseproxy.proxy('0.0.0.0', '6080')
        mock_log.assert_called_once_with(baseproxy.CONF, 'nova')
        mock_gmr.mock_assert_called_once_with(version)
        mock_init.assert_called_once_with(
            listen_host='0.0.0.0', listen_port='6080', source_is_ipv6=False,
            cert='self.pem', key=None, ssl_only=False,
            daemon=False, record=None, security_proxy=None, traffic=True,
            web='/usr/share/spice-html5', file_only=True,
            RequestHandlerClass=websocketproxy.NovaProxyRequestHandler)
        mock_start.assert_called_once_with()

    @mock.patch('os.path.exists', return_value=False)
    @mock.patch('sys.exit', side_effect=test.TestingException)
    def test_proxy_exit_with_error(self, mock_exit, mock_exists):
        self.flags(ssl_only=True)
        self.assertRaises(test.TestingException, baseproxy.proxy,
                          '0.0.0.0', '6080')
        self.assertEqual(self.stderr.getvalue(),
                         "SSL only and self.pem not found\n")
        mock_exit.assert_called_once_with(-1)
开发者ID:arbrandes,项目名称:nova,代码行数:57,代码来源:test_baseproxy.py

示例10: export_import_export

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
def export_import_export():
    out = StringIO()
    export_bloggers(out)
    out = out.getvalue()
    db.drop_all()
    db.create_all()
    import_bloggers(StringIO(out))
    out2 = StringIO()
    export_bloggers(out2)
    assert json.loads(out) == json.loads(out2.getvalue()), \
        "export(import(export())) != export()"
开发者ID:zenhack,项目名称:iron-blogger2,代码行数:13,代码来源:test_task_import_export.py

示例11: _test_deqatn_2

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
    def _test_deqatn_2(self):
        model = BDF(debug=None)
        #model.cards_to_read.add('DEQATN')
        #model.test_deqatn = True
        card = ["DEQATN", 1000, "MAXDIFF(t1,t2)=abs(t2-t1)/t1"]
        model.add_card(card, "DEQATN", is_list=True)
        model.cross_reference()

        s = StringIO()
        with self.assertRaises(AttributeError): # TODO: fix this...
            model.write_bdf(s)
        s.getvalue()
开发者ID:saullocastro,项目名称:pyNastran,代码行数:14,代码来源:test_dequatn.py

示例12: TestNovaStatusMain

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
class TestNovaStatusMain(test.NoDBTestCase):
    """Tests for the basic nova-status command infrastructure."""

    def setUp(self):
        super(TestNovaStatusMain, self).setUp()
        self.output = StringIO()
        self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.output))

    @mock.patch.object(status.config, 'parse_args')
    @mock.patch.object(status, 'CONF')
    def _check_main(self, mock_CONF, mock_parse_args,
                    category_name='check', expected_return_value=0):
        mock_CONF.category.name = category_name
        return_value = status.main()

        self.assertEqual(expected_return_value, return_value)
        mock_CONF.register_cli_opt.assert_called_once_with(
            status.category_opt)

    @mock.patch.object(status.version, 'version_string_with_package',
                       return_value="x.x.x")
    def test_main_version(self, mock_version_string):
        self._check_main(category_name='version')
        self.assertEqual("x.x.x\n", self.output.getvalue())

    @mock.patch.object(status.cmd_common, 'print_bash_completion')
    def test_main_bash_completion(self, mock_print_bash):
        self._check_main(category_name='bash-completion')
        mock_print_bash.assert_called_once_with(status.CATEGORIES)

    @mock.patch.object(status.cmd_common, 'get_action_fn')
    def test_main(self, mock_get_action_fn):
        mock_fn = mock.Mock()
        mock_fn_args = [mock.sentinel.arg]
        mock_fn_kwargs = {'key': mock.sentinel.value}
        mock_get_action_fn.return_value = (mock_fn, mock_fn_args,
                                           mock_fn_kwargs)

        self._check_main(expected_return_value=mock_fn.return_value)
        mock_fn.assert_called_once_with(mock.sentinel.arg,
                                        key=mock.sentinel.value)

    @mock.patch.object(status.cmd_common, 'get_action_fn')
    def test_main_error(self, mock_get_action_fn):
        mock_fn = mock.Mock(side_effect=Exception('wut'))
        mock_get_action_fn.return_value = (mock_fn, [], {})

        self._check_main(expected_return_value=255)
        output = self.output.getvalue()
        self.assertIn('Error:', output)
        # assert the traceback is in the output
        self.assertIn('wut', output)
开发者ID:amadev,项目名称:nova,代码行数:54,代码来源:test_status.py

示例13: _report_testsuite

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
    def _report_testsuite(suite_name, tests, xml_document, parentElement,
                          properties):
        """
        Appends the testsuite section to the XML document.
        """
        testsuite = xml_document.createElement('testsuite')
        parentElement.appendChild(testsuite)

        testsuite.setAttribute('name', suite_name)
        testsuite.setAttribute('tests', str(len(tests)))

        testsuite.setAttribute(
            'time', '%.3f' % sum(map(lambda e: e.elapsed_time, tests))
        )
        failures = filter(lambda e: e.outcome == e.FAILURE, tests)
        testsuite.setAttribute('failures', str(len(list(failures))))

        errors = filter(lambda e: e.outcome == e.ERROR, tests)
        testsuite.setAttribute('errors', str(len(list(errors))))

        skips = filter(lambda e: e.outcome == _TestInfo.SKIP, tests)
        testsuite.setAttribute('skipped', str(len(list(skips))))
 
        _XMLTestResult._report_testsuite_properties(
            testsuite, xml_document, properties)

        for test in tests:
            _XMLTestResult._report_testcase(test, testsuite, xml_document)

        systemout = xml_document.createElement('system-out')
        testsuite.appendChild(systemout)

        stdout = StringIO()
        for test in tests:
            # Merge the stdout from the tests in a class
            if test.stdout is not None:
                stdout.write(test.stdout)
        _XMLTestResult._createCDATAsections(
            xml_document, systemout, stdout.getvalue())

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

        stderr = StringIO()
        for test in tests:
            # Merge the stderr from the tests in a class
            if test.stderr is not None:
                stderr.write(test.stderr)
        _XMLTestResult._createCDATAsections(
            xml_document, systemerr, stderr.getvalue())

        return testsuite
开发者ID:kirthiss,项目名称:unittest-xml-reporting,代码行数:54,代码来源:result.py

示例14: test_simple_roundtrip

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
    def test_simple_roundtrip(self):
        # FIXME: we compare the loaded json to avoid dealing with encoding
        # differences when comparing objects, but this is kinda stupid
        r_ipkg = InstalledPkgDescription(self.sections, self.meta, {})
        f = StringIO()
        r_ipkg._write(f)
        r_s = f.getvalue()

        ipkg = InstalledPkgDescription.from_string(r_s)
        f = StringIO()
        ipkg._write(f)
        s = f.getvalue()

        self.assertEqual(json.loads(r_s), json.loads(s))
开发者ID:jjehannet,项目名称:Bento,代码行数:16,代码来源:test_ipkg.py

示例15: _test_progress_bar

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import getvalue [as 别名]
def _test_progress_bar(len):
    out = StringIO()
    fill_str = ('123456890' * (len//10))[:len]
    pb = DialogUI(out).get_progressbar('label', fill_str, maxval=10)
    pb.start()
    for x in range(11):
        pb.update(x)
        out.flush()  # needed atm
        pstr = out.getvalue()
        ok_startswith(pstr, 'label:')
        assert_in(' %d%% ' % (10*x), pstr)
        assert_in('ETA', pstr)
    pb.finish()
    ok_endswith(out.getvalue(), '\n')
开发者ID:glalteva,项目名称:datalad,代码行数:16,代码来源:test_dialog.py


注:本文中的six.moves.StringIO.getvalue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。