Reputation: 19
I have a simple view to recalculate values (g -> kg) in a django form to add data inside of the view and to simply re-calculate it.
Now, i want to test such view to give it the value and compare "output" How should I test it. Here is a code of view itself:
def weight_converter(request):
if request.method == 'POST':
form = Adder(request.POST)
if form.is_valid():
try:
value_in_g = int(form.cleaned_data['added_data'])
result_kg = value_in_g/1000
return render(request, 'weight_converter.html',
{'result': result_kg, 'initial_value': value_in_g,})
except ValueError as e:
e.message = 'Enter the number, not the string'
return render(request, 'weight_converter.html', {'message': e.message})
else:
form = Adder()
return render(request, 'weight_converter.html', {'form': form})
Would something like this work?
def test_weightconverter_view_calculation(self):
response = self.client.get('/weight_converter/', {'value_in_g': '1234'})
self.assertEqual(response.context['result'], 1.234)
Thanks in advance for any advice! )
Upvotes: 1
Views: 105
Reputation: 476729
You make a GET request, not a POST request, and the result
is only specified with the POST request, and likely with added_data
as key:
def test_weightconverter_view_calculation(self):
response = self.client.post('/weight_converter/', {'added_data': '1234'})
self.assertEqual(response.context['result'], 1.234)
Here however it would likely make more sense to do the calculations with a GET request, since there are no side effects when converting grams to kilograms.
Upvotes: 1