python - django unit test for logged in or anonymous user -
i have service returning dictionary depending on whethter user logged in or anonymous or anonymous email.i have used service in django rest api , put logic in api view. want create unit test api , want test following different situation i.e
- if user logged in
- if user anonymous no email
- if user anonymous email
i.e,
for 1, if user logged in ,we have different value, 2, if user anonymous, have different value, 3, if user anonymous provide email,we have different value
now in django unit test,how can check different situation?
for better convenient,i sharing have tried(which 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 want know **how check type of situations in django unit test i.e
if user logged in test something..... elif user anonymous test thing.....
in fact , please don't bother shared code,what need know how check above written situations
,i have shared code let know have tried far check situations.but pretty sure, not right way,but sorry unable find right way.may lack of writing api testing in djano,in fact writing first time.
to check anonymous user, can use (as seen in the docs)
self.user.is_anonymous()
to check logged in user, can use (again, taken docs
self.user.is_authenticated()
that being said, these should separate unit tests. unit test should simple, , test 1 thing. it's anti-pattern test these different cases in 1 single unit test.
Comments
Post a Comment