Я предлагаю вам создать собственный метод asserter (assertExtensiveFlightSearchGivesError(self, data, expected_error_message)
), чтобы удалить некоторые дубликаты:
class FlaskTestCase(unittest.TestCase):
def assertExtensiveFlightSearchGivesError(self, data, expected_error_message):
response = test_client.post("/flight_search/extensive", data=data)
self.assertEqual(4xx, response.status_code)
self.assertIn(expected_error_message, response.data, "extensive flight search did not contain expected error message")
def test_city_code(self):
self.assertExtensiveFlightSearchGivesError(
{'origin': 'xxx'},
b'That does not appear to be a valid city code'
)
def test_code_pairs(self):
self.assertExtensiveFlightSearchGivesError(
{'origin': "HFD", 'destination': "CAS"},
b'This origin-destination pair is not in searchable cache'
)
# ... and so on
Вы также можете собрать все тестовые примеры вместе и использовать .subTest()
:
TEST_CASES = [
({'origin': 'xxx'}, b'That does not appear to be a valid city code'),
({'origin': "HFD", 'destination': "CAS"}, b'This origin-destination pair is not in searchable cache')
]
class FlaskTestCase2(unittest.TestCase):
def assertExtensiveFlightSearchGivesError(self, data, expected_error_message):
response = test_client.post("/flight_search/extensive", data=data)
self.assertEqual(4xx, response.status_code)
self.assertIn(expected_error_message, response.data, "extensive flight search did not contain expected error message")
def test_all_error_cases(self):
for data, expected_error_message in TEST_CASES:
with self.subTest():
self.assertExtensiveFlightSearchGivesError(data, expected_error_message)
Но в вашем случае самый лучший пример кода IMO яснее.