python类TestApp()的实例源码

test_http_utils.py 文件源码 项目:captaincloud 作者: bpsagar 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_make_app(self):
        test = self.Test2(value=10)
        app = bottle_api.make_app(('/api', test))
        test_app = TestApp(app)

        params = {'arg1': 'test'}
        response = test_app.post(
            '/api/endpoint/', {'data': json.dumps(params)})
        expected_response = {
            'data': {'works': True, 'arg1': 'test', 'value': 10},
            'status': 'OK'
        }
        self.assertEqual(response.json, expected_response)

        params = {'arg1': 'error'}
        response = test_app.post(
            '/api/endpoint/', {'data': json.dumps(params)})
        expected_response = {
            'data': {},
            'status': 'ERROR'
        }
        self.assertEqual(response.json, expected_response)
cli.py 文件源码 项目:buttervolume 作者: anybox 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_from(resp, key):
    """get specified key from plugin response output
    """
    if resp is None:
        return False
    try:  # bottle
        content = resp.content
    except:  # TestApp
        content = resp.body
    if resp.status_code == 200:
        error = jsonloads(content)['Err']
        if error:
            log.error(error)
            return False
        return jsonloads(content).get(key)
    else:
        log.error('%s: %s', resp.status_code, resp.reason)
        return False
cli.py 文件源码 项目:buttervolume 作者: anybox 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def purge(args, test=False):
    urlpath = '/VolumeDriver.Snapshots.Purge'
    param = {'Name': args.name[0],
             'Pattern': args.pattern[0],
             'Dryrun': args.dryrun}
    if test:
        param['Test'] = True
        resp = TestApp(app).post(urlpath, json.dumps(param))
    else:
        resp = Session().post(
            'http+unix://{}{}'
            .format(urllib.parse.quote_plus(SOCKET), urlpath),
            json.dumps(param))
    res = get_from(resp, '')
    if res:
        print(res)
    return res
test_server_handlers.py 文件源码 项目:hdlcc 作者: suoto 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def setup():
        it.BUILDER_NAME = os.environ.get('BUILDER_NAME', None)
        it.BUILDER_PATH = os.environ.get('BUILDER_PATH', None)
        _logger.info("Builder name: %s", it.BUILDER_NAME)
        _logger.info("Builder path: %s", it.BUILDER_PATH)
        if it.BUILDER_NAME:
            it.PROJECT_FILE = p.join(VIM_HDL_EXAMPLES, it.BUILDER_NAME + '.prj')
        else:
            it.PROJECT_FILE = None

        if it.BUILDER_PATH:
            it.patch = mock.patch.dict(
                'os.environ',
                {'PATH' : os.pathsep.join([it.BUILDER_PATH, os.environ['PATH']])})
            it.patch.start()
        it.app = TestApp(handlers.app)
test_pyramid.py 文件源码 项目:dd-trace-py 作者: DataDog 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_tween_overriden():
    """ In case our tween is overriden by the user config we should not log
    rendering """
    from ...test_tracer import get_dummy_tracer
    from ...util import override_global_tracer
    tracer = get_dummy_tracer()
    with override_global_tracer(tracer):
        config = Configurator(settings={'pyramid.tweens': 'pyramid.tweens.excview_tween_factory'})
        trace_pyramid(config)

        def json(request):
            return {'a': 1}
        config.add_route('json', '/json')
        config.add_view(json, route_name='json', renderer='json')
        app = webtest.TestApp(config.make_wsgi_app())
        app.get('/json', status=200)
        spans = tracer.writer.pop()
        assert not spans
test_issue16.py 文件源码 项目:vishnu 作者: anomaly 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_app(backend):
    from webtest import TestApp
    from vishnu.middleware import SessionMiddleware
    from vishnu.session import Config

    api = falcon.API()
    api.add_route("/private", PrivateHandler())
    api.add_route("/public", PublicHandler())
    api.add_route("/login/save", LoginHandler())
    api.add_route("/logout", LogoutHandler())

    config = Config(
        secret="OVc1Mbt79AK5Pmi6sWnJnXZvEPNO3BnI",
        backend=backend
    )
    session = SessionMiddleware(api, config)

    return TestApp(app=session, extra_environ={'wsgi.url_scheme': 'https'})
