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


Python TestApp.request方法代码示例

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


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

示例1: TestDecorator

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestDecorator(unittest.TestCase):
    """
    Ensure the decorators are applied and route correctly
    """

    def setUp(self):
        """
        Start each test with a new Router instance
        """
        self.app = TestApp(router)

    def test_root_route(self):
        """
        WebTest a basic route
        """
        resp = self.app.get('/foo')

        self.assertEqual(resp.status_int, 200)
        self.assertEqual(resp.content_type, 'text/plain')
        self.assertIn('wor', resp)
        self.assertEqual(1, len(router.mapping))

    def test_route_not_found(self):
        """
        WebTest to make sure a route doesn't show up
        """
        resp = self.app.get('/bar', status=404)

        self.assertEqual(resp.status_int, 404)

    def test_method_not_allowed(self):
        """
        WebTest to check that method is not accepted
        """
        for method in ['HEAD', 'GET']:
            resp = self.app.request('/foo', method=method)
            self.assertEqual(resp.status_int, 200)
        
        for method in ['POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
                       'TRACE']:
            resp = self.app.request('/foo', method=method, status=405)
            self.assertEqual(resp.status_int, 405)

    @unittest.skip("WebTest does not support HTTP 501 NOT IMPLEMENTED yet")
    def test_not_implemented(self):
        """
        WebTest to check response returns 'NOT IMPLEMENTED' on
        unrecognized methods
        """
        resp = self.app.request('/foo', method='HERPS', status=501)
        self.assertEqual(resp.status_int, 501)
开发者ID:bramwelt,项目名称:aragog,代码行数:53,代码来源:test_routing.py

示例2: test_bad_rest

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
    def test_bad_rest(self):

        class ThingsController(RestController):
            pass

        class RootController(object):
            things = ThingsController()

        # create the app
        app = TestApp(make_app(RootController()))

        # test get_all
        r = app.get('/things', status=404)
        assert r.status_int == 404

        # test get_one
        r = app.get('/things/1', status=404)
        assert r.status_int == 404

        # test post
        r = app.post('/things', {'value': 'one'}, status=404)
        assert r.status_int == 404

        # test edit
        r = app.get('/things/1/edit', status=404)
        assert r.status_int == 404

        # test put
        r = app.put('/things/1', {'value': 'ONE'}, status=404)

        # test put with _method parameter and GET
        r = app.get('/things/1?_method=put', {'value': 'ONE!'}, status=405)
        assert r.status_int == 405

        # test put with _method parameter and POST
        r = app.post('/things/1?_method=put', {'value': 'ONE!'}, status=404)
        assert r.status_int == 404

        # test get delete
        r = app.get('/things/1/delete', status=404)
        assert r.status_int == 404

        # test delete
        r = app.delete('/things/1', status=404)
        assert r.status_int == 404

        # test delete with _method parameter and GET
        r = app.get('/things/1?_method=DELETE', status=405)
        assert r.status_int == 405

        # test delete with _method parameter and POST
        r = app.post('/things/1?_method=DELETE', status=404)
        assert r.status_int == 404

        # test "RESET" custom action
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = app.request('/things', method='RESET', status=404)
            assert r.status_int == 404
开发者ID:alex-devops,项目名称:pecan,代码行数:61,代码来源:test_rest.py

示例3: TestTASRAppClient

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestTASRAppClient(TASRTestCase):
    '''
    This is a wrapper class to encapsulate the route_to_testapp method,
    allowing us to use both httmock (in the test) and requests (in the client).
    '''

    def setUp(self):
        self.app = APP
        self.tasr = TestApp(APP)

    @httmock.urlmatch(netloc=HOST_PORT)
    def route_to_testapp(self, url, requests_req):
        '''This is some tricky stuff.  To test the client methods, we need the
        responses package calls to route to our webtest TestApp WSGI wrapper.
        We use httmock to intercept the requests call, then we handle
        processing in this function instead -- calling the TestApp wrapper.
        '''
        if url.geturl() != requests_req.url:
            logging.warn('%s != %s', url.geturl(), requests_req.url)
        # create a webtest TestRequest from the requests PreparedRequest
        webtest_req = TestRequest.blank(requests_req.url,
                                        method=requests_req.method,
                                        body=requests_req.body,
                                        headers=requests_req.headers)

        # have the TestApp wrapper process the TestRequest
        webtest_resp = self.tasr.request(webtest_req)

        '''webtest responses support multiple headers with the same key, while
        the requests package holds them in a case-insensitive dict of lists of
        (key,value) tuples.  We need to translate by hand here to keep cases
        with multiple headers with the same key
        '''
        headers = HTTPHeaderDict()
        for key, value in webtest_resp.headers.iteritems():
            headers.add(key, value)

        # use the webtest TestResponse to build a new requests HTTPResponse
        requests_http_resp = HTTPResponse(body=webtest_resp.body,
                                           headers=headers,
                                           status=webtest_resp.status_code)

        # get an HTTPAdaptor, then use it to build the requests Response object
        adap = requests.adapters.HTTPAdapter()
        requests_resp = adap.build_response(requests_req, requests_http_resp)

        '''For some reason, we need to explicitly set the _content attribute
        after the response object is built -- it is already in there as
        raw.data, but it doesn't make it to _content, so it never hits
        content() without this intervention.
        '''
        requests_resp._content = webtest_resp.body
        return requests_resp
开发者ID:ifwe,项目名称:tasr,代码行数:55,代码来源:client_test.py

示例4: TestLoginController

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestLoginController(TestController):
    def setUp(self):
        self.app = TestApp("config:test.ini", relative_to="/Users/tonky/projects/Croner")

    def tearDown(self):
        pass

    def test_login_index(self):
        response = self.app.get(url(controller='login'))
        ok_('Login' in response.body)

    def test_bad_password(self):
        response = self.app.request("/login/save", POST={'login': 'joe', 'password': '2'})

        ok_('wrong' in response.body)

    def test_do_login(self):
        response = self.app.request("/login/save", POST={'login': 'joe', 'password': '1'})

        eq_(response.status, "302 Found")
        home = response.follow()
        ok_('Welcome, Joe!' in home.body)
开发者ID:tonky,项目名称:croner,代码行数:24,代码来源:test_login.py

