如何使用pytest测试Django模型? [英] How to test a Django model with pytest?

查看:369
本文介绍了如何使用pytest测试Django模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开始使用pytest.我已经配置了pytest,无论如何我都无法在pytest的Django特定测试中找到资源.如何使用pytest_django测试模型?

I am getting started with pytest. I have configured pytest, anyway I couldn't found a resource on Django specific testing with pytest. How do I test a model with pytest_django?

我已经问过一个关于单元测试的问题,

I have already asked a question on unittesting,

如何有效地测试此Django模型?

我想知道如何用py.test编写相同的测试吗?

I want know how the same tests can be written with py.test?

在模型下方添加和用unittest编写的测试.

adding below the model and the tests written in unittest.

正在测试的模型是

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=25, unique=True, error_messages={
        'unique': 'The username is taken'
    })
    first_name = models.CharField(max_length=60, blank=True, null=True)
    last_name = models.CharField(max_length=60, blank=True, null=True)
    email = models.EmailField(unique=True, db_index=True, error_messages={
        'unique': 'This email id is already registered!'
    })

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    date_joined = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username',]


    objects = UserManager()

    def get_full_name(self):
        return ' '.join([self.first_name, self.last_name])

    def get_short_name(self):
        return self.email

    def __unicode__(self):
        return self.username

unittest写成

class SettingsTest(TestCase):    
    def test_account_is_configured(self):
        self.assertTrue('accounts' in INSTALLED_APPS)
        self.assertTrue('accounts.User' == AUTH_USER_MODEL)


class UserTest(TestCase):
    def setUp(self):
        self.username = "testuser"
        self.email = "testuser@testbase.com"
        self.first_name = "Test"
        self.last_name = "User"
        self.password = "z"

        self.test_user = User.objects.create_user(
            username=self.username,
            email=self.email,
            first_name=self.first_name,
            last_name=self.last_name
        )

    def test_create_user(self):
        self.assertIsInstance(self.test_user, User)

    def test_default_user_is_active(self):
        self.assertTrue(self.test_user.is_active)

    def test_default_user_is_staff(self):
        self.assertFalse(self.test_user.is_staff)

    def test_default_user_is_superuser(self):
        self.assertFalse(self.test_user.is_superuser)

    def test_get_full_name(self):
        self.assertEqual('Test User', self.test_user.get_full_name())

    def test_get_short_name(self):
        self.assertEqual(self.email, self.test_user.get_short_name())

    def test_unicode(self):
        self.assertEqual(self.username, self.test_user.__unicode__())

谢谢您的投入.

推荐答案

pytest支持运行Python unittest.py样式测试.它旨在利用现有的unittest风格的项目来使用pytest功能.具体而言,pytest将自动在测试文件中收集unittest.TestCase子类及其测试方法.它将调用典型的安装/拆卸方法,并通常尝试使编写的测试套件可以在unittest上运行,也可以使用pytest来运行.

pytest has support for running Python unittest.py style tests. It’s meant for leveraging existing unittest-style projects to use pytest features. Concretely, pytest will automatically collect unittest.TestCase subclasses and their test methods in test files. It will invoke typical setup/teardown methods and generally try to make test suites written to run on unittest, to also run using pytest.

给定的测试可以使用py.test进行测试,而无需进行任何修改,但是py.test使测试更具有Pythonic性.

The given tests can be tested with py.test without any modification, however py.test makes the tests more pythonic.

class SettingsTest(TestCase):    
    def test_account_is_configured(self):
        assert 'accounts' in INSTALLED_APPS
        assert 'accounts.User' == AUTH_USER_MODEL


class UserTest(TestCase):
    def setUp(self):
        self.username = "testuser"
        self.email = "testuser@testbase.com"
        self.first_name = "Test"
        self.last_name = "User"
        self.password = "z"

        self.test_user = User.objects.create_user(
            username=self.username,
            email=self.email,
            first_name=self.first_name,
            last_name=self.last_name
        )

    def test_create_user(self):
        assert isinstance(self.test_user, User)

    def test_default_user_is_active(self):
        assert self.test_user.is_active

    def test_default_user_is_staff(self):
        assert not self.test_user.is_staff

    def test_default_user_is_superuser(self):
        assert not self.test_user.is_superuser

    def test_get_full_name(self):
        assert self.test_user.get_full_name() == 'Test User'

    def test_get_short_name(self):
        assert self.test_user.get_short_name() == self.email

    def test_unicode(self):
        assert self.test_user.__unicode__() == self.username

如@Sid所述,您可以在运行测试时使用@pytest.mark.django_db标记(修饰符)访问数据库,而无需使用django.test.TestCase

as @Sid mentioned, you can use the @pytest.mark.django_db marker (decorator) to access the database when running a test without using django.test.TestCase,

这篇关于如何使用pytest测试Django模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