这是功能测试。 Webtest 可以保留会话 cookie,以便您可以使用它以用户身份登录和访问各种页面。
myapp = pyramid.paster.get_app('testing.ini')
app = TestApp(myapp)
resp = app.post('/login', params={'login': 'foo', 'password': 'seekrit'})
# this may be a redirect in which case you may want to follow it
resp = app.get('/protected/resource')
assert resp.status_code == 200
就仅测试应用的某些部分而言,您可以使用自定义的东西(或仅使用自定义 groupfinder)覆盖身份验证策略。
def make_test_groupfinder(principals=None):
def _groupfinder(u, r):
return principals
return _groupfinder
然后您可以使用此功能来模拟各种主体。但是,如果您的应用程序还依赖于 authenticated_userid(request) 任何地方,这不会处理用户 ID。为此,您必须将身份验证策略替换为虚拟策略。
class DummyAuthenticationPolicy(object):
def __init__(self, userid, extra_principals=()):
self.userid = userid
self.extra_principals = extra_principals
def authenticated_userid(self, request):
return self.userid
def effective_principals(self, request):
principals = [Everyone]
if self.userid:
principals += [Authenticated]
principals += list(self.extra_principals)
return principals
def remember(self, request, userid, **kw):
return []
def forget(self, request):
return []