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


Python NativeIO.getvalue方法代码示例

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


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

示例1: Test_copy_dir

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
class Test_copy_dir(unittest.TestCase):
    def setUp(self):
        import tempfile
        from pyramid.compat import NativeIO
        self.dirname = tempfile.mkdtemp()
        self.out = NativeIO()
        self.fixturetuple = ('pyramid.tests.test_scaffolds',
                             'fixture_scaffold')

    def tearDown(self):
        import shutil
        shutil.rmtree(self.dirname, ignore_errors=True)
        self.out.close()

    def _callFUT(self, *arg, **kw):
        kw['out_'] = self.out
        from pyramid.scaffolds.copydir import copy_dir
        return copy_dir(*arg, **kw)

    def test_copy_source_as_pkg_resource(self):
        vars = {'package':'mypackage'}
        self._callFUT(self.fixturetuple,
                      self.dirname,
                      vars,
                      1, False,
                      template_renderer=dummy_template_renderer)
        result = self.out.getvalue()
        self.assertTrue('Creating %s/mypackage/' % self.dirname in result)
        self.assertTrue(
            'Copying fixture_scaffold/+package+/__init__.py_tmpl to' in result)
        source = pkg_resources.resource_filename(
            'pyramid.tests.test_scaffolds',
            'fixture_scaffold/+package+/__init__.py_tmpl')
        target = os.path.join(self.dirname, 'mypackage', '__init__.py')
        with open(target, 'r') as f:
            tcontent = f.read()
        with open(source, 'r') as f:
            scontent = f.read()
        self.assertEqual(scontent, tcontent)

    def test_copy_source_as_dirname(self):
        vars = {'package':'mypackage'}
        source = pkg_resources.resource_filename(*self.fixturetuple)
        self._callFUT(source,
                      self.dirname,
                      vars,
                      1, False,
                      template_renderer=dummy_template_renderer)
        result = self.out.getvalue()
        self.assertTrue('Creating %s/mypackage/' % self.dirname in result)
        self.assertTrue('Copying __init__.py_tmpl to' in result)
        source = pkg_resources.resource_filename(
            'pyramid.tests.test_scaffolds',
            'fixture_scaffold/+package+/__init__.py_tmpl')
        target = os.path.join(self.dirname, 'mypackage', '__init__.py')
        with open(target, 'r') as f:
            tcontent = f.read()
        with open(source, 'r') as f:
            scontent = f.read()
        self.assertEqual(scontent, tcontent)
开发者ID:adamryan,项目名称:pyramid,代码行数:62,代码来源:test_copydir.py

示例2: TestPServeCommand

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
class TestPServeCommand(unittest.TestCase):
    def setUp(self):
        from pyramid.compat import NativeIO
        self.out_ = NativeIO()

    def out(self, msg):
        self.out_.write(msg)
        
    def _getTargetClass(self):
        from pyramid.scripts.pserve import PServeCommand
        return PServeCommand

    def _makeOne(self, *args):
        effargs = ['pserve']
        effargs.extend(args)
        cmd = self._getTargetClass()(effargs)
        cmd.out = self.out
        return cmd

    def test_run_no_args(self):
        inst = self._makeOne()
        result = inst.run()
        self.assertEqual(result, 2)
        self.assertEqual(self.out_.getvalue(), 'You must give a config file')

    def test_run_stop_daemon_no_such_pid_file(self):
        path = os.path.join(os.path.dirname(__file__), 'wontexist.pid')
        inst = self._makeOne('--stop-daemon', '--pid-file=%s' % path)
        inst.run()
        self.assertEqual(self.out_.getvalue(),'No PID file exists in %s' %
                         path)
        
    def test_run_stop_daemon_bad_pid_file(self):
        path = __file__
        inst = self._makeOne('--stop-daemon', '--pid-file=%s' % path)
        inst.run()
        self.assertEqual(
            self.out_.getvalue(),'Not a valid PID file in %s' % path)

    def test_run_stop_daemon_invalid_pid_in_file(self):
        fn = tempfile.mktemp()
        with open(fn, 'wb') as tmp:
            tmp.write(b'9999999')
        tmp.close()
        inst = self._makeOne('--stop-daemon', '--pid-file=%s' % fn)
        inst.run()
        self.assertEqual(self.out_.getvalue(),
                         'PID in %s is not valid (deleting)' % fn)

    def test_parse_vars_good(self):
        vars = ['a=1', 'b=2']
        inst = self._makeOne('development.ini')
        result = inst.parse_vars(vars)
        self.assertEqual(result, {'a': '1', 'b': '2'})
        
    def test_parse_vars_bad(self):
        vars = ['a']
        inst = self._makeOne('development.ini')
        self.assertRaises(ValueError, inst.parse_vars, vars)
