I am trying to write unit test case for an external facing api of my Django application. I have a model called Dummy
with two fields temp
and content
. The following function is called by third party to fetch the content
field. temp
is an indexed unique key.
@csrf_exempt
def fetch_dummy_content(request):
try:
temp = request.GET.get("temp")
dummy_obj = Dummy.objects.get(temp=temp)
except Dummy.DoesNotExist:
content = 'Object not found.'
else:
content = dummy_obj.content
return HttpResponse(content, content_type='text/plain')
I have the following unit test case.
def test_dummy_content(self):
params = {
'temp': 'abc'
}
dummy_obj = mommy.make(
'Dummy',
temp='abc',
content='Hello World'
)
response = self.client.get(
'/fetch_dummy_content/',
params=params
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'Hello World')
Every time I run the test case, it goes into exception
and returns Object not found.
instead of Hello World
. Uponn further debugging I found that temp
from request object inside view function is always None
, even though I am passing it in params
.
I might be missing something and not able to figure out. What's the proper way to test these kind of functions.
There's no params
parameter for the get
or any of the other functions on the client, you're probably thinking of data
.
response = self.client.get(
'/fetch_dummy_content/',
data=params
)
It's the second argument anyway, so you can just do self.client.get('/fetch_dummy_content/', params)
too.
Any unknown parameters get included in the environment which explains why you were not getting an error for using the wrong name.