I'm building RESTful API services using django rest framework, I've reached the point where i have to create an automated test for my RESTful API services.
The sessionList api require token authentication, in case the user doesn't have the token he won't be able to access the session collection.
The api worked fine when I've tested it using POSTMAN and the real browser.
SessionList:
class SessionList(generics.ListCreateAPIView):
authentication_classes = [TokenAuthentication, ]
permission_classes = [IsAuthenticated, ]
throttle_scope = 'session'
throttle_classes = (ScopedRateThrottle,)
name = 'session-list'
filter_class = SessionFilter
serializer_class = SessionSerializer
ordering_fields = (
'distance_in_miles',
'speed'
)
def get_queryset(self):
return Session.objects.filter(owner=self.request.user)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
Then i've created an automated test using DRF test
RunningSessionTest:
class RunningSessionTest(APITestCase):
def test_get_sessions(self):
factory = APIRequestFactory()
view = views.SessionList.as_view()
user = User.objects.create_user(
'user01', 'user01@example.com', 'user01P4ssw0rD')
request = factory.get('http://localhost:8000/sessions/')
force_authenticate(request, user=user)
response = view(request)
assert Response.status_code == status.HTTP_200_OK
def test_get_sessions_not_authenticated_user(self):
factory = APIRequestFactory()
view = views.SessionList.as_view()
user = User.objects.create_user(
'user01', 'user01@example.com', 'user01P4ssw0rD')
request = factory.get('http://localhost:8000/sessions/')
response = view(request)
assert Response.status_code == status.HTTP_401_UNAUTHORIZED
The issue: in both cases, if the user has the token or not the response value is HTTP_200_OK
I've tried to solve the problem by trying different methods to implement the test. I've used APIRequestFactory, Also i've used the APIClient but i got the same result. To be honest after reading the document many times i couldn't understand the differences between the APIClient and the APIRequestFactory.
The result of the test :
Traceback (most recent call last):
File "C:\python_work\DjnagoREST\01\restful01\RunKeeper\tests.py", line 67, in test_get_sessions_not_authenticated_user
assert Response.status_code == status.HTTP_401_UNAUTHORIZED
AssertionError
I will be grateful to your help.