使用Django单元测试发布数据未保存到后端

时间:2018-07-27 08:20:24

标签: django django-testing

我正在创建一个django应用程序,该应用程序在设计应用程序之前就实现了我的大部分逻辑。 我创建了一个用于用户注册的测试用例,但是每当我发布到注册URL时,它都会收到我发布的数据,但永远不会将其填充到数据库中。

class AuthTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test_reg_index(self):
        response = self.client.get(reverse_lazy('register'))
        return self.assertEqual(response.status_code, 200)

    def test_registration(self):
        data = {
            'last_name': 'test_user',
            'first_name': 'test_user',
            'email': 'fashtop3@gmail.com',
            'phone': '08035112897',
        }
        response = self.client.post(reverse_lazy('register'), data)

        self.assertEqual(response.status_code, 302)

    def test_login(self):
        # self.client.login(username='foo', password='bar')  # request.user is now user foo
        data = {
            'email': 'test_user@example.com',
            'password': 'pass123',
        }
        response = self.client.post(reverse_lazy('login'), data)

        self.assertEqual(response.status_code, 200)
class RegisterView(FormView):
    """
    this handles users registration
    """
    form_class = RegForm
    template_name = "club/register.html"
    success_url = reverse_lazy("register")

    # def get(self, request, *args, **kwargs):
    #     return super(RegisterView, self).get(request, *args, **kwargs)

    def form_invalid(self, form):
        print(form.errors.as_data)
        return super().form_invalid(form)

    def form_valid(self, form):
        """
        Process valid registration form
        :param form:
        :return: redirects to success_url
        """
        random_password = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(6))
        try:
            with transaction.atomic():
                """Allow database transactions"""
                data = form.cleaned_data
                user = User.objects.create_user(
                    email=data['email'],
                    password=random_password,
                    remember_token=hashlib.sha1(str(datetime.now()).encode('utf-8')).hexdigest()
                )
                user.profile.last_name = data['last_name']
                user.profile.first_name = data['first_name']
                user.profile.phone = data['phone']
                user.save()
                send_notification.delay(user.pk, random_password)
                print('Reg success')
                messages.success(self.request, "Regular successfully registered "
                                               "please check your mail for verification",
                                 extra_tags="alert-success")
        except IntegrityError as e:
            print(e)
            messages.error(self.request, "Registration Failed: Email address already exist", extra_tags="alert-danger")
            return super(RegisterView, self).form_invalid(form)
        except Exception as e:
            print(str(e))
            messages.error(self.request, "Registration Error, contact site administrator: ", extra_tags="alert-danger")
            return super(RegisterView, self).form_invalid(form)

        return super(RegisterView, self).form_valid(form)

3 个答案:

答案 0 :(得分:3)

TestCase类将每个测试包装在一个事务中,该事务将在事务之后回滚(请参阅相关的documentation)。

即使test_registration成功注册了用户,也无法在test_login中使用它。

我建议创建一个setUpClass方法进行测试的用户。

答案 1 :(得分:0)

大约两天后,我就解决了Qts .. 为了在成功进行单元测试后保留数据,您必须从unittest继承一个TestCase,否则要执行自动回滚,然后从django.test导入TestCase。

答案 2 :(得分:0)

为此,您需要使用 import unittest 而不是 from django.test import TestCase

并且在您的单元测试类中使用 unittest.TestCase

扩展 TestCase

看下面的例子

import unittest 
class MyTest(unittest.TestCase):
    .......