【问题标题】:Unit test for MultipleChoiceField in django tests always failsdjango 测试中 MultipleChoiceField 的单元测试总是失败
【发布时间】:2019-06-02 14:38:42
【问题描述】:

我正在尝试为带有 MultipleChoiceField 的表单的发布请求的视图执行 unittest,但它总是失败,这是我的代码:

来自 forms.py

class AddUserForm(forms.Form):
    OPTIONS = (
        ("إدارة عامة", "إدارة عامة"),
        ("إدارة المستخدمين", "إدارة المستخدمين"),
    )

    username = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control',
        'placeholder': 'إسم المستخدم'
    }))
    password = forms.CharField(widget=forms.PasswordInput(attrs={
        'class': 'form-control',
        'placeholder': 'كلمة المرور'
    }))
    name = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control',
        'placeholder': 'اسم الموظف '
    }))
    branch = forms.ModelChoiceField(queryset=Branch.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
    authorities = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                            choices=OPTIONS)

views.py

@login_required
def create_user(request):
    add_user_form = AddUserForm(request.POST)
    if request.method == 'POST':
        if add_user_form.is_valid():
            username = add_user_form.cleaned_data['username']
            password = add_user_form.cleaned_data['password']
            name = add_user_form.cleaned_data['name']
            branch = add_user_form.cleaned_data['branch']
            authorities = add_user_form.cleaned_data['authorities']
            check_users = User.objects.all()
            for item in check_users:
                if item.username == username:
                    messages.error(request, 'إسم المستخدم موجود بالفعل ')
                else:
                    new_user = User.objects.create_user(username=username, password=password)
                    new_account = Account.objects.create(name=name, user=new_user, branch=branch)
                    for unit in authorities:
                        if unit == 'إدارة المستخدمين':
                            section_obj = Section.objects.get(name=unit)
                            Rule.objects.create(account=new_account, section=section_obj)
                    return redirect('user_details', pk=new_account.id)
    else:
        add_user_form = AddUserForm(request.POST)
    context = {
        'add_user_form': add_user_form,
    }
    return render(request, 'users/users_create.html', context)

最后是我如何尝试使用 `unittest:

class TestCreateUser(TestCase):
    def setUp(self):
        new_user = User.objects.create_user(username='user', password='password')
        new_branch = Branch.objects.create(name='test branch')
        Account.objects.create(user=new_user, name='ay name', branch=new_branch)

    def test_visit_unauthorised(self):
        response = self.client.get('/user/create/')
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/login/?next=/user/create/')

    def test_visit_authorised(self):
        self.client.login(username='user', password='password')
        response = self.client.get('/user/create/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'users/users_create.html')

    def test_post_request_empty_data(self):
        self.client.login(username='user', password='password')
        response = self.client.post('/user/create/', {})
        self.assertFormError(response, 'add_user_form', 'username', 'This field is required.')
        self.assertFormError(response, 'add_user_form', 'password', 'This field is required.')
        self.assertFormError(response, 'add_user_form', 'name', 'This field is required.')
        self.assertFormError(response, 'add_user_form', 'branch', 'This field is required.')
        self.assertFormError(response, 'add_user_form', 'authorities', 'This field is required.')

    def test_post_request_invalid_data(self):
        self.client.login(username='user', password='password')
        new_branch = Branch.objects.create(name='test branch 2')
        the_list = ['ay 7aga', ' ay 7etta']
        text = 'just a text'
        for i in range(130):
            text += 'h'
        response = self.client.post('/user/create/',
                                    {'username': text, 'password': 'pass', 'name': text, 'branch': new_branch,
                                     'authorities': the_list})
        self.assertEqual(response.status_code, 200)

    def test_post_request_valid_data(self):
        self.client.login(username='user', password='password')
        new_branch = Branch.objects.create(name='test branch 3')
        the_list = [('إدارة المستخدمين', 'إدارة المستخدمين'), ('إدارة عامة', 'إدارة عامة')]
        text = 'just a text'
        response = self.client.post('/user/create/',
                                    {'username': text, 'password': 'pass', 'name': text, 'branch': new_branch,
                                     'authorities': the_list})
        self.assertEqual(response.status_code, 302)

错误总是来自与我的领域相关的这段代码:

    def test_post_request_valid_data(self):
        self.client.login(username='user', password='password')
        new_branch = Branch.objects.create(name='test branch 3')
        the_list = [('إدارة المستخدمين', 'إدارة المستخدمين'), ('إدارة عامة', 'إدارة عامة')]
        text = 'just a text'
        response = self.client.post('/user/create/',
                                    {'username': text, 'password': 'pass', 'name': text, 'branch': new_branch,
                                     'authorities': the_list})
        self.assertEqual(response.status_code, 302)

错误 AssertionError: 200 != 302

【问题讨论】:

  • 你想测试redirect
  • 是的,如果它给了我 302 那么它工作得很好,它重定向到结果页面。如果没有,它给了 200,那么它就不能正常工作。

标签: python django unit-testing


【解决方案1】:

测试redirect:

from django.urls import reverse

def test_post_request_valid_data(self):
    self.client.login(username='user', password='password')
    new_branch = Branch.objects.create(name='test branch 3')
    the_list = [('إدارة المستخدمين', 'إدارة المستخدمين'), ('إدارة عامة', 'إدارة عامة')]
    text = 'just a text'
    response = self.client.post('/user/create/',
                                {'username': text, 'password': 'pass', 'name': text, 'branch': new_branch,
                                 'authorities': the_list}, follow=True)
    self.assertRedirects(response, reverse('user_details', kwargs={'pk': "1"}))

【讨论】:

  • 没有修复它,我认为问题出在:the_list = [('إدارة المستخدمين', 'إدارة المستخدمين'), ('إدارة عامة', 'إدارة عامة')] 作为表单将这些数据视为无效类型或其他东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 2019-02-19
  • 2023-03-06
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
相关资源
最近更新 更多