开发者ID:aadabi,项目名称:pyramid,代码行数:61,代码来源:test_pserve.py

示例3: test_truncating_formatter

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
 def test_truncating_formatter(self):
     buf = NativeIO()
     logger = logging.Logger('test', logging.DEBUG)
     hdlr = StreamHandler(buf)
     hdlr.setFormatter(TruncatingFormatter())
     logger.addHandler(hdlr)
     logger.debug('%s', 'X' * 99, extra=dict(output_limit=100))
     self.assert_equal(len(buf.getvalue().strip()), 99)
     buf.seek(0)
     buf.truncate()
     logger.debug('%s', 'X' * 101, extra=dict(output_limit=100))
     self.assert_equal(len(buf.getvalue().strip()), 100)
开发者ID:helixyte,项目名称:everest,代码行数:14,代码来源:test_utils.py

示例4: to_string

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
 def to_string(self, obj):
     """
     Converts the given resource to a string representation and returns
     it.
     """
     stream = NativeIO()
     self.to_stream(obj, stream)
     return stream.getvalue()
开发者ID:b8va,项目名称:everest,代码行数:10,代码来源:base.py

示例5: print_tb

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
 def print_tb(self):
     if self.isexc and self.exc_value:
         out = NativeIO()
         traceback.print_exception(
             self.exc_type, self.exc_value, self.exc_traceback, file=out)
         return out.getvalue()
     else:
         return self.exc
开发者ID:webmaven,项目名称:ptah,代码行数:10,代码来源:config.py

示例6: TestPServeCommand

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
class TestPServeCommand(unittest.TestCase):
    def setUp(self):
        from pyramid.compat import NativeIO
        self.out_ = NativeIO()

    def out(self, msg):
        self.out_.write(msg)

    def _get_server(*args, **kwargs):
        def server(app):
            return ''

        return server

    def _getTargetClass(self):
        from pyramid.scripts.pserve import PServeCommand
        return PServeCommand

    def _makeOne(self, *args):
        effargs = ['pserve']
        effargs.extend(args)
        cmd = self._getTargetClass()(effargs)
        cmd.out = self.out
        return cmd

    def test_run_no_args(self):
        inst = self._makeOne()
        result = inst.run()
        self.assertEqual(result, 2)
        self.assertEqual(self.out_.getvalue(), 'You must give a config file')

    def test_get_options_no_command(self):
        inst = self._makeOne()
        inst.args = ['foo', 'a=1', 'b=2']
        result = inst.get_options()
        self.assertEqual(result, {'a': '1', 'b': '2'})

    def test_parse_vars_good(self):
        from pyramid.tests.test_scripts.dummy import DummyApp

        inst = self._makeOne('development.ini', 'a=1', 'b=2')
        inst.loadserver = self._get_server


        app = DummyApp()

        def get_app(*args, **kwargs):
            app.global_conf = kwargs.get('global_conf', None)

        inst.loadapp = get_app
        inst.run()

        self.assertEqual(app.global_conf, {'a': '1', 'b': '2'})

    def test_parse_vars_bad(self):
        inst = self._makeOne('development.ini', 'a')
        inst.loadserver = self._get_server
        self.assertRaises(ValueError, inst.run)
