Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

Meaningful error message if Redirect after Post fails (Testing Django)

After successful POST a redirect should happen (PRG Pattern)

    response = admin_client.post(url, data)
    assert response.status_code == 302

If this test fails, I get a very meaningless error message.

AssertionError assert 200 == 302

Since the status is 200, I know that the form data which I send did not validate.

Is there a django-way to get the error message of the django form validation into the exception?

Example: I would like to see something like "foo is require" (if "foo" is not in data)

question from:https://stackoverflow.com/questions/65933218/meaningful-error-message-if-redirect-after-post-fails-testing-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Django's custom TestCase class is a subclass of unittest.TestCase and all of its assert functions have a msg argument which when passed are used as the error message when an assertion fails. Also since you want the forms error to be displayed, you can get the form instance from the context and get its errors. Something like this should work:

assertEqual(response.status_code, 302, str(response.context['form'].errors))

Note forms also have form.errors.as_data() which will show the exceptions raised during form validation, or form.errors.as_json() any of which you might find more usable. Reference Form.errors


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...