免责声明:这确实not回答你的问题。这只是一个如何使用的示例unittest
以编程方式(而不是从命令行)模块并捕获其输出(尽管not来自 IDLE 和/或作为 Tkinter 应用程序的一部分)。然而,这两件事(从另一个它运行测试并捕获结果)在您的 Tkinter 应用程序中都是必要的。)
正在测试的代码执行的一些操作与您的问题中的操作非常相似。
也就是说,用两种不同的方式对文本文件中的单词进行计数 - 实际上涉及两个单独的测试 - 一个使用collections.Counter
字典子类和另一个做同样的事情是“手动”完成的。然后将每个结果与预期结果进行比较。
内容如下very用于测试的简单测试文件:
Here's one line
And another line
And another line make three
这是代码:
import collections
from io import StringIO
import unittest
class TestWordCounts(unittest.TestCase):
TEST_FILENAME = './sample_e_input.txt'
EXPECTED_RESULT = {"heres": 1,
'one': 1,
'line': 3,
'and': 2,
'another': 2,
'make': 1,
'three': 1}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.get_text()
def test_collections_counter(self):
''' Count words collections.Counter. '''
counter = collections.Counter((word for word in self.clean_text.split()))
self.assertEqual(len(counter), len(self.EXPECTED_RESULT))
self.assertEqual(counter, self.EXPECTED_RESULT)
print('test_collections_counter passed')
def test_manual_count(self):
''' Count words manually. '''
word_counts = self.count_words(self.clean_text)
self.assertEqual(len(word_counts), len(self.EXPECTED_RESULT))
self.assertEqual(word_counts, self.EXPECTED_RESULT)
print('test_manual_count passed')
def get_text(self):
''' Read test file then convert to lowercase and remove punctuation. '''
with open(self.TEST_FILENAME, encoding="utf8") as file:
text = file.read()
cleaned = text.lower()
for substring in '. , : " \' ! *'.split():
cleaned = cleaned.replace(substring, "")
self.clean_text = cleaned
def count_words(self, file_text):
wordcount = collections.defaultdict(int)
for word in file_text.split():
wordcount[word] += 1
return dict(wordcount)
if __name__ == '__main__':
# Run unit test, capture output, and then print it.
output = StringIO()
tests = unittest.TestLoader().loadTestsFromTestCase(TestWordCounts)
test_result = unittest.TextTestRunner(stream=output).run(tests)
print(output.getvalue()) # Print captured output from running test.
打印输出:
test_collections_counter passed
test_manual_count passed
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK