关于python:使用self vs cls访问unittest中的变量

Using self vs cls to access variable in unittest

假设我有一个简单的类对象,它看起来像某种Counter(当然它还有其他函数,但它超出了这个问题的范围):

1
2
3
4
5
from collections import Counter

class Vocabulary:
    def __init__(self, words):
        self.vocab = Counter(words)

Vocabulary类添加到unittest中,我可以使用setUpClass类方法,如下所示:

1
2
3
4
5
6
7
8
9
10
import unittest

class VocabularyTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.vocab = Vocabulary(["z","a","b","c","f","d","e","g","a","d","b","e","w"])


    def test_counts_set_correctly(self):
        self.assertEqual(cls.vocab["a"], 2)

或者我可以只用self

1
2
3
4
5
6
7
class VocabularyTests(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(VocabularyTests, self).__init__(*args, **kwargs)
        self.vocab = Vocabulary(["z","a","b","c","f","d","e","g","a","d","b","e","w"])

    def test_counts_set_correctly(self):
        self.assertEqual(self.vocab["a"], 2)

以上两种方法都可以。但如果我有一种不和谐的模式呢:

1
2
3
4
5
6
7
8
9
10
import unittest

class VocabularyTests(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.vocab = Vocabulary(["z","a","b","c","f","d","e","g","a","d","b","e","w"])


    def test_counts_set_correctly(self):
        self.assertEqual(self.vocab["a"], 2)

根据python类中使用的"cls"变量是什么?,这只是一种编码约定,但是在使用self.vocab的UnitTest的第三个版本和使用@classmethod的前两个惯用测试之间有什么区别吗?


对于unittest.TestCase子类,不要在__init__中进行任何测试设置。这不是它的目的。如果希望每个测试方法执行一次设置,请将其放在此处:

1
2
def setUp(self):
    ...

如果希望每个测试类执行一次安装程序,请将其放在此处:

1
2
3
@classmethod
def setUpClass(cls):
    ...

最后,让我们来解决一个误解。技术上来说,这两者没有区别:

1
2
3
@classmethod
def setUpClass(cls):
    ...

还有这个:

1
2
3
@classmethod
def setUpClass(self):
    ...

第二种方法只是更混乱/不好地编写第一种方法。