Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django testing: Test the initial value of a form field

I have a view that should be setting an initial value for a form field based on a GET value. I want to test this. I'm currently using Django's test client but I am open to looking at other tools.

Edit

Sorry, I did not mention that I am well aware of the assertContains method but I was hoping there was a better way other than searching the HTML for an input tag and the value attribute.

like image 471
Belmin Fernandez Avatar asked Nov 21 '10 01:11

Belmin Fernandez


People also ask

How do I run a test case in Django?

Open /catalog/tests/test_models.py.TestCase , as shown: from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.

How does Django do testing?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.

What order Django tests are run?

Order in which tests are executedAll TestCase subclasses are run first. Then, all other Django-based tests (test cases based on SimpleTestCase , including TransactionTestCase ) are run with no particular ordering guaranteed nor enforced among them. Then any other unittest.

What is self client in Django?

self. client , is the built-in Django test client. This isn't a real browser, and doesn't even make real requests. It just constructs a Django HttpRequest object and passes it through the request/response process - middleware, URL resolver, view, template - and returns whatever Django produces.


1 Answers

Hate to answer my own question (like the 3rd time I've done it) but after mocking around with the test client, I've found a better way:

def test_creating_stop(self):
    c = self.client

    # Check that name is pre-filled
    response = c.get('%s?name=abcd' % reverse('add_new_stop'))
    self.assertEqual(response.context['form'].initial['name'], 'abcd')

Does anyone see anything wrong with this? I'll leave it up for a while see what people think.

like image 109
Belmin Fernandez Avatar answered Sep 20 '22 16:09

Belmin Fernandez