【发布时间】:2020-03-15 07:16:02
【问题描述】:
我有一个端点,它从我的数据库中返回一个列表。如果在此过程中出现问题,我会返回一个 internal_server_error,它有 500 个 status_code 和一条消息作为参数。
def get_general_ranking():
try:
ranking_list = GamificationService.get_general_ranking()
return basic_response(ranking_list, 200)
except Exception as e:
logging.error(str(e))
cache.delete()
return internal_server_error_response('Could not get ranking. Check log for reasons.')
我正在对此端点进行单元测试。所以,现在,我有这个实现:
class TestGamificationController(unittest.TestCase):
def setUp(self):
"""
Function called when the class is initialized.
"""
test_app = app.test_client()
self.general_ranking = test_app.get('/v1/gamification/general_ranking')
def test_endpoint_general_ranking(self):
"""
Testing the endpoint '/v1/gamification/general_ranking'.
"""
assert self.general_ranking.status_code == 200, "Wrong status code."
assert len(self.general_ranking.json) > 0, "/v1/gamification/general_ranking is returning an empty list."
assert self.general_ranking.content_type == 'application/json', "Wrong content_type"
但是,如下所示,当我运行覆盖率测试以检查我是否覆盖了 100% 的代码时,我得到了 75%。缺少的行是例外行。
---------- coverage: platform darwin, python 3.8.0-final-0 -----------
Name Stmts Miss Cover Missing
------------------------------------------------------------------------
api/controller/GamificationController.py 16 4 75% 18-21
缺少的行:
except Exception as e:
logging.error(str(e))
cache.delete()
return internal_server_error_response('Could not get ranking. Check log for reasons.')
如何使用 pytest 也解决这个异常?还是我应该使用其他东西?
【问题讨论】:
-
您的问题中没有任何
pytest测试。 -
@TheIncorrigible1 我可能不得不使用 pytest 来解决这个问题。但我会将这个添加到问题中。谢谢。
标签: python unit-testing exception flask pytest