示例5: TestJWTAuthenticationPolicy_with_RSA

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestJWTAuthenticationPolicy_with_RSA(unittest.TestCase):
    """Testcases for the JWTAuthenticationPolicy class."""

    def setUp(self):
        self.config = Configurator(settings={
          "jwtauth.private_key_file": 'pyramid_jwtauth/tests/testkey',
          "jwtauth.public_key_file": 'pyramid_jwtauth/tests/testkey.pub',
          "jwtauth.algorithm": "RS256",
        })
        self.config.include("pyramid_jwtauth")
        self.config.add_route("public", "/public")
        self.config.add_view(stub_view_public, route_name="public")
        self.config.add_route("auth", "/auth")
        self.config.add_view(stub_view_auth, route_name="auth")
        self.config.add_route("groups", "/groups")
        self.config.add_view(stub_view_groups, route_name="groups")
        self.app = TestApp(self.config.make_wsgi_app())
        self.policy = self.config.registry.queryUtility(IAuthenticationPolicy)

    def _make_request(self, *args, **kwds):
        return make_request(self.config, *args, **kwds)

    def test_from_settings_with_RSA_public_private_key(self):
        self.assertEqual(self.policy.algorithm, 'RS256')
        self.assertEqual(self.policy.master_secret, None)
        # from Crypto.PublicKey import RSA
        with open('pyramid_jwtauth/tests/testkey', 'r') as rsa_priv_file:
            private_key = rsa_priv_file.read()
            self.assertEqual(self.policy.private_key, private_key)
        with open('pyramid_jwtauth/tests/testkey.pub', 'r') as rsa_pub_file:
            public_key = rsa_pub_file.read()
            self. assertEqual(self.policy.public_key, public_key)

        self.assertNotEqual(private_key, public_key)
        req = self._make_request("/auth")
        claims = make_claims(userid="[email protected]")
        jwt_authenticate_request(req, claims, private_key, 'RS256')

        token = pyramid_jwtauth.utils.parse_authz_header(req)["token"]
        userid = self.policy.authenticated_userid(req)
        self.assertEqual(userid, "[email protected]")

        import jwt
        payload = jwt.decode(token, key=public_key, verify=True)
        self.assertIn('sub', payload)
        self.assertEqual(payload['sub'], "[email protected]")

        r = self.app.request(req)
        self.assertEqual(r.body, b"[email protected]")
开发者ID:circlingthesun,项目名称:pyramid_jwtauth,代码行数:51,代码来源:test_jwtauth.py

示例6: test_basic_rest

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]

#.........这里部分代码省略.........
        assert r.status_int == 200
        assert r.body == b_('DELETE FOUR!')

        # test delete
        r = app.delete('/things/4')
        assert r.status_int == 200
        assert r.body == b_('DELETED')

        # make sure it works
        r = app.get('/things')
        assert r.status_int == 200
        assert len(loads(r.body.decode())['items']) == 4

        # test delete with _method parameter and GET
        r = app.get('/things/3?_method=DELETE', status=405)
        assert r.status_int == 405

        # make sure it works
        r = app.get('/things')
        assert r.status_int == 200
        assert len(loads(r.body.decode())['items']) == 4

        # test delete with _method parameter and POST
        r = app.post('/things/3?_method=DELETE')
        assert r.status_int == 200
        assert r.body == b_('DELETED')

        # make sure it works
        r = app.get('/things')
        assert r.status_int == 200
        assert len(loads(r.body.decode())['items']) == 3

        # test "RESET" custom action
        r = app.request('/things', method='RESET')
        assert r.status_int == 200
        assert r.body == b_('RESET')

        # test "RESET" custom action with _method parameter
        r = app.get('/things?_method=RESET')
        assert r.status_int == 200
        assert r.body == b_('RESET')

        # test the "OPTIONS" custom action
        r = app.request('/things', method='OPTIONS')
        assert r.status_int == 200
        assert r.body == b_('OPTIONS')

        # test the "OPTIONS" custom action with the _method parameter
        r = app.post('/things', {'_method': 'OPTIONS'})
        assert r.status_int == 200
        assert r.body == b_('OPTIONS')

        # test the "other" custom action
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = app.request('/things/other', method='MISC', status=405)
            assert r.status_int == 405

        # test the "other" custom action with the _method parameter
        r = app.post('/things/other', {'_method': 'MISC'}, status=405)
        assert r.status_int == 405

        # test the "others" custom action
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = app.request('/things/others/', method='MISC')
开发者ID:alex-devops,项目名称:pecan,代码行数:70,代码来源:test_rest.py

示例7: TestController

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]

