简体   繁体   中英

Unit test for MultipleChoiceField in django tests always fails

I'm trying to do a unittest for a view with a post request with data for a form that has a MultipleChoiceField , but it always fails to success, here are my codes :

the from in 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)

and the 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)

And finally here is how I tried to use `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)

The error always comes from this block of code which is related to my field :

    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)

The Error AssertionError: 200 != 302

test 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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM