我正在尝试测试是否在django_authopenid中注册了新用户时创建了UserProfile模型。 我不明白如何将Openid会话数据添加到POST。
class UserTestCAse(TestCase):
def test_register_should_create_UserProfile(self):
from django.test.client import Client
c = Client()
response = c.post('/account/register/', {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']},)
self.assertEqual(response.status_code, 302)
user = User.objects.get( username ='john')
self.assertTrue(user.get_profile())
答案 0 :(得分:2)
显然,在不使用Client.login()的情况下将会话数据添加到django.test.client.Client并不容易。
最简单的解决方案是创建一个新的RequestFactory类,以便我可以使用OpenID会话对象构建一个Request。
class RequestFactory(Client):
"""
Class that lets you create mock Request objects for use in testing.
Usage:
rf = RequestFactory()
get_request = rf.get('/hello/')
post_request = rf.post('/submit/', {'foo': 'bar'})
This class re-uses the django.test.client.Client interface, docs here:
http://www.djangoproject.com/documentation/testing/#the-test-client
Once you have a request object you can pass it to any view function,
just as if that view had been hooked up using a URLconf.
"""
def request(self, **request):
"""
Similar to parent class, but returns the request object as soon as it
has created it.
"""
environ = {
'HTTP_COOKIE': self.cookies,
'PATH_INFO': '/',
'QUERY_STRING': '',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': 'testserver',
'SERVER_PORT': 80,
'SERVER_PROTOCOL': 'HTTP/1.1',
}
environ.update(self.defaults)
environ.update(request)
request = WSGIRequest(environ)
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception("Couldn't create request mock object - "
"request middleware returned a response")
return request
我使用了RequestFactory方法,如下所示:
class UserProfileCreation(TestCase):
def test_register_should_create_UserProfile(self):
count = User.objects.count()
print 'Original Users' + str(count)
from forum.tests.request_factory import RequestFactory
rf = RequestFactory()
post_request = rf.post('/register/', {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup'] } )
from django_authopenid.util import OpenID
openid_instance = OpenID('https://www.google.com/accounts/o8/id?id=AItOxxxxxxxxxxxxxxxxxA',
1267727884,
[u'openid.op_endpoint', u'openid.claimed_id', u'openid.identity', u'openid.return_to', u'openid.response_nonce', u'openid.assoc_handle'],
)
post_request.session['openid'] = openid_instance
from django_authopenid.views import register
response = register(post_request)
print "after POST User count: " + str(User.objects.count())
self.assertEqual(response.status_code, 302)
user = User.objects.get( username ='john')
self.assertTrue(user.get_profile())