#.........这里部分代码省略.........
        self.assertEqual(res.headers['x-account-bytes-used'], '40')
        self.assertEqual(res.headers['x-account-container-count'], '10')
        self.assertEqual(res.headers['x-account-object-count'], '2')
        self.assertEqual(body, res.body)

    def test_14_REQUEST_merge_GET_account_with_marker(self):
        """ relay to get account (container listing) in merge mode with marker param. """
        res = self.app.get('/both/v1.0/AUTH_test?marker=hoge:TEST2', headers=dict(X_Auth_Token='[email protected]@__v'))
        body = 'hoge:TEST3\nhoge:TEST4'
        print res.body
        print res.headers
        self.assertEqual(body, res.body)

    def test_15_REQUEST_merge_GET_container(self):
        """ relay to get container (object listing) in merge mode. """
        res = self.app.get('/both/v1.0/AUTH_test/hoge:TEST0', headers=dict(X_Auth_Token='[email protected]@__v'), expect_errors=True)
        body = 'test0.txt\ntest1.txt\ntest2.txt\ntest2.txt\ntest4.txt'
        #print self.app.app.debug
        print res.status
        print res.body
        print res.headers
        print proxy0_srv.env
        print proxy1_srv.env
        self.assertEqual(body, res.body)

    def test_16_REQUEST_merge_GET_object(self):
        """ relay to get object in merge mode. """
        res = self.app.get('/both/v1.0/AUTH_test/hoge:TEST0/test0.txt', headers=dict(X_Auth_Token='[email protected]@__v'), expect_errors=True)
        body = 'This is a test0.\nOK?'
        self.assertEqual(body, res.body)

    def test_17_REQUEST_merge_COPY_object_in_same_account(self):
        """ relay to copy object in the same account. """
        res = self.app.request('/both/v1.0/AUTH_test/hoge:TEST1/copied_test0.txt', method='PUT', body='',
                               headers={'X_Auth_Token': '[email protected]@__v',
                                        'X_Copy_From': '/hoge:TEST0/test0.txt'},
                               expect_errors=True)
        print res.status
        print res.body
        self.assertEqual(proxy0_srv.env['CONTENT_LENGTH'], '0')
        self.assertEqual(proxy0_srv.env['PATH_INFO'], '/v1.0/AUTH_test/TEST1/copied_test0.txt')
        self.assertEqual(proxy0_srv.env['HTTP_X_COPY_FROM'], '/TEST0/test0.txt')
    
    def test_18_REQUEST_merge_COPY_object_across_accounts(self):
        """ relay to copy object across accounts. """
        res = self.app.request('/both/v1.0/AUTH_test/gere:TEST1/copied_test0.txt', method='PUT', body='',
                               headers={'X_Auth_Token': '[email protected]@__v',
                                        'X_Copy_From': '/hoge:TEST0/test0.txt'},
                               expect_errors=True)
        print proxy0_srv.env
        print proxy0_srv.env['REQUEST_METHOD']
        print proxy0_srv.env['PATH_INFO']
        print proxy1_srv.env
        print proxy1_srv.env['REQUEST_METHOD']
        print proxy1_srv.env['PATH_INFO']
        self.assertEqual(proxy0_srv.env['SERVER_NAME'], '127.0.0.1')
        self.assertEqual(proxy0_srv.env['SERVER_PORT'], '8080')
        self.assertEqual(proxy0_srv.env['REQUEST_METHOD'], 'GET')
        self.assertEqual(proxy0_srv.env['PATH_INFO'], '/v1.0/AUTH_test/TEST0/test0.txt')
        self.assertEqual(proxy1_srv.env['SERVER_NAME'], '127.0.0.1')
        self.assertEqual(proxy1_srv.env['SERVER_PORT'], '18080')
        self.assertEqual(proxy1_srv.env['REQUEST_METHOD'], 'PUT')
        self.assertEqual(proxy1_srv.env['PATH_INFO'], '/v1.0/AUTH_test/TEST1/copied_test0.txt')
        res = self.app.get('/both/v1.0/AUTH_test/gere:TEST1/copied_test0.txt', headers=dict(X_Auth_Token='[email protected]@__v'), expect_errors=True)
        body = 'This is a test0.\nOK?'
        print res.body
开发者ID:AsherBond,项目名称:colony,代码行数:70,代码来源:test_dispatcher.py

示例8: TestTASRTopicApp

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestTASRTopicApp(TASRTestCase):
    '''These tests check that the TASR native REST API (including the get by ID
    calls) are working as expected.  This does not check the S+V API calls.
    '''

    def setUp(self):
        self.event_type = "gold"
        fix_rel_path = "schemas/%s.avsc" % (self.event_type)
        self.avsc_file = TASRTestCase.get_fixture_file(fix_rel_path, "r")
        self.schema_str = self.avsc_file.read()
        self.tasr_app = TestApp(APP)
        self.url_prefix = 'http://%s:%s/tasr' % (APP.config.host,
                                                 APP.config.port)
        self.topic_url = '%s/topic/%s' % (self.url_prefix, self.event_type)
        self.content_type = 'application/json; charset=utf8'
        # clear out all the keys before beginning -- careful!
        APP.ASR.redis.flushdb()

    def tearDown(self):
        # this clears out redis after each test -- careful!
        APP.ASR.redis.flushdb()

    def abort_diff_status(self, resp, code):
        self.assertEqual(code, resp.status_code,
                         u'Non-%s status code: %s' % (code, resp.status_code))

    def register_schema(self, schema_str, expect_errors=False):
        return self.tasr_app.request(self.topic_url, method='PUT',
                                     expect_errors=expect_errors,
                                     content_type=self.content_type,
                                     body=schema_str)

    def test_get_all_topics(self):
        '''GET /tasr/topic - as expected'''
        # reg two vers for target topic and one for an alt topic
        self.register_schema(self.schema_str)
        schema_str_2 = self.schema_str.replace('tagged.events',
                                               'tagged.events.alt', 1)
        self.register_schema(schema_str_2)
        alt_topic = 'bob'
        alt_url = '%s/topic/%s' % (self.url_prefix, alt_topic)
        self.tasr_app.request(alt_url, method='PUT',
                              content_type=self.content_type,
                              body=self.schema_str)
        # now get all with versions and check the headers
        url = "%s/topic" % (self.url_prefix)
        resp = self.tasr_app.request(url, method='GET')
        self.abort_diff_status(resp, 200)
        # we expect a list of SubjectMetadata objects here
        meta_dict = SubjectHeaderBot.extract_metadata(resp)
        self.assertEqual(2, meta_dict[self.event_type].current_version,
                         'bad ver')
        self.assertEqual(1, meta_dict[alt_topic].current_version, 'bad ver')
        # lastly check the body
        buff = StringIO.StringIO(resp.body)
        group_names = []
        for topic_line in buff:
            group_names.append(topic_line.strip())
        buff.close()
        self.assertListEqual(sorted(group_names), sorted(meta_dict.keys()),
                             'Expected group_names in body to match headers.')

    def test_register_schema(self):
        '''PUT /tasr/topic/<topic name> - as expected'''
        resp = self.register_schema(self.schema_str)
        self.abort_diff_status(resp, 201)
        smeta = SchemaHeaderBot.extract_metadata(resp)
        self.assertIn(self.event_type, smeta.group_names, 'event_type missing')
        self.assertEqual(1, smeta.group_version(self.event_type), 'bad ver')
        self.assertTrue(smeta.group_timestamp(self.event_type), 'missing ts')

    def test_reg_fail_on_empty_schema(self):
        '''PUT /tasr/topic/<topic name> - empty schema'''
        resp = self.register_schema(None, expect_errors=True)
        self.abort_diff_status(resp, 400)

    def test_reg_fail_on_invalid_schema(self):
        '''PUT /tasr/topic/<topic name> - bad schema'''
        bad_schema_str = "%s }" % self.schema_str
        resp = self.register_schema(bad_schema_str, expect_errors=True)
        self.abort_diff_status(resp, 400)

    def test_reg_fail_on_bad_content_type(self):
        '''PUT /tasr/topic/<topic name> - bad Content-Type'''
        resp = self.tasr_app.request(self.topic_url, method='PUT',
                                     content_type='text/plain; charset=utf8',
                                     expect_errors=True,
                                     body=self.schema_str)
        self.abort_diff_status(resp, 406)

    def test_reg_and_rereg(self):
        '''PUT /tasr/topic/<topic name> - multiple calls, same schema'''
        resp = self.register_schema(self.schema_str)
        self.abort_diff_status(resp, 201)
        smeta = SchemaHeaderBot.extract_metadata(resp)
        self.assertEqual(1, smeta.group_version(self.event_type), 'bad ver')

        # on the re-registration, we should get the same version back
        resp2 = self.register_schema(self.schema_str)
        self.abort_diff_status(resp2, 200)