base.py 文件源码 项目:pyramid_runner 作者: asif-mahmud 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def setUp(self):
        """Defines useful variables and initializes database.

        After this, following variables will be available-
            1. config: Application configuration
            2. engine: DB engine
            3. session: DB session instance
            4. test_app: Test WSGI app
        """
        settings = self.get_settings()
        app = services.main({}, **settings)
        self.test_app = webtest.TestApp(app=app)

        self.config = testing.setUp(settings=settings)

        self.engine = models.get_engine(settings)
        session_factory = models.get_session_factory(self.engine)

        self.session = models.get_tm_session(
            session_factory,
            transaction.manager
        )

        self.__init_database()
__init__.py 文件源码 项目:web 作者: pyjobs 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _get_initialized_app_context(parsed_args):
        """
        :param parsed_args: parsed args (eg. from take_action)
        :return: (wsgi_app, test_app)
        """
        config_file = parsed_args.config_file
        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgi_app = loadapp(config_name, relative_to=here_dir)
        test_app = TestApp(wsgi_app)

        # Make available the tg.request and other global variables
        tresponse = test_app.get('/_test_vars')

        return wsgi_app, test_app
test_redis.py 文件源码 项目:websauna 作者: websauna 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def app(request):
    """py.test fixture to set up a dummy app for Redis testing.

    :param request: pytest's FixtureRequest (internal class, cannot be hinted on a signature)
    """

    config = testing.setUp()
    config.add_route("home", "/")
    config.add_route("redis_test", "/redis_test")
    config.add_view(redis_test, route_name="redis_test")

    # same is in test.ini
    config.registry.settings["redis.sessions.url"] = "redis://localhost:6379/14"

    def teardown():
        testing.tearDown()

    config.registry.redis = create_redis(config.registry)

    app = TestApp(config.make_wsgi_app())
    return app
test_throttle.py 文件源码 项目:websauna 作者: websauna 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def throttle_app(request, paster_config):
    '''Custom WSGI app with permission test views enabled.'''

    class Initializer(websauna.system.Initializer):

        def configure_views(self):
            self.config.add_route("throttle_sample", "/")
            self.config.add_view(throttle_sample, route_name="throttle_sample", decorator=throttled_view(limit=1))

        def configure_csrf(self):
            """Disable CSRF for this test run for making testing simpler."""
            self.config.set_default_csrf_options(require_csrf=False)

    global_config, app_settings = paster_config
    init = Initializer(global_config, app_settings)
    init.run()
    app = TestApp(init.make_wsgi_app())
    app.init = init
    return app
test_throttle.py 文件源码 项目:websauna 作者: websauna 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_throttle(throttle_app: TestApp, test_request):
    """Throttling should give us 429."""

    app = throttle_app

    # clear counter from previous test run
    clear_throttle(test_request, "throttle_sample")

    app.get("/", status=200)

    # We exceeded the limit of 1 request per hour
    app.get("/", status=429)

    # Let's clear the counter
    clear_throttle(test_request, "throttle_sample")

    app.get("/", status=200)
test_viewconfig.py 文件源码 项目:websauna 作者: websauna 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def setup_wsgi():
    configurator = Configurator()

    configurator.include("pyramid_jinja2")
    configurator.add_jinja2_renderer('.html')
    configurator.add_jinja2_search_path('websauna.tests:templates/viewconfig', name='.html')

    configurator.add_route("parent_hello", "/parent_hello")
    configurator.add_route("child_hello", "/child_hello")

    from websauna.tests.viewconfig import testmodule
    configurator.set_root_factory(testmodule.Root)
    configurator.scan(testmodule)

    wsgi = TestApp(configurator.make_wsgi_app())
    return wsgi
