jeudi 29 octobre 2015

How to avoid huge test refactoring on form change in Django

Suppose there is a model, like:

class Book(Model):
    title = CharField(...)

So now I decide to add a choice field. So I add one plus set the default value thinking that this will allow me not to refactor code that much:

class Book(Model):
    title = CharField(...)
    book_type = ChoiceField(..., default=SOME_CHOICE_DEFAULT)

But unfortunately this forces to me to refactor a lot of tests. For example there about 10 tests for the form for this model like:

def test_book_form_is_invalid_on_some_condition():
    form = BookForm({'title': 'iwfew23@f'})
    assert not form.is_valid()

I have to add a book_type field to each one. This is really frustrating. Also I have to refactor more functional tests:

def test_update_view_changes_something(admin_client):
    admin_client.post(reverse('book:update'), {'title': 'some_title'})
    ...

This will also complain that book_type isn't there.

How do I deal with such cascade refactoring when introducing a small model change?

I guess one of the ways to challenge this would be to introduce a global fixture which contains a default form data:

 @pytest.fixture
 def book_form_data():
     return {'title': 'some title'}

 def test_some_form_test(book_form_data):
     book_form_data['title'] = 'another title for this test'
     form = BookForm(book_form_data)
     ...

So the only place where I should add book_type will be this fixture. But that does not look quite right as well.

Aucun commentaire:

Enregistrer un commentaire