python 单元测试:对外部文件应用测试

python unittesting: applying a test on an external file

我写了一个简短的脚本来测试我保存在不同文件夹中的文本文件的第一个单词是否全部以大写字母开头。但是,我意识到 self...append 方法不能正常工作。这是代码:

import os
import unittest

DIRECTORY= os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
text_file = os.path.join(DIRECTORY, '/data/text_folder')

class TestAugmentation (unittest.TestCase):

    def __init__(self,  *args, **kwargs):
        super(TestAugmentation, self).__init__(*args, **kwargs)

        self.file = os.path.join(text_file, 'test.txt') 
        self.text = [] # the list of the augmented text

    def test_reader(self):
        with open(self.file) as f:
           data = f.readlines()
        for element in data:
           self.text.append(element.strip())

    def test_capitalization(self):
        for entry in [entry for entry in self.text]:
            self.assertTrue(entry.split[0].isupper(), 'The sentence starts with a lowercase')


if __name__ == '__main__':
    unittest.main()

特别是我想将 test.txt 文件的内容附加到 self.text 列表中,这样我就可以在所有其他函数中使用它来与 test_capitalization 函数。但是,追加似乎不起作用。

test.txt 文件包含如下示例句子,我希望看到错误,因为并非所有句子都以大写字母开头。

'The weather is nice'

'the first chapter is fine'

'Her name is Lucy' ...

根据您的代码,我假设每个句子都在单独的一行中。 您的代码中有几处是有问题的。 首先,风格问题:设置单元测试通常在 setUp 中完成,而不是在 __init__.
中完成 其次,test_reader 不是测试,而是设置的一部分,或者可以在测试本身中完成。相互依赖的测试是不好的做法,也测试不测试任何东西的功能。

您的测试不起作用,因为 test_reader test_capitalization 之后执行 -- 默认情况下 unittest 按字母顺序排列测试。

因此,这是一个工作版本的示例,前提是您的代码中假定每行有一个句子:

class TestAugmentation(unittest.TestCase):

    def setUp(self):
        self.file = os.path.join(text_file, 'test.txt')

    def test_capitalization(self):
        for line in open(self.file):
            line = line.strip()
            if line:  # ignore empty lines
                self.assertTrue(line[0].isupper(),
                                f'{line} starts with a lower case letter')

或者如果你想在设置中读取文件,因为你在其他测试中需要它,你也可以这样写:

class TestAugmentation(unittest.TestCase):

    def setUp(self):
        file_path = os.path.join(text_file, 'test.txt')
        self.text = []
        for line in open(file_path):
            line = line.strip()
            if line:
                self.text.append(line)

    def test_capitalization(self):
        for line in self.text:
            self.assertTrue(line[0].isupper(),
                            f'{line} starts with a lower case letter')

请注意,在这种情况下,文件会在每次测试前读取。 如果你在测试中只阅读一次 class,你可以使用 setUpClass 代替:

    def setUpClass(cls):
        file_path = os.path.join(text_file, 'test.txt')
        cls.text = []
        for line in open(file_path):
            ...