2

Suppose I have an unit test which tests a view. That view requires a form to do some processing. My unit test looks like this:

class ViewTests(TestCase):
def setUp(self):
    self.factory = RequestFactory()

def test_login_view_post(self):
    # require form object to pass it in post function
    response = self.client.post(reverse('login'))
    self.assertContains(response, "Your username and password didn't match", status_code=200)

Can someone tell me that how can I pass the form object in the post function?

Thanks.

1 Answer 1

3

You don't actually pass the form object in the post, you pass the form data as if the form was being submitted (which is what you are simulating)

post_data = {
    "username": "foo",
    "password": "bar"
}
response = self.client.post(reverse('login'), data=post_data)

Or you can simply include the form in another test and instantiate it with data to test its validity.

def test_form(self):
    data = {
        "username": "foo",
        "password": "bar"
    }
    form = LoginForm(data)
    self.assertFalse(form.is_valid())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.