开发者ID:Natim,项目名称:pyramid,代码行数:60,代码来源:test_pserve.py

示例7: Api

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
def Api(request):
    """ Rest API interface """
    response = request.response

    # authentication by token
    token = request.environ.get('HTTP_X_AUTH_TOKEN')
    if token:
        secret = ptah.get_settings(ptah.CFG_ID_PTAH, request.registry)['secret']

        try:
            timestamp, userid, tokens, user_data = parse_ticket(
                secret, '%s!' % token, '0.0.0.0')
        except BadTicket:
            userid = None

        if userid:
            ptah.auth_service.set_userid(userid)

    # search service and action
    service = request.matchdict['service']
    subpath = request.matchdict['subpath']
    if subpath:
        action = subpath[0]
        arguments = subpath[1:]
        if ':' in action:
            action, arg = action.split(':', 1)
            arguments = (arg,) + arguments
    else:
        action = 'apidoc'
        arguments = ()

    request.environ['SCRIPT_NAME'] = '/__rest__/%s' % service
    response.headerslist = {'Content-Type': 'application/json'}

    # execute action for specific service
    try:
        result = config.get_cfg_storage(ID_REST)[service](
            request, action, *arguments)
    except WSGIHTTPException as exc:
        response.status = exc.status
        result = {'message': str(exc)}
    except Exception as exc:
        response.status = 500

        out = NativeIO()
        traceback.print_exc(file=out)

        result = {'message': str(exc),
                  'traceback': out.getvalue()}

    if isinstance(result, Response):
        return result

    response.text = text_(
        dumps(result, indent=True, default=dthandler), 'utf-8')
    return response
开发者ID:djedproject,项目名称:ptahcms,代码行数:58,代码来源:restsrv.py

示例8: get_traceback

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
def get_traceback():
    """
    Fetches the last traceback from :var:`sys.exc_info` and returns it as a
    formatted string.

    :returns: formatted traceback (string)
    """
    buf = NativeIO()
    traceback.print_exc(file=buf)
    return buf.getvalue()
开发者ID:b8va,项目名称:everest,代码行数:12,代码来源:utils.py

示例9: test_list_models

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
    def test_list_models(self):
        @ptah.tinfo(
            'custom', title='Custom model',
            description = 'Custom model description')

        class CustomModel(object):
            """ Custom module description """

            title = 'Custom Module'

        self.init_ptah()

        sys.argv[1:] = ['--list-models', 'ptah.ini']

        stdout = sys.stdout
        out = NativeIO()
        sys.stdout = out

        manage.main(False)
        sys.stdout = stdout

        val = out.getvalue()

        self.assertIn('* type:custom: Custom model (disabled: False)', val)
        self.assertIn('Custom model description', val)
        self.assertIn('class: CustomModel', val)
        self.assertIn('module: test_manage', val)

        # disable
        cfg = ptah.get_settings(ptah.CFG_ID_PTAH)
        cfg['disable_models'] = ('type:custom',)

        out = NativeIO()
        sys.stdout = out

        manage.main(False)
        sys.stdout = stdout

        val = out.getvalue()

        self.assertIn('* type:custom: Custom model (disabled: True)', val)
开发者ID:carlicos,项目名称:ptah,代码行数:43,代码来源:test_manage.py

示例10: string_from_data

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
    def string_from_data(self, data_element):
        """
        Converts the given data element into a string representation.

        :param data_element: object implementing
            :class:`everest.representers.interfaces.IExplicitDataElement`
        :returns: string representation (using the MIME content type
            configured for this representer)
        """
        stream = NativeIO()
        self.data_to_stream(data_element, stream)
        return stream.getvalue()
开发者ID:b8va,项目名称:everest,代码行数:14,代码来源:base.py

示例11: test_populate_no_params

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
    def test_populate_no_params(self):
        sys.argv[:] = ['ptah-populate', 'ptah.ini']

        stdout = sys.stdout
        out = NativeIO()
        sys.stdout = out

        populate.main()
        sys.stdout = stdout

        val = out.getvalue()

        self.assertIn(
            'usage: ptah-populate [-h] [-l] [-a] config [step [step ...]]', val)