#.........这里部分代码省略.........
开发者ID:ifwe,项目名称:tasr,代码行数:103,代码来源:test_app_topic.py

示例9: TestVEPAuthPlugin

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestVEPAuthPlugin(unittest2.TestCase):
    """Testcases for the main VEPAuthPlugin class."""

    def setUp(self):
        self.plugin = VEPAuthPlugin(
            audiences=["localhost"], verifier=vep.DummyVerifier(), token_manager=StubTokenManager()
        )
        application = PluggableAuthenticationMiddleware(
            stub_application,
            [["vep", self.plugin]],
            [["vep", self.plugin]],
            [["vep", self.plugin]],
            [],
            stub_request_classifier,
            stub_challenge_decider,
        )
        self.app = TestApp(application)

    def _make_assertion(self, address, audience="http://localhost", **kwds):
        return vep.DummyVerifier.make_assertion(address, audience, **kwds)

    def _start_session(self, email="[email protected]", *args, **kwds):
        assertion = self._make_assertion(email, *args, **kwds)
        headers = {"Authorization": "Browser-ID " + assertion}
        session = self.app.get(self.plugin.token_url, headers=headers).json
        return {"token": session["id"], "secret": session["key"]}

    def test_implements(self):
        verifyClass(IIdentifier, VEPAuthPlugin)
        verifyClass(IAuthenticator, VEPAuthPlugin)
        verifyClass(IChallenger, VEPAuthPlugin)

    def test_make_plugin_can_explicitly_set_all_properties(self):
        plugin = make_plugin(
            audiences="example.com",
            token_url="/test_token_url",
            verifier="vep:DummyVerifier",
            token_manager="vep:LocalVerifier",
            nonce_timeout=42,
        )
        self.assertEquals(plugin.audiences, ["example.com"])
        self.assertEquals(plugin.token_url, "/test_token_url")
        self.assertTrue(isinstance(plugin.verifier, vep.DummyVerifier))
        self.assertTrue(isinstance(plugin.token_manager, vep.LocalVerifier))
        self.assertEquals(plugin.nonce_timeout, 42)

    def test_make_plugin_produces_sensible_defaults(self):
        # The "audiences" parameter must be set explicitly
        self.assertRaises(ValueError, make_plugin)
        plugin = make_plugin("one two")
        self.assertEquals(plugin.audiences, ["one", "two"])
        self.assertEquals(plugin.token_url, "/request_token")
        self.assertTrue(isinstance(plugin.verifier, vep.RemoteVerifier))
        self.assertTrue(isinstance(plugin.token_manager, SignedTokenManager))
        self.assertEquals(plugin.nonce_timeout, 60)

    def test_make_plugin_loads_urlopen_from_dotted_name(self):
        plugin = make_plugin("one two", verifier="vep:LocalVerifier", verifier_urlopen="urllib2:urlopen")
        self.assertEquals(plugin.audiences, ["one", "two"])
        self.assertTrue(isinstance(plugin.verifier, vep.LocalVerifier))
        self.assertEquals(plugin.verifier.urlopen, urllib2.urlopen)

    def test_make_plugin_treats_empty_audiences_string_as_none(self):
        plugin = make_plugin("")
        self.assertEquals(plugin.audiences, None)
        plugin = make_plugin(" ")
        self.assertEquals(plugin.audiences, [])

    def test_make_plugin_errors_out_on_unexpected_keyword_args(self):
        self.assertRaises(TypeError, make_plugin, "", unexpected="spanish-inquisition")

    def test_make_plugin_errors_out_on_args_to_a_non_callable(self):
        self.assertRaises(ValueError, make_plugin, "", verifier="vep:__doc__", verifier_urlopen="urllib2:urlopen")

    def test_checking_for_silly_argument_errors(self):
        self.assertRaises(ValueError, VEPAuthPlugin, audiences="notalist")

    def test_remember_does_nothing(self):
        self.assertEquals(self.plugin.remember(make_environ(), {}), [])

    def test_forget_gives_a_challenge_header(self):
        headers = self.plugin.forget(make_environ(), {})
        self.assertEquals(len(headers), 1)
        self.assertEquals(headers[0][0], "WWW-Authenticate")
        self.assertTrue(headers[0][1].startswith("MAC+BrowserID "))
        self.assertTrue(self.plugin.token_url in headers[0][1])

    def test_unauthenticated_requests_get_a_challenge(self):
        # Requests to most URLs generate a 401, which is passed through
        # with the appropriate challenge.
        r = self.app.get("/", status=401)
        challenge = r.headers["WWW-Authenticate"]
        self.assertTrue(challenge.startswith("MAC+BrowserID"))
        self.assertTrue(self.plugin.token_url in challenge)
        # Requests to URLs with "forbidden" generate a 403 in the downstream
        # app, which should be converted into a 401 by the plugin.
        r = self.app.get("/forbidden", status=401)
        challenge = r.headers["WWW-Authenticate"]
        self.assertTrue(challenge.startswith("MAC+BrowserID"))
        self.assertTrue(self.plugin.token_url in challenge)
#.........这里部分代码省略.........
开发者ID:mozilla-services,项目名称:repoze.who.plugins.vepauth,代码行数:103,代码来源:test_plugin.py

