我正在尝试为我编写的一个包含try/except
块的函数编写单元测试。
如果我的字符串包含少于3个字符,我已经引发了一个自定义异常。我想测试当输入一个长度小于3个字符的字符串时,错误是否会被引发。
运行函数时,如果我输入一个长度小于3个字符的字符串,例如"ha" - 我会得到正确的错误消息:"您的句子中没有足够的字母",这让我相信我已经正确地引发了自定义异常,然而,通过搜索我得知这意味着我在函数中没有引发自定义异常。我只是看不到或理解我哪里出错了。
函数文件:
from collections import Counter
# set custom exception to raise when a word with less than 3 letters is given
class NotEnoughLetters(Exception):
pass
# create a function that will return the 3 most common letters
def three_most_common(string: str):
string = string.replace(" ", "")
try:
if not all(char.isalpha() for char in string):
raise ValueError("Your input must contain a string") # using all because in this instance I haven't accounted for strings and ints mixed
if len(string) < 3:
raise NotEnoughLetters("There are not enough letters in your sentence")
most_common = Counter(string).most_common(3)
letters = [key for key, value in most_common]
except ValueError as err:
return err
except NotEnoughLetters as e:
return e
else:
return f"Here are your most common letters: 1) {letters[0]} 2) {letters[1]} 3) {letters[2]}"
finally:
print("The program is running, please wait for your output")
测试文件:
import unittest
from unittest import TestCase
from common_letters import three_most_common, NotEnoughLetters
class TestCommonLetters(TestCase):
# valid input
def test_good_string(self):
expected_input = "cheesy puff"
expected_output = "Here are your most common letters: 1) e 2) f 3) c"
result = three_most_common(expected_input)
self.assertEqual(expected_output, result) # add assertion here
# invalid input
def test_bad_string(self):
expected_input = "cheesy puff"
false_output = "Here are your most common letters: 1) f 2) f 3) e"
result = three_most_common(expected_input)
self.assertNotEqual(false_output, result)
# edge case 1, having 3 letters
def test_having_three_letters(self):
expected_input = "hay"
expected_output = "Here are your most common letters: 1) h 2) a 3) y"
result = three_most_common(expected_input)
self.assertEqual(expected_output, result)
# edge case 2, having 2 letters TODO this didn't work so get clarification tomorrow as to why not
def test_having_two_letters(self):
with self.assertRaises(NotEnoughLetters):
three_most_common(string="ha")
if __name__ == '__main__':
unittest.main()
这给我提供了以下输出:
Traceback (most recent call last):
File "C:\Homework-LivvyW\Homework-LivvyW\Homework_week7-LivvyW\test_common_letters.py", line 31, in test_having_two_letters
with self.assertRaises(NotEnoughLetters):
AssertionError: NotEnoughLetters not raised
我尝试过查看类似的stackoverflow问题/答案,但遗憾的是仍然不明白我哪里出错了。谢谢!
three_most_common
并没有引发那个异常,这正是测试失败所告诉你的。 - mkrieger1