如何使用flask和pytest测试一个端点异常?

2024-04-26 11:00:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从数据库返回列表的端点。如果在此过程中出现问题,我将返回一个内部服务器错误,其中包含500个状态代码和一条消息作为参数

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来覆盖这个异常呢?还是我应该用别的


Tags: testselfappgetreturnresponsedeferror