我想更好地编写这个测试:
def test_profile_created(self):
self.client.post(reverse('registration_register'), data={
'username':'ygam',
'email':'ygam@example.com',
'password1':'ygam',
'password2':'ygam'
})
"""
Test if a profile is created on save
"""
user = User.objects.get(username='ygam')
self.assertTrue(UserProfile.objects.filter(user=user).exists())
我刚刚在 django-registration 测试中发现了这段代码,它实际上并没有“创建”用户:
def test_registration_signal(self):
def receiver(sender, **kwargs):
self.failUnless('user' in kwargs)
self.assertEqual(kwargs['user'].username, 'bob')
self.failUnless('request' in kwargs)
self.failUnless(isinstance(kwargs['request'], WSGIRequest))
received_signals.append(kwargs.get('signal'))
received_signals = []
signals.user_registered.connect(receiver, sender=self.backend.__class__)
self.backend.register(_mock_request(),
username='bob',
email='bob@example.com',
password1='secret')
self.assertEqual(len(received_signals), 1)
self.assertEqual(received_signals, [signals.user_registered])
但是,他为此“_mock_request”使用了自定义函数:
class _MockRequestClient(Client):
def request(self, **request):
environ = {
'HTTP_COOKIE': self.cookies,
'PATH_INFO': '/',
'QUERY_STRING': '',
'REMOTE_ADDR': '127.0.0.1',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',
'wsgi.version': (1,0),
'wsgi.url_scheme': 'http',
'wsgi.errors': self.errors,
'wsgi.multiprocess':True,
'wsgi.multithread': False,
'wsgi.run_once': False,
'wsgi.input': None,
}
environ.update(self.defaults)
environ.update(request)
request = WSGIRequest(environ)
# We have to manually add a session since we'll be bypassing
# the middleware chain.
session_middleware = SessionMiddleware()
session_middleware.process_request(request)
return request
def _mock_request():
return _MockRequestClient().request()
但是,它可能对我的需要来说太长了。我希望能够以某种方式“伪造”帐户创建。我在模拟和存根方面没有太多经验,所以任何帮助都可以。谢谢!