Reputation: 640
Do one need to create a test for a ModelForm
as below? The reason is that there is actually no code.
class HouseForm(forms.ModelForm):
class Meta:
model = House
exclude = ['user',]
fields = ['area', 'num_floors',]
So the only part to test is just to check if the exclude
and include
fields do not have a common field. Also to test that exclude
and include
do have all the fields of the model and no more.
Does it make sense?
On the other hand, I would like to write a unit test for the following view. It utilizes the ModelForm above.
Is it somehow possible to write a real unit test without using some tools like Selenium which is in some sense functional testing? The point is that I don't know how can one pass some field values over the view.
@login_required
def update_or_create_house(request, house_id=None):
if house_id:
house = request.user.house_set.get(pk=house_id)
else:
house = None
if request.method=="POST":
form = HouseForm(request.POST, instance=house)
if form.is_valid():
result = form.save(commit=False)
result.user = request.user
result.save()
return redirect('houses-viewall')
else:
print form.errors
else:
form = HouseForm(instance=house)
return render(request, 'housemgm/edit_house.html', {'form':form, 'house':house,})
The last question: Is a good design to have edit and create functionality in the same view? Or should I split them into two parts?
Just for sake of completeness the model is
class House(models.Model):
area = models.FloatField()
owner = models.ForeignKey(User)
num_floors = models.IntegerField(default=1)
Upvotes: 2
Views: 1460
Reputation: 599600
Firstly, don't test things that are provided by Django itself. If you don't have any custom code in your model form, don't test it specifically: the functionality of model forms in general is already well tested by Django.
To test your view, you can use the built-in test client which simulates GETs and POSTs on your view. You can then make assertions on the contents of the response, and on the state of the database before and after your test.
Finally, yes this is a good pattern for the view.
Upvotes: 6