示例10: TestJWTAuthenticationPolicy

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestJWTAuthenticationPolicy(unittest.TestCase):
    """Testcases for the JWTAuthenticationPolicy class."""

    def setUp(self):
        self.config = Configurator(settings={
            "jwtauth.find_groups": "pyramid_jwtauth.tests.test_jwtauth:stub_find_groups",
            "jwtauth.master_secret": MASTER_SECRET,
        })
        self.config.include("pyramid_jwtauth")
        self.config.add_route("public", "/public")
        self.config.add_view(stub_view_public, route_name="public")
        self.config.add_route("auth", "/auth")
        self.config.add_view(stub_view_auth, route_name="auth")
        self.config.add_route("groups", "/groups")
        self.config.add_view(stub_view_groups, route_name="groups")
        self.app = TestApp(self.config.make_wsgi_app())
        self.policy = self.config.registry.queryUtility(IAuthenticationPolicy)

    def _make_request(self, *args, **kwds):
        return make_request(self.config, *args, **kwds)

    # create an authenticated request that has a JWT with the userid set
    # in our case, this is the 'sub' request.
    #
    # we need to have the following claims as a minimum:
    # 'sub': the userid that we want to authenticate - it can be anything.
    # 'iat': the issued at time stamp
    # 'nbf': the not before time stamp
    # 'exp': the expiry time for the JWT
    def _make_authenticated_request(self, userid, *args, **kwds):
        claims = None
        if 'claims' in kwds:
            claims = kwds['claims']
            del kwds['claims']
        req = self._make_request(*args, **kwds)
        # creds = self._get_credentials(req, userid=userid)
        claims = make_claims(userid=userid, claims=claims)
        # jwt_authenticate_request(req, **creds)
        # note jwt_authenticate_request() returns headers if wanted
        jwt_authenticate_request(req, claims, MASTER_SECRET)
        return req

    def test_the_class_implements_auth_policy_interface(self):
        verifyClass(IAuthenticationPolicy, JWTAuthenticationPolicy)

    def test_from_settings_can_explicitly_set_all_properties(self):
        policy = JWTAuthenticationPolicy.from_settings({
          "jwtauth.find_groups": "pyramid_jwtauth.tests.test_jwtauth:stub_find_groups",
          "jwtauth.master_secret": MASTER_SECRET,
          # "jwtauth.decode_mac_id": "pyramid_macauth.tests:stub_decode_mac_id",
          # "jwtauth.encode_mac_id": "pyramid_macauth.tests:stub_encode_mac_id",
        })
        self.assertEqual(policy.find_groups, stub_find_groups)
        self.assertEqual(policy.master_secret, MASTER_SECRET)
        # self.assertTrue(isinstance(policy.nonce_cache, macauthlib.NonceCache))
        # self.assertEqual(policy.decode_mac_id, stub_decode_mac_id)
        # self.assertEqual(policy.encode_mac_id, stub_encode_mac_id)

    # def test_from_settings_passes_on_args_to_nonce_cache(self):
    #     policy = MACAuthenticationPolicy.from_settings({
    #       "macauth.nonce_cache": "macauthlib:NonceCache",
    #       "macauth.nonce_cache_nonce_ttl": 42,
    #     })
    #     self.assertTrue(isinstance(policy.nonce_cache, macauthlib.NonceCache))
    #     self.assertEqual(policy.nonce_cache.nonce_ttl, 42)
    #     self.assertRaises(TypeError, MACAuthenticationPolicy.from_settings, {
    #       "macauth.nonce_cache": "macauthlib:NonceCache",
    #       "macauth.nonce_cache_invalid_arg": "WHAWHAWHAWHA",
    #     })

    def test_from_settings_errors_out_on_unexpected_keyword_args(self):
        self.assertRaises(ValueError, JWTAuthenticationPolicy.from_settings, {
          "jwtauth.unexpected": "spanish-inquisition",
        })

    # def test_from_settings_errors_out_on_args_to_a_non_callable(self):
    #     self.assertRaises(ValueError, MACAuthenticationPolicy.from_settings, {
    #       "macauth.nonce_cache": "pyramid_macauth.tests:stub_non_callable",
    #       "macauth.nonce_cache_arg": "invalidarg",
    #     })

    # def test_from_settings_errors_out_if_decode_mac_id_is_not_callable(self):
    #     self.assertRaises(ValueError, MACAuthenticationPolicy.from_settings, {
    #       "macauth.decode_mac_id": "pyramid_macauth.tests:stub_non_callable",
    #     })

    # def test_from_settings_errors_out_if_encode_mac_id_is_not_callable(self):
    #     self.assertRaises(ValueError, MACAuthenticationPolicy.from_settings, {
    #       "macauth.encode_mac_id": "pyramid_macauth.tests:stub_non_callable",
    #     })

    def test_from_settings_produces_sensible_defaults(self):
        policy = JWTAuthenticationPolicy.from_settings({})
        # Using __code__ here is a Py2/Py3 compatible way of checking
        # that a bound and unbound method point to the same function object.
        self.assertEqual(policy.find_groups.__code__,
                          JWTAuthenticationPolicy.find_groups.__code__)

    # def test_from_settings_curries_args_to_decode_mac_id(self):
    #     policy = MACAuthenticationPolicy.from_settings({
#.........这里部分代码省略.........
开发者ID:circlingthesun,项目名称:pyramid_jwtauth,代码行数:103,代码来源:test_jwtauth.py