开发者ID:carlicos,项目名称:ptah,代码行数:16,代码来源:test_populate.py

示例12: run

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
    def run(self):
        # print defaults
        if self.options.printcfg:
            data = config.get_cfg_storage(SETTINGS_OB_ID).export(True)

            parser = configparser.ConfigParser(dict_type=OrderedDict)
            for key, val in sorted(data.items()):
                parser.set(configparser.DEFAULTSECT,
                           key, val.replace('%', '%%'))

            fp = NativeIO()
            try:
                parser.write(fp)
            finally:
                pass

            print (fp.getvalue())
            return

        if self.options.all:
            section = ''
        else:
            section = self.options.section

        # print description
        groups = sorted(config.get_cfg_storage(ID_SETTINGS_GROUP).items(),
                        key = lambda item: item[1].__title__)

        for name, group in groups:
            if section and name != section:
                continue

            print ('')
            title = group.__title__ or name

            print (grpTitleWrap.fill('{0} ({1})'.format(title, name)))
            if group.__description__:
                print (grpDescriptionWrap.fill(
                    group.__description__))

            print ('')
            for node in group.__fields__.values():
                default = '<required>' if node.required else node.default
                print (nameWrap.fill(
                    ('%s.%s: %s (%s: %s)' % (
                        name, node.name, node.title,
                        node.__class__.__name__, default))))

                print (nameTitleWrap.fill(node.description))
                print ('')
开发者ID:carlicos,项目名称:ptah,代码行数:52,代码来源:settings.py

示例13: test_list_modules

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
    def test_list_modules(self):

        @ptah.manage.module('custom')
        class CustomModule(ptah.manage.PtahModule):
            """ Custom module description """

            title = 'Custom Module'

        self.init_ptah()

        sys.argv[1:] = ['--list-modules', 'ptah.ini']

        stdout = sys.stdout
        out = NativeIO()
        sys.stdout = out

        manage.main(False)
        sys.stdout = stdout

        val = out.getvalue()

        self.assertIn('* custom: Custom Module (disabled: False)', val)
        self.assertIn('Custom module description', val)

        # disable
        cfg = ptah.get_settings(ptah.CFG_ID_PTAH)
        cfg['disable_modules'] = ('custom',)

        out = NativeIO()
        sys.stdout = out

        manage.main(False)
        sys.stdout = stdout

        val = out.getvalue()

        self.assertIn('* custom: Custom Module (disabled: True)', val)
开发者ID:carlicos,项目名称:ptah,代码行数:39,代码来源:test_manage.py

示例14: test_manage_no_params

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
    def test_manage_no_params(self):
        self.init_ptah()

        sys.argv[:] = ['ptah-manage', 'ptah.ini']

        stdout = sys.stdout
        out = NativeIO()
        sys.stdout = out

        manage.main(False)
        sys.stdout = stdout

        val = out.getvalue()

        self.assertIn(
            '[-h] [--list-modules] [--list-models] config', val)
开发者ID:carlicos,项目名称:ptah,代码行数:18,代码来源:test_manage.py

示例15: test_no_params

# 需要导入模块: from pyramid.compat import NativeIO [as 别名]
# 或者: from pyramid.compat.NativeIO import getvalue [as 别名]
    def test_no_params(self, m_bs):
        m_bs.return_value = {
            'registry': self.registry, 'request': self.request}

        sys.argv[:] = ['amdjs', 'pyramid_amdjs.ini']

        stdout = sys.stdout
        out = NativeIO()
        sys.stdout = out

        amd.main()
        sys.stdout = stdout

        val = out.getvalue()

        self.assertIn('[-h] [-b] [-m] [--deps] [--no-min] config', val)
开发者ID:calwi,项目名称:pyramid_amdjs,代码行数:18,代码来源:test_script.py


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