Django 测试:测试表单字段的初始值

发布于 2024-10-03 17:46:36 字数 405 浏览 5 评论 0原文

我有一个观点,应该根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

⊕婉儿 2024-10-10 17:46:37

我认为这个功能是 1.3 版本中附带的,但可能更早出现。我稍微修改了页面上的示例以适应您的要求,但它是未经测试的代码,并且我假设了一些内容,例如响应上下文的表单参数。根据需要进行修改。这个答案的重点是展示请求工厂。

http://docs.djangoproject.com/en/开发/主题/测试/#django.test.client.RequestFactory

from django.utils import unittest
from django.test.client import RequestFactory

class SimpleTest(unittest.TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()

    def test_details(self):
        get_param = 'some_value'
        # Create an instance of a GET request.
        request = self.factory.get('/customer/details/?param={0}'.format(get_param))

        # Test my_view() as if it were deployed at /customer/details
        response = my_view(request)

        # test 1
        form = response.form
        idx = form.as_p().find(get_param)
        self.assertNotEqual(idx, -1)            
        #or.. test 2
        self.assertContains(response, get_param)

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

from django.utils import unittest
from django.test.client import RequestFactory

class SimpleTest(unittest.TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()

    def test_details(self):
        get_param = 'some_value'
        # Create an instance of a GET request.
        request = self.factory.get('/customer/details/?param={0}'.format(get_param))

        # Test my_view() as if it were deployed at /customer/details
        response = my_view(request)

        # test 1
        form = response.form
        idx = form.as_p().find(get_param)
        self.assertNotEqual(idx, -1)            
        #or.. test 2
        self.assertContains(response, get_param)
等风来 2024-10-10 17:46:37

如果您严格检查表单字段的初始值,另一种选择是测试您的表单:

forms.py

from django import forms

class MyForm(forms.Form):
    title = forms.CharField(initial='My Default Title')

test_forms.py

from django.test import TestCase
from .forms import MyForm

class MyFormTests(TestCase):
    def test_myform_initial_value(self):
        form = MyForm()
        self.assertEqual(form['title'].initial, 'My Default Title')

If you strictly checking for the initial value of a form field, another alternative is testing your form:

forms.py:

from django import forms

class MyForm(forms.Form):
    title = forms.CharField(initial='My Default Title')

test_forms.py

from django.test import TestCase
from .forms import MyForm

class MyFormTests(TestCase):
    def test_myform_initial_value(self):
        form = MyForm()
        self.assertEqual(form['title'].initial, 'My Default Title')
找个人就嫁了吧 2024-10-10 17:46:36

讨厌回答我自己的问题(就像我第三次这样做),但在与测试客户端进行嘲笑之后,我找到了一个更好的方法:

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')

有人认为这有什么问题吗?我会把它搁置一段时间,看看人们的想法。

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.

初心未许 2024-10-10 17:46:36

接受的解决方案检查表单上的 initial['...'] 值,但您也可以检查字段上的实际值。伪代码如下。

如果您想测试直接来自模型的默认值(未设置 form.initial)并确保 initial['...'] 是实际值,这会很有帮助。

def test_some_default_value(self):
        response = self.client.get('/signup/')
        self.assertEquals(response.context['form']['plan'].value(), my_value)

def test_some_default_value_2(self):
        some_different_conditions...
        response = self.client.get('/signup/')
        self.assertEquals(response.context['form']['plan'].value(), a_different_value)

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.

def test_some_default_value(self):
        response = self.client.get('/signup/')
        self.assertEquals(response.context['form']['plan'].value(), my_value)

def test_some_default_value_2(self):
        some_different_conditions...
        response = self.client.get('/signup/')
        self.assertEquals(response.context['form']['plan'].value(), a_different_value)
十雾 2024-10-10 17:46:36

该值将作为 嵌入到 html 中。您可以使用您喜欢的任何工具搜索该字符串。

response = Client().get('/customer/details/')
print [line for line in response.split('\n') if line.find('<input') > -1]

The value will be embedded in the html as <input value= 'whatever'/>. You can search for that string with whatever tool you prefer.

response = Client().get('/customer/details/')
print [line for line in response.split('\n') if line.find('<input') > -1]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文