Reputation: 4285
i have a service which actually returning a dictionary depending on whethter the user is logged in or anonymous or anonymous with email.I have used the service in a django rest api and put all the logic in the api view. Now i want to create a unit test for this api and want to test the following different situation i.e
i.e,
for 1, if user is logged in ,we will have a different value, for 2, if user is anonymous, we will have another different value, for 3, if user is anonymous but provide an email,we will have another different value
now in django unit test,how can i check this different situation?
for better convenient,i am sharing what i have actually tried(which is actually not working perfectly)
def test_requirement_header_create_api(self, mocked_get_or_save_anonymous_user_email):
mocked_get_or_save_anonymous_user_email.return_value = dict()
client = APIClient(enforce_csrf_checks=True)
logged_in = client.login(username=self.user.email, password=self.user.password)
if logged_in:
self.data = {
"user_id": self.user_id,
"description": self.description,
}
expected_return = {
"user_id": self.user_id,
"description": self.description,
}
elif self.anonymous_user:
self.data = {
"email": self.anonymous_user.email,
"anonymous_user_email_id": self.anonymous_user.id,
"description": self.description,
}
expected_return = {
"id": 2,
"status": self.requirement_status,
"description": self.description,
}
else:
self.data = {
"description": self.description,
"session": self.session,
}
expected_return = {
"description": self.description,
"session": self.session,
}
response = client.post('/api/requirement-header/', self.data, format='json')
self.assertDictEqual(response.data, expected_return)
i just want to know **how to check this type of situations in django unit test i.e
if user is logged in then test something.....
elif user is anonymous then test some another thing.....
in fact , please don't bother about my shared code,what i need to know is that how to check my above written situations
,i have shared my code to let you know what i have actually tried so far to check those situations.but i am pretty sure, this is not the right way,but sorry to say i am unable to find the right way.may be this is my lack of writing api testing in djano,in fact i am writing for the very first time.
Upvotes: 2
Views: 1276
Reputation: 825
To check for anonymous user, you can use (as seen in the docs)
self.user.is_anonymous()
To check for logged in user, you can use (again, taken from the docs
self.user.is_authenticated()
That being said, these should be separate unit tests. Unit test should be simple, and test only one thing. It's an anti-pattern to test these different cases in one single unit test.
Upvotes: 2