tools.py 文件源码 项目:reahl 作者: reahl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def open(self, url_string, follow_redirects=True, **kwargs):
        """GETs the URL in `url_string`.

           :param url_string: A string containing the URL to be opened.
           :keyword follow_redirects: If False, this method acts as a simple GET request. If True (the default),
                                      the method hebaves like a browser would, by opening redirect responses.
           :keyword relative: Set to True to indicate that `url_string` contains a path relative to the current location.

           Other keyword arguments are passed directly on to 
           `WebTest.get <http://webtest.readthedocs.org/en/latest/api.html#webtest.app.TestApp.get>`_.
        """
        if self.last_response:
            self.history.append(self.last_response.request.url)
        relative = not url_string.startswith('/')
        if relative:
            url_string = self.get_full_path(url_string)
        self.last_response = self.testapp.get(url_string, **kwargs)
        if follow_redirects:
            self.follow_response()
test_secure.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def setUp(self):
        super(SecureControllerSharedPermissionsRegression, self).setUp()

        class Parent(object):
            @expose()
            def index(self):
                return 'hello'

        class UnsecuredChild(Parent):
            pass

        class SecureChild(Parent, SecureController):
            @classmethod
            def check_permissions(cls):
                return False

        class RootController(object):

            secured = SecureChild()
            unsecured = UnsecuredChild()

        self.app = TestApp(make_app(RootController()))
test_recursive.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def forward(app):
    app = TestApp(RecursiveMiddleware(app))
    res = app.get('')

    assert res.headers['content-type'] == 'text/plain'
    assert res.status == '200 OK'
    assert 'requested page returned' in res
    res = app.get('/error')
    assert res.headers['content-type'] == 'text/plain'
    assert res.status == '200 OK'
    assert 'Page not found' in res
    res = app.get('/not_found')
    assert res.headers['content-type'] == 'text/plain'
    assert res.status == '200 OK'
    assert 'Page not found' in res
    try:
        res = app.get('/recurse')
    except AssertionError as e:
        if str(e).startswith('Forwarding loop detected'):
            pass
        else:
            raise AssertionError('Failed to detect forwarding loop')
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def app_(self):
        class LookupController(object):
            def __init__(self, someID):
                self.someID = someID

            @expose()
            def index(self):
                return '/%s' % self.someID

            @expose()
            def name(self):
                return '/%s/name' % self.someID

        class RootController(object):
            @expose()
            def index(self):
                return '/'

            @expose()
            def _lookup(self, someID, *remainder):
                return LookupController(someID), remainder

        return TestApp(Pecan(RootController()))
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def app_(self):
        class LookupController(object):
            def __init__(self, someID):
                self.someID = someID

            @expose()
            def index(self):
                return self.someID

        class UserController(object):
            @expose()
            def _lookup(self, someID, *remainder):
                return LookupController(someID), remainder

        class RootController(object):
            users = UserController()

        return TestApp(Pecan(RootController()))
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def app_(self):
        class RootController(object):
            @expose()
            def index(self):
                redirect('/testing')

            @expose()
            def internal(self):
                redirect('/testing', internal=True)

            @expose()
            def bad_internal(self):
                redirect('/testing', internal=True, code=301)

            @expose()
            def permanent(self):
                redirect('/testing', code=301)

            @expose()
            def testing(self):
                return 'it worked!'

        return TestApp(make_app(RootController(), debug=False))
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_x_forward_proto(self):
        class ChildController(object):
            @expose()
            def index(self):
                redirect('/testing')  # pragma: nocover

        class RootController(object):
            @expose()
            def index(self):
                redirect('/testing')  # pragma: nocover

            @expose()
            def testing(self):
                return 'it worked!'  # pragma: nocover
            child = ChildController()

        app = TestApp(make_app(RootController(), debug=True))
        res = app.get(
            '/child', extra_environ=dict(HTTP_X_FORWARDED_PROTO='https')
        )
        # non-canonical url will redirect, so we won't get a 301
        assert res.status_int == 302
        # should add trailing / and changes location to https
        assert res.location == 'https://localhost/child/'
        assert res.request.environ['HTTP_X_FORWARDED_PROTO'] == 'https'
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def app_(self):
        class RootController(object):

            @expose()
            def redirect_with_context(self):
                request.context['foo'] = 'bar'
                redirect('/testing')

            @expose()
            def internal_with_context(self):
                request.context['foo'] = 'bar'
                redirect('/testing', internal=True)

            @expose('json')
            def testing(self):
                return request.context

        return TestApp(make_app(RootController(), debug=False))
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_thread_local_dir(self):
        """
        Threadlocal proxies for request and response should properly
        proxy ``dir()`` calls to the underlying webob class.
        """
        class RootController(object):
            @expose()
            def index(self):
                assert 'method' in dir(request)
                assert 'status' in dir(response)
                return '/'

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        assert r.body == b_('/')
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_request_state_cleanup(self):
        """
        After a request, the state local() should be totally clean
        except for state.app (so that objects don't leak between requests)
        """
        from pecan.core import state

        class RootController(object):
            @expose()
            def index(self):
                return '/'

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        assert r.body == b_('/')

        assert state.__dict__ == {}
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_kajiki(self):

        class RootController(object):
            @expose('kajiki:kajiki.html')
            def index(self, name='Jonathan'):
                return dict(name=name)

        app = TestApp(
            Pecan(RootController(), template_path=self.template_path)
        )
        r = app.get('/')
        assert r.status_int == 200
        assert b_("<h1>Hello, Jonathan!</h1>") in r.body

        r = app.get('/index.html?name=World')
        assert r.status_int == 200
        assert b_("<h1>Hello, World!</h1>") in r.body
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_renderer_not_found(self):

        class RootController(object):
            @expose('mako3:mako.html')
            def index(self, name='Jonathan'):
                return dict(name=name)

        app = TestApp(
            Pecan(RootController(), template_path=self.template_path)
        )
        try:
            r = app.get('/')
        except Exception as e:
            expected = e

        assert 'support for "mako3" was not found;' in str(expected)
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_json(self):
        try:
            from simplejson import loads
        except:
            from json import loads  # noqa

        expected_result = dict(
            name='Jonathan',
            age=30, nested=dict(works=True)
        )

        class RootController(object):
            @expose('json')
            def index(self):
                return expected_result

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        result = dict(loads(r.body.decode()))
        assert result == expected_result
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_alternate_route(self):

        class RootController(object):

            @expose(route='some-path')
            def some_path(self):
                return 'Hello, World!'

        app = TestApp(Pecan(RootController()))

        r = app.get('/some-path/')
        assert r.status_int == 200
        assert r.body == b_('Hello, World!')

        r = app.get('/some_path/', expect_errors=True)
        assert r.status_int == 404
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_manual_route(self):

        class SubController(object):

            @expose(route='some-path')
            def some_path(self):
                return 'Hello, World!'

        class RootController(object):
            pass

        route(RootController, 'some-controller', SubController())

        app = TestApp(Pecan(RootController()))

        r = app.get('/some-controller/some-path/')
        assert r.status_int == 200
        assert r.body == b_('Hello, World!')

        r = app.get('/some-controller/some_path/', expect_errors=True)
        assert r.status_int == 404
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_custom_route_with_attribute_conflict(self):

        class RootController(object):

            @expose(route='mock')
            def greet(self):
                return 'Hello, World!'

            @expose()
            def mock(self):
                return 'You are not worthy!'

        app = TestApp(Pecan(RootController()))

        self.assertRaises(
            RuntimeError,
            app.get,
            '/mock/'
        )
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_conflicting_custom_routes(self):

        class RootController(object):

            @expose(route='testing')
            def foo(self):
                return 'Foo!'

            @expose(route='testing')
            def bar(self):
                return 'Bar!'

        app = TestApp(Pecan(RootController()))

        self.assertRaises(
            RuntimeError,
            app.get,
            '/testing/'
        )
test_base.py 文件源码 项目:deb-python-pecan 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_conflicting_custom_routes_in_subclass(self):

        class BaseController(object):

            @expose(route='testing')
            def foo(self):
                return request.path

        class ChildController(BaseController):
            pass

        class RootController(BaseController):
            child = ChildController()

        app = TestApp(Pecan(RootController()))

        r = app.get('/testing/')
        assert r.body == b_('/testing/')

        r = app.get('/child/testing/')
        assert r.body == b_('/child/testing/')


问题


面经


文章

微信
公众号

扫码关注公众号