在pytest中运行时表单始终无效

时间:2019-09-24 09:09:05

标签: python django django-forms django-admin pytest-django

我在尝试在pytest中获取有效表格时遇到问题。我正在通过Django Admin操作测试数据更改。无论我向表单发布什么数据,form.is_valid()都将始终返回False。将字典传递给表单可以直接使用,但是我希望能够通过操作进行测试,以确保该操作可以过滤掉锁定的记录。

# test_admin.py

@pytest.mark.django_db
class BaseTestCase(TestCase):
    """Base TestCase with utilites to create user and login client."""

    def setUp(self):
        """Class setup."""
        self.index_url = '/'
        self.login()
        self.django_db_setup()

    def create_user(self):
        """Create user and returns username, password tuple."""
        username, password = 'testadmin', 'password123'
        user = User.objects.create_superuser(
            username,
            'admin@test.com',
            password,
            first_name='Admin',
            last_name='Account',
        )
        self.user = user
        return (username, password)

    def login(self):
        """Log in client session."""
        username, password = self.create_user()
        self.client.login(username=username, password=password)

    @staticmethod
    def django_db_setup():
        call_command('loaddata', 'fixtures/fixture.json')


class AdminTestCase(BaseTestCase):

    def test_responsible_list(self):
        products = Product.objects.filter(pk__in=[230005, 229724])
        form_data = {
            'action': 'set_product_class',
            'apply': 'Submit',
            'product_class': '1',
            ACTION_CHECKBOX_NAME: products.values_list('pk', flat=True),
        }
        self.client.post('/admin/store/product/', form_data, follow=True)
        # Assert product_classes have changed


# actions.py

def set_product_class(modeladmin, request, queryset):
    # Exclude products that are locked
    queryset = queryset.exclude(is_locked=True)
    form = None
    if 'apply' in request.POST:
        form = SetProductClassForm(data=request.POST)
        if form.is_valid():
           # action code


# forms.py

class SetProductClassForm(forms.Form):
    _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
    product_class = forms.ModelChoiceField(ProductClass.objects.all())

我在操作if form.is_valid():

的行上方放置了pdb跟踪

当我在pytest中运行此代码时:

(Pdb) form.is_valid()
False
(Pdb) request.POST
<QueryDict: {u'action': [u'set_product_class'], u'apply': [u'Submit'], u'product_class': [u'1'], u'_selected_action': [u'230005', u'229724']}>

但是,如果我通过Django shell运行相同的代码,则该表格有效:

(Pdb) form.is_valid()
True
(Pdb) request.POST
<QueryDict: {u'action': [u'set_product_class'], u'apply': [u'Submit'], u'product_class': [u'1'], u'_selected_action': [u'230005', u'229724']}>

为什么我不能通过pytest获得有效的表格?

1 个答案:

答案 0 :(得分:1)

检查form.errors给出以下信息:

{'product_class': [u'Select a valid choice. That choice is not one of the available choices.']}

此问题是由夹具中缺少表单中的ProductClass的数据引起的。将数据添加到测试数据库可解决此问题。