Django测试中MultipleChoiceField的单元测试始终失败

时间:2019-06-02 14:38:42

标签: python django unit-testing

我正在尝试为具有发布请求且包含unittest的表单数据的视图做一个MultipleChoiceField,但是它总是失败,这是我的代码:

来自 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

1 个答案:

答案 0 :(得分: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"}))