示例11: TestHawkAuthPlugin

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestHawkAuthPlugin(unittest.TestCase):
    """Testcases for the main HawkAuthPlugin class."""

    def setUp(self):
        self.plugin = HawkAuthPlugin()
        application = PluggableAuthenticationMiddleware(stub_application,
                                    [["hawk", self.plugin]],
                                    [["hawk", self.plugin]],
                                    [["hawk", self.plugin]],
                                    [],
                                    stub_request_classifier,
                                    stub_challenge_decider)
        self.app = TestApp(application)

    def _get_credentials(self, **data):
        id, key = self.plugin.encode_hawk_id(Request.blank("/"), data)
        return {"id": id, "key": key}

    def test_implements(self):
        verifyClass(IIdentifier, HawkAuthPlugin)
        verifyClass(IAuthenticator, HawkAuthPlugin)
        verifyClass(IChallenger, HawkAuthPlugin)

    def test_make_plugin_can_explicitly_set_all_properties(self):
        plugin = make_plugin(
            master_secret="elvislives",
            nonce_cache="hawkauthlib:NonceCache",
            decode_hawk_id=dotted_name("stub_decode_hawk_id"),
            encode_hawk_id=dotted_name("stub_encode_hawk_id"))
        self.assertEquals(plugin.master_secret, "elvislives")
        self.assertTrue(isinstance(plugin.nonce_cache, hawkauthlib.NonceCache))
        self.assertEquals(plugin.decode_hawk_id, stub_decode_hawk_id)
        self.assertEquals(plugin.encode_hawk_id, stub_encode_hawk_id)

    def test_make_plugin_passes_on_args_to_nonce_cache(self):
        plugin = make_plugin(
            nonce_cache="hawkauthlib:NonceCache",
            nonce_cache_window=42)
        self.assertTrue(isinstance(plugin.nonce_cache, hawkauthlib.NonceCache))
        self.assertEquals(plugin.nonce_cache.window, 42)
        self.assertRaises(TypeError, make_plugin,
            nonce_cache="hawkauthlib:NonceCache",
            nonce_cache_invalid_arg="WHAWHAWHAWHA")

    def test_make_plugin_errors_out_on_unexpected_keyword_args(self):
        self.assertRaises(TypeError, make_plugin,
                                     unexpected="spanish-inquisition")

    def test_make_plugin_errors_out_on_args_to_a_non_callable(self):
        self.assertRaises(ValueError, make_plugin,
                                      nonce_cache=dotted_name("unittest"),
                                      nonce_cache_arg="invalidarg")

    def test_make_plugin_errors_out_if_decode_hawk_id_is_not_callable(self):
        self.assertRaises(ValueError, make_plugin,
                                      decode_hawk_id=dotted_name("unittest"))

    def test_make_plugin_produces_sensible_defaults(self):
        plugin = make_plugin()
        self.assertEquals(plugin.decode_hawk_id.im_func,
                          HawkAuthPlugin.decode_hawk_id.im_func)
        self.assertTrue(isinstance(plugin.nonce_cache, hawkauthlib.NonceCache))

    def test_make_plugin_curries_args_to_decode_hawk_id(self):
        plugin = make_plugin(
            decode_hawk_id=dotted_name("stub_decode_hawk_id"),
            decode_hawk_id_hello="hi")
        self.assertEquals(plugin.decode_hawk_id(None, "id")[0], "id")
        self.assertEquals(plugin.decode_hawk_id(None, "id")[1]["hello"], "hi")

    def test_remember_does_nothing(self):
        self.assertEquals(self.plugin.remember(make_environ(), {}), [])

    def test_forget_gives_a_challenge_header(self):
        headers = self.plugin.forget(make_environ(), {})
        self.assertEquals(len(headers), 1)
        self.assertEquals(headers[0][0], "WWW-Authenticate")
        self.assertTrue(headers[0][1] == "Hawk")

    def test_unauthenticated_requests_get_a_challenge(self):
        # Requests to most URLs generate a 401, which is passed through
        # with the appropriate challenge.
        r = self.app.get("/", status=401)
        challenge = r.headers["WWW-Authenticate"]
        self.assertTrue(challenge.startswith("Hawk"))
        # Requests to URLs with "forbidden" generate a 403 in the downstream
        # app, which should be converted into a 401 by the plugin.
        r = self.app.get("/forbidden", status=401)
        challenge = r.headers["WWW-Authenticate"]
        self.assertTrue(challenge.startswith("Hawk"))

    def test_authenticated_request_works(self):
        creds = self._get_credentials(username="[email protected]")
        req = Request.blank("/")
        hawkauthlib.sign_request(req, **creds)
        r = self.app.request(req)
        self.assertEquals(r.body, "[email protected]")

    def test_authentication_fails_when_hawkid_has_no_userid(self):
        creds = self._get_credentials(hello="world")
#.........这里部分代码省略.........
开发者ID:mozilla-services,项目名称:repoze.who.plugins.hawkauth,代码行数:103,代码来源:tests.py

