Sunday, March 29, 2015

Re: How to mock a model backend

Hi Sven,

You can mock the call to the external service like this.

@mock.patch.object(MyModelBackend, 'authenticate') # First the class of your model backend. Then the method you want to mock.
  def test_something_that_uses_login(self, mock_authenticate):  # The mock object is passed to your test method
      mock_authenticate.return_value = # whatever your authenticate method to returns
      # the rest of your code

More about mock library

http://www.voidspace.org.uk/python/mock/

Best 




On Thu, Mar 26, 2015 at 11:18 AM Sven Mäurer <maeurer.sven@gmail.com> wrote:
In my model backend I usually call an external service which returns me an user that is saved and returned. When I don't have credentials I want to mock the backend for some test cases. In the setup of each test case I am calling the login method where CRED contains the real credentials or mock credentials. This can be determined by are_credentials_given.

def are_credentials_given():
return not os.path.isfile(os.path.join(BASE_DIR, 'settings/credentials'))

def login(self):
u = User.objects.create(id=CRED['ID'], is_staff=True)
u.save()
token, c = Token.objects.get_or_create(user=u)
if c:
token.save()
self.client = APIClient()
self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
self.client.login(username=CRED['USERNAME'], password=CRED['PASSWORD'])

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/894d8e22-b448-41fc-bd1b-a82a2a35db8a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAL60nj%2BS4aLkdt7E7ALoTmK4uFC%3DrH5NXSdUZ8P4R_B8KZWVeg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment