Django 测试:测试表单字段的初始值
我有一个观点,应该根据 GET 值为表单字段设置初始值。我想测试一下。我目前正在使用 Django 的测试客户端,但我愿意看看其他工具。
编辑
抱歉,我没有提到我很了解 assertContains 方法,但我希望除了在 HTML 中搜索 input
标记和 value
属性之外,还有更好的方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为这个功能是 1.3 版本中附带的,但可能更早出现。我稍微修改了页面上的示例以适应您的要求,但它是未经测试的代码,并且我假设了一些内容,例如响应上下文的表单参数。根据需要进行修改。这个答案的重点是展示请求工厂。
http://docs.djangoproject.com/en/开发/主题/测试/#django.test.client.RequestFactory
I think this feature comes with 1.3 but it may have come in earlier. I've slightly modified the example on the page to work with your requirements, but it's untested code and I've assumed a few things like the form parameter of the response context. Modify as applicable. The point of this answer is to show the request factory.
http://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.RequestFactory
如果您严格检查表单字段的初始值,另一种选择是测试您的表单:
forms.py:
test_forms.py
If you strictly checking for the initial value of a form field, another alternative is testing your form:
forms.py:
test_forms.py
讨厌回答我自己的问题(就像我第三次这样做),但在与测试客户端进行嘲笑之后,我找到了一个更好的方法:
有人认为这有什么问题吗?我会把它搁置一段时间,看看人们的想法。
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:
Does anyone see anything wrong with this? I'll leave it up for a while see what people think.
接受的解决方案检查表单上的
initial['...']
值,但您也可以检查字段上的实际值。伪代码如下。如果您想测试直接来自模型的默认值(未设置 form.initial)并确保
initial['...']
是实际值,这会很有帮助。The accepted solution check
initial['...']
value on the form but you could also check the actual value on the field. Pseudo-code bellow.This is helpful if you want to test a default value coming directly from the model (form.initial is not set) and to make sure that
initial['...']
is the actual value.该值将作为 嵌入到 html 中。您可以使用您喜欢的任何工具搜索该字符串。
The value will be embedded in the html as <input value= 'whatever'/>. You can search for that string with whatever tool you prefer.