python - Django:优化违反 DRY 的测试

标签 python django testing dry django-testing

正在测试的模型是

class A(models.Model):
    """ model A"""
    name = models.CharField(max_length=50, unique=True)
    slug = AutoSlugField(max_length=265, unique=True, populate_from='name')
    link = models.URLField(blank=True)

    class Meta:
        verbose_name = 'Model A'

    def __unicode__(self):
        return self.name

class B(models.Model):
    """ model B"""
    name = models.CharField(max_length=50, unique=True)
    slug = AutoSlugField(max_length=265, unique=True, populate_from='name')
    link = models.URLField(blank=True)

    class Meta:
        verbose_name = 'Model B'

    def __unicode__(self):
        return self.name

给定模型的简单测试,

class TestA(TestCase):
    """ Test the A model """

    def setUp(self):
        self.name = 'A'
        self.slug = 'a'
        self.object = A.objects.create(name=self.name)

    def test_autoslug_generaton(self):
        """ test automatically generated slug """
        assert self.object.slug == self.slug

    def test_return_correct_name(self):
        """ test the __unicode__() method """
        assert self.object.__unicode__() == self.name

class TestB(TestCase):
    """ Test the A model """

    def setUp(self):
        self.name = 'B'
        self.slug = 'b'
        self.object = B.objects.create(name=self.name)

    def test_autoslug_generaton(self):
        """ test automatically generated slug """
        assert self.object.slug == self.slug

    def test_return_correct_name(self):
        """ test the __unicode__() method """
        assert self.object.__unicode__() == self.name

这里的测试违反了 DRY,因为测试只是模型更改后的重复。如何重构测试,因为它不违反 DRY?

DRY- Dont Repeat Yourself, a software development philosophy which aims at reducing redundancy and code repetition.

谢谢。

最佳答案

正如 @mevius 评论中指出的答案中提到的,多重继承是一种可行的方法。为重复的测试方法创建一个Mixin,并在实际的测试类中实现setUptearDown:

class MixinAB(object):

    def test_autoslug_generaton(self):
        """ test automatically generated slug """
        assert self.object.code == self.slug

    def test_return_correct_name(self):
        """ test the __unicode__() method """
        assert self.object.__unicode__() == self.name


class TestA(MixinAB, TestCase):
    """ Test the A model """

    def setUp(self):
        self.name = 'A'
        self.slug = 'a'
        self.object = A.objects.create(name=self.name)

关于python - Django:优化违反 DRY 的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516387/

相关文章:

python - Django 测试 : no data in temporary database file

python - 在 Django 中计算大型数据集

python - DJango 1.8 在子模板上使用完全不同的 CSS

testing - JMeter JSR223 后处理器获取 Cookie

python - 如何解析txt文件末尾的json格式文本

python - 未找到 TestLink xmlrpc API(通过 Python)404

python - 来自 pandas 系列的 Spark DataFrame

python - 在谷歌驱动器上创建一个文件夹(如果不存在)并使用 Python 脚本将文件上传到它

javascript - JS 测试 : Trigger jQuery keypress event from CasperJS and PhanthomJS

java - 测试字符串是否为 Java 变量标识符 : (a-z, A-Z,_,$) 后跟 (a-z,A-Z,0-9,_,$)