示例12: TestTASRCoreApp

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestTASRCoreApp(TASRTestCase):
    '''These tests check that the TASR core app endpoints work.'''

    def setUp(self):
        self.event_type = "gold"
        fix_rel_path = "schemas/%s.avsc" % (self.event_type)
        self.avsc_file = TASRTestCase.get_fixture_file(fix_rel_path, "r")
        self.schema_str = self.avsc_file.read()
        self.tasr_app = TestApp(APP)
        self.url_prefix = 'http://%s:%s/tasr' % (APP.config.host,
                                                 APP.config.port)
        self.subject_url = '%s/subject/%s' % (self.url_prefix, self.event_type)
        self.content_type = 'application/json; charset=utf8'
        # clear out all the keys before beginning -- careful!
        APP.ASR.redis.flushdb()

    def tearDown(self):
        # this clears out redis after each test -- careful!
        APP.ASR.redis.flushdb()

    def abort_diff_status(self, resp, code):
        self.assertEqual(code, resp.status_code,
                         u'Non-%s status code: %s' % (code, resp.status_code))

    def register_subject(self, subject_name):
        url = '%s/subject/%s' % (self.url_prefix, subject_name)
        return self.tasr_app.put(url, {'subject_name': subject_name})

    def register_schema(self, subject_name, schema_str, expect_errors=False):
        reg_url = '%s/subject/%s/register' % (self.url_prefix, subject_name)
        return self.tasr_app.request(reg_url, method='PUT',
                                     content_type=self.content_type,
                                     expect_errors=expect_errors,
                                     body=schema_str)

    ###########################################################################
    # /id app
    ###########################################################################
    def test_lookup_by_md5_id(self):
        '''GET /tasr/id/<MD5 ID> - as expected'''
        put_resp = self.register_schema(self.event_type, self.schema_str)
        # the canonicalized form returned has normalized whitespace
        canonicalized_schema_str = put_resp.body
        smeta = SchemaHeaderBot.extract_metadata(put_resp)
        self.assertEqual(1, smeta.group_version(self.event_type), 'bad ver')
        url = "%s/id/%s" % (self.url_prefix, smeta.md5_id)
        get_resp = self.tasr_app.request(url, method='GET')
        self.abort_diff_status(get_resp, 200)
        self.assertEqual(canonicalized_schema_str, get_resp.body,
                         u'Unexpected body: %s' % get_resp.body)

    def test_lookup_by_md5_id__accept_json(self):
        '''GET /tasr/id/<MD5 ID> - "Accept: text/json" as expected'''
        put_resp = self.register_schema(self.event_type, self.schema_str)
        # the canonicalized form returned has normalized whitespace
        canonicalized_schema_str = put_resp.body
        smeta = SchemaHeaderBot.extract_metadata(put_resp)
        self.assertEqual(1, smeta.group_version(self.event_type), 'bad ver')
        url = "%s/id/%s" % (self.url_prefix, smeta.md5_id)
        get_resp = self.tasr_app.request(url, method='GET', accept='text/json')
        self.abort_diff_status(get_resp, 200)
        self.assertEqual(canonicalized_schema_str, get_resp.body,
                         u'Unexpected body: %s' % get_resp.body)

    def test_lookup_by_sha256_id(self):
        '''GET /tasr/id/<SHA256 ID> - as expected'''
        put_resp = self.register_schema(self.event_type, self.schema_str)
        # the canonicalized form returned has normalized whitespace
        canonicalized_schema_str = put_resp.body
        smeta = SchemaHeaderBot.extract_metadata(put_resp)
        self.assertEqual(1, smeta.group_version(self.event_type), 'bad ver')
        url = "%s/id/%s" % (self.url_prefix, smeta.sha256_id)
        get_resp = self.tasr_app.request(url, method='GET')
        self.abort_diff_status(get_resp, 200)
        self.assertEqual(canonicalized_schema_str, get_resp.body,
                         u'Unexpected body: %s' % get_resp.body)

    def test_lookup_by_sha256_id__accept_json(self):
        '''GET /tasr/id/<SHA256 ID> - "Accept: text/json" as expected'''
        put_resp = self.register_schema(self.event_type, self.schema_str)
        # the canonicalized form returned has normalized whitespace
        canonicalized_schema_str = put_resp.body
        smeta = SchemaHeaderBot.extract_metadata(put_resp)
        self.assertEqual(1, smeta.group_version(self.event_type), 'bad ver')
        url = "%s/id/%s" % (self.url_prefix, smeta.sha256_id)
        get_resp = self.tasr_app.request(url, method='GET', accept='text/json')
        self.abort_diff_status(get_resp, 200)
        self.assertEqual(canonicalized_schema_str, get_resp.body,
                         u'Unexpected body: %s' % get_resp.body)

    def test_lookup_by_sha256_id_str__bad_id(self):
        '''GET /tasr/id/<id str> - fail on bad ID'''
        resp = self.register_schema(self.event_type, self.schema_str)
        self.abort_diff_status(resp, 201)
        ver_meta = SchemaHeaderBot.extract_metadata(resp)
        sha256_id = ver_meta.sha256_id
        # get a "bad" ID from a different schema string
        rs = tasr.registered_schema.RegisteredSchema()
        rs.schema_str = self.schema_str.replace('tagged.events', 'bob')
        bad_sha256_id = rs.sha256_id
#.........这里部分代码省略.........
开发者ID:ifwe,项目名称:tasr,代码行数:103,代码来源:test_app_core.py

示例13: TestTASRSubjectApp

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestTASRSubjectApp(TASRTestCase):
    '''These tests check that the TASR S+V REST API, expected by the Avro-1124
    repo code.  This does not check the TASR native API calls.
    '''

    def setUp(self):
        self.event_type = "gold"
        fix_rel_path = "schemas/%s.avsc" % (self.event_type)
        self.avsc_file = TASRTestCase.get_fixture_file(fix_rel_path, "r")
        self.schema_str = self.avsc_file.read()
        self.tasr_app = TestApp(APP)
        self.url_prefix = 'http://%s:%s/tasr' % (APP.config.host,
                                                 APP.config.port)
        self.subject_url = '%s/subject/%s' % (self.url_prefix, self.event_type)
        self.content_type = 'application/json; charset=utf8'
        # clear out all the keys before beginning -- careful!
        APP.ASR.redis.flushdb()

    def tearDown(self):
        # this clears out redis after each test -- careful!
        APP.ASR.redis.flushdb()

    def abort_diff_status(self, resp, code):
        self.assertEqual(code, resp.status_code,
                         u'Non-%s status code: %s' % (code, resp.status_code))

    def register_subject(self, subject_name):
        url = '%s/subject/%s' % (self.url_prefix, subject_name)
        return self.tasr_app.put(url, {'subject_name': subject_name})

    def register_schema(self, subject_name, schema_str, expect_errors=False):
        reg_url = '%s/subject/%s/register' % (self.url_prefix, subject_name)
        return self.tasr_app.request(reg_url, method='PUT',
                                     content_type=self.content_type,
                                     expect_errors=expect_errors,
                                     body=schema_str)

    ###########################################################################
    # subject tests
    ###########################################################################
    def test_all_subject_names(self):
        '''GET /tasr/subject - gets _all_ current subjects, as expected'''
        # reg two vers for target subject and one for an alt subject
        self.register_subject(self.event_type)
        alt_subject_name = 'bob'
        self.register_subject(alt_subject_name)
        # now get all and check the headers
        resp = self.tasr_app.request('%s/subject' % self.url_prefix,
                                     method='GET')
        self.abort_diff_status(resp, 200)
        meta_dict = SubjectHeaderBot.extract_metadata(resp)

        self.assertIn(self.event_type, meta_dict.keys(), 'missing subject')
        subj = meta_dict[self.event_type]
        self.assertEqual(self.event_type, subj.name, 'bad subject name')

        self.assertIn(alt_subject_name, meta_dict.keys(), 'missing subject')
        alt_subj = meta_dict[alt_subject_name]
        self.assertEqual(alt_subject_name, alt_subj.name, 'bad subject name')

        # lastly check the body
        buff = StringIO.StringIO(resp.body)
        group_names = []
        for topic_line in buff:
            group_names.append(topic_line.strip())
        buff.close()
        self.assertListEqual(sorted(group_names), sorted(meta_dict.keys()),
                             'Expected group_names in body to match headers.')

    def test_lookup_subject(self):
        '''GET /tasr/subject/<subject> - lookup the subject by name'''
        self.register_subject(self.event_type)
        resp = self.tasr_app.request(self.subject_url, method='GET')
        self.abort_diff_status(resp, 200)
        metas = SubjectHeaderBot.extract_metadata(resp)
        self.assertEqual(self.event_type, metas[self.event_type].name,
                         'unexpected subject name')

    def test_lookup_subject__accept_json(self):
        '''GET /tasr/subject/<subject> - lookup the subject by name'''
        self.register_subject(self.event_type)
        resp = self.tasr_app.request(self.subject_url, method='GET',
                                     accept='text/json')
        self.abort_diff_status(resp, 200)
        metas = SubjectHeaderBot.extract_metadata(resp)
        self.assertEqual(self.event_type, metas[self.event_type].name,
                         'unexpected subject name')

    def test_lookup_missing_subject(self):
        '''GET /tasr/subject/<subject> - lookup the subject by name'''
        missing_subject_name = 'bob'
        url = '%s/%s' % (self.url_prefix, missing_subject_name)
        resp = self.tasr_app.request(url, method='GET', expect_errors=True)
        self.abort_diff_status(resp, 404)

    def test_lookup_missing_subject__accept_json(self):
        '''GET /tasr/subject/<subject> - lookup the subject by name'''
        missing_subject_name = 'bob'
        url = '%s/%s' % (self.url_prefix, missing_subject_name)
        resp = self.tasr_app.request(url, method='GET',
#.........这里部分代码省略.........
开发者ID:ifwe,项目名称:tasr,代码行数:103,代码来源:test_app_subject.py

示例14: TestMACAuthenticationPolicy

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import request [as 别名]
class TestMACAuthenticationPolicy(unittest.TestCase):
    """Testcases for the MACAuthenticationPolicy class."""

    def setUp(self):
        self.config = Configurator(settings={
            "macauth.find_groups": "pyramid_macauth.tests:stub_find_groups",
        })
        self.config.include("pyramid_macauth")
        self.config.add_route("public", "/public")
        self.config.add_view(stub_view_public, route_name="public")
        self.config.add_route("auth", "/auth")
        self.config.add_view(stub_view_auth, route_name="auth")
        self.config.add_route("groups", "/groups")
        self.config.add_view(stub_view_groups, route_name="groups")
        self.app = TestApp(self.config.make_wsgi_app())
        self.policy = self.config.registry.queryUtility(IAuthenticationPolicy)

    def _make_request(self, *args, **kwds):
        return make_request(self.config, *args, **kwds)

    def _make_signed_request(self, userid, *args, **kwds):
        creds = self._get_credentials(userid=userid)
        req = self._make_request(*args, **kwds)
        macauthlib.sign_request(req, **creds)
        return req

    def _get_credentials(self, **data):
        id = tokenlib.make_token(data)
        key = tokenlib.get_token_secret(id)
        return {"id": id, "key": key}

    def test_the_class_implements_auth_policy_interface(self):
        verifyClass(IAuthenticationPolicy, MACAuthenticationPolicy)

    def test_from_settings_can_explicitly_set_all_properties(self):
        policy = MACAuthenticationPolicy.from_settings({
          "macauth.find_groups": "pyramid_macauth.tests:stub_find_groups",
          "macauth.decode_mac_id": "pyramid_macauth.tests:stub_decode_mac_id",
          "macauth.nonce_cache": "macauthlib:NonceCache",
        })
        self.assertEquals(policy.find_groups, stub_find_groups)
        self.assertEquals(policy.decode_mac_id, stub_decode_mac_id)
        self.assertTrue(isinstance(policy.nonce_cache, macauthlib.NonceCache))

    def test_from_settings_passes_on_args_to_nonce_cache(self):
        policy = MACAuthenticationPolicy.from_settings({
          "macauth.nonce_cache": "macauthlib:NonceCache",
          "macauth.nonce_cache_nonce_ttl": 42,
        })
        self.assertTrue(isinstance(policy.nonce_cache, macauthlib.NonceCache))
        self.assertEquals(policy.nonce_cache.nonce_ttl, 42)
        self.assertRaises(TypeError, MACAuthenticationPolicy.from_settings, {
          "macauth.nonce_cache": "macauthlib:NonceCache",
          "macauth.nonce_cache_invalid_arg": "WHAWHAWHAWHA",
        })

    def test_from_settings_errors_out_on_unexpected_keyword_args(self):
        self.assertRaises(ValueError, MACAuthenticationPolicy.from_settings, {
          "macauth.unexpected": "spanish-inquisition",
        })

    def test_from_settings_errors_out_on_args_to_a_non_callable(self):
        self.assertRaises(ValueError, MACAuthenticationPolicy.from_settings, {
          "macauth.nonce_cache": "pyramid_macauth.tests:stub_non_callable",
          "macauth.nonce_cache_arg": "invalidarg",
        })

    def test_from_settings_errors_out_if_decode_mac_id_is_not_callable(self):
        self.assertRaises(ValueError, MACAuthenticationPolicy.from_settings, {
          "macauth.decode_mac_id": "pyramid_macauth.tests:stub_non_callable",
        })

    def test_from_settings_produces_sensible_defaults(self):
        policy = MACAuthenticationPolicy.from_settings({})
        self.assertEquals(policy.find_groups.im_func,
                          MACAuthenticationPolicy.find_groups.im_func)
        self.assertEquals(policy.decode_mac_id.im_func,
                          MACAuthenticationPolicy.decode_mac_id.im_func)
        self.assertTrue(isinstance(policy.nonce_cache, macauthlib.NonceCache))

    def test_from_settings_curries_args_to_decode_mac_id(self):
        policy = MACAuthenticationPolicy.from_settings({
          "macauth.decode_mac_id": "pyramid_macauth.tests:stub_decode_mac_id",
          "macauth.decode_mac_id_suffix": "-TEST",
        })
        self.assertEquals(policy.decode_mac_id(None, "id"), ("id", "id-TEST"))

    def test_remember_does_nothing(self):
        policy = MACAuthenticationPolicy()
        req = self._make_signed_request("[email protected]", "/")
        self.assertEquals(policy.remember(req, "[email protected]"), [])

    def test_forget_gives_a_challenge_header(self):
        policy = MACAuthenticationPolicy()
        req = self._make_signed_request("[email protected]", "/")
        headers = policy.forget(req)
        self.assertEquals(len(headers), 1)
        self.assertEquals(headers[0][0], "WWW-Authenticate")
        self.assertTrue(headers[0][1] == "MAC")

#.........这里部分代码省略.........
开发者ID:tarekziade,项目名称:pyramid_macauth,代码行数:103,代码来源:tests.py


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