【问题标题】:pytest - mock exception of method to test Flask APIpytest - 测试 Flask API 的方法的模拟异常
【发布时间】:2021-07-05 10:16:55
【问题描述】:

我想使用 pytest 和 mock 对以下 Flask API 进行单元测试:

    #api.py
    @api.route("/get_job/<job_name>")
        class JobStatus(Resource):
            @api.marshal_with(m_res)
            def get(self, job_name):
                try:
                    job_status = gcp.generate_signed_url("bucket_name", blob_path)
                except ValueError as e:
                    try:
                        client = kube.SparkApplicationClient()
                        job_status = client.get(job_name)["status"]["applicationState"]["state"]
                    except ApiException as e:
                        abort(404, "job doesn't exist: %s\n" % e)
                return {"job_status": job_status}

我为发送两个异常但补丁不起作用的情况编写了以下测试:

    #test_api.py    
    import pytest
    from unittest.mock import patch, MagicMock
    from kubernetes.client.rest import ApiException
    from api import server
        
    @pytest.fixture
    def app():
        app = server.app
        return app
        
        
    @patch("api.gcp.generate_signed_url", MagicMock(side_effect=Exception(ValueError)))
    @patch("api.kube.SparkApplicationClient.get", MagicMock(side_effect=Exception(ApiException)))
    def test_get_job_status_doesnt_exists(client):
        response = client.get(
            "/api/get_job/68987af5-ccf4-4c11-a89a-d6645b7f7"
        )
        assert response.status_code == 404

基本上我试图让gcp.generate_signed_url 和client.get(job_name) 在测试时引发异常

谢谢!!! :)

【问题讨论】:

    标签: python unit-testing flask pytest magicmock


    【解决方案1】:

    试试:

    @patch(
      "api.gcp.generate_signed_url", 
      side_effect=ValueError)
    )
    

    还有:

    @patch(
      "api.kube.SparkApplicationClient.get",
      **{
        'return_value.get.side_effect': ApiException
      }
    )   
    

    【讨论】:

      猜你喜欢
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2017-08-05
      相关资源
      最近更新 更多