Reputation: 1199
I'm running a unit test in Django but keep getting an error
File "C:\****\views.py", line 21, in post
s = str(points['string_points'])
KeyError: 'string_points'
Command Used:
python manage.py test
The structure of my test code looks as follows:
class TestSetUp(APITestCase):
def setUp(self):
self.getClosestDistance_url = reverse('getClosestDistance')
self.calculateClosestDistance_url = reverse('calcClosestDistance')
points = {
"string_points": "(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)"
}
return super().setUp()
def tearDown(self):
return super().tearDown()
class TestViews(TestSetUp):
def test_getClosestPoints_with_no_data(self):
res = self.client.post(self.calculateClosestDistance_url)
import pdb # python debugger
pdb.set_trace()
self.assertEqual(res.status_code, 400)
Structure of my views.py file is as follows:
class closestDistanceValue(APIView):
def get(self, request):
points = Points.objects.all()
serializer = PointsSerializer(points, many=True)
return Response(serializer.data)
def post(self, request, format=None):
points=request.data # user input
s = str(points['string_points'])
closestPoint = getClosestDistance(s)
data = {
'point': s,
'closestPoint': closestPoint
}
serializer = PointsSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
JSON Body for POST request. Keyed in as user input
{
"string_points": "(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)"
}
What I'm I missing?
Upvotes: 0
Views: 39
Reputation: 12869
You need to send the data with the request. You could either set the data as an attribute of the test, or just pass it with the request.
class TestSetUp(APITestCase):
def setUp(self):
self.getClosestDistance_url = reverse('getClosestDistance')
self.calculateClosestDistance_url = reverse('calcClosestDistance')
self.points = {
"string_points": "(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)"
}
return super().setUp()
def tearDown(self):
return super().tearDown()
class TestViews(TestSetUp):
def test_getClosestPoints_with_no_data(self):
res = self.client.post(self.calculateClosestDistance_url, self.points)
self.assertEqual(res.status_code, 400)
Or with the test itself;
def test_getClosestPoints_with_no_data(self):
data = {
"string_points": "(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)"
}
res = self.client.post(self.calculateClosestDistance_url, data)
self.assertEqual(res.status_code, 400)
Upvotes: 2