django测试非现场验证错误 [英] django test non-field validation errors

查看:55
本文介绍了django测试非现场验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试非字段特定验证错误的django方法是什么?

What is the django way to test non field specific validation errors?

例如,一个电子邮件字段将测试输入的文本是否为有效的电子邮件地址,但是一个非字段错误将显示在窗体上方,与任何一个字段都没有关系。例如,它会说该电子邮件地址已经注册。

For example, an email field will test is the text entered is a valid email address, but a non-field error will display above the form, with no relationship to any one field. It would, for instance, say that that email address is already registered.

在测试应用程序时,如何测试这些非字段验证错误?

When testing applications, how do you test these non-field validation errors?

编辑:使问题更清楚。我有一个自定义的验证功能,但我想使用Django提供的unittest框架来测试它是否抛出了它应该抛出的错误。

To make the question more clear. I have a custom validation function, but I'd like to test that it's throwing the errors it's supposed to using the unittest framework provided by Django.

我可以调用该函数直接并以这种方式对其进行测试,但这并不能确保在视图中正确使用它(即:我想进行集成测试)。

I could call the function directly and test it that way, but that doesn't ensure that it's being used properly in the view (ie: I want to do an integration test).

谢谢。

编辑:我已经找到了解决方法,例如如何测试而不是验证

I have found the solution as how to test and not validate a field error.

这是通过assertFormError完成的。将字段名称更改为无,并将错误字符串更改为错误字符串列表。

It's done with assertFormError. Change the field name to None and change the error string to a list of error strings.

self.assertFormError(response, 'form', 'field name', 'error') # Test single field error
self.assertFormError(response, 'form', None, ['Error #1.', 'Error #2']) # Test general form errors


推荐答案

只是为了得到一个答案,是正确的,即使问题本身已经存在,我也将发布答案。

Just for the sake of having an answer that is correct, even though it is already in the question itself I'll post the answer.

您可以使用 assertFormError()

You can test a form for errors by using assertFormError().


断言表单上的字段在呈现在表单上时会引发所提供的错误列表。

Asserts that a field on a form raises the provided list of errors when rendered on the form.

请注意,表单名称必须是上下文中表单的名称。你是你的实际形式

Please note that the form name has to be the name of the form in the context not the actual form you are using for validation.

对于 non_field_errors (与任何字段无关的一般错误),您可以按以下方式使用它:

You can use it as follows for non_field_errors (general errors not related to any field):

self.assertFormError(response, 'form', None, 'Some error')

您可以测试特定字段错误,如下所示:

You can test for a specific field error as follows:

self.assertFormError(response, 'form', 'field_name', 'Some error')

您还可以传入一组错误进行测试。

You can also pass in a tuple of errors to test against.

errors = ['some error 1', 'some error 2']
self.assertFormError(response, 'form', 'field_name', errors)

这篇关于django测试非现场验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