Django Testing: Faking User Creation

Posted by Ygam on Stack Overflow See other posts from Stack Overflow or by Ygam
Published on 2012-09-28T03:34:01Z Indexed on 2012/09/28 3:37 UTC
Read the original article Hit count: 330

Filed under:
|
|

I want to better write this test:

def test_profile_created(self):
        self.client.post(reverse('registration_register'), data={
            'username':'ygam',
            'email':'[email protected]',
            '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())

and I just came upon this code on django-registration tests that does not actually "create" the user:

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='[email protected]',
                              password1='secret')

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_registered])

However he used a custom function for this "_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()

However, it may be too long of a function for my needs. I want to be able to somehow "fake" the account creation. I have not much experience on mocks and stubs so any help would do. Thanks!

© Stack Overflow or respective owner

Related posts about python

Related posts about django