Python unit test failing for api

  Kiến thức lập trình

I have a python api like for which i am writing unit test case for both success as well as exception scenario. When i am running both of it its failing for 1 but passing for the other unit test case. Help me in fixing it.

Api code:

@router.post('/cold-start/rule', status_code=201)
async def create_cold_start_rule(request: List[ColdStartCreateRequestModel]):
    """
    function to create cold start rule
    """
    try:
        return await cm_service.add_cold_start_data(request)
    except (ColdStartRuleException) as ex:
        return JSONResponse(content={"errorMessage": ex.message}, status_code=ex.code)
    except Exception as ex:
        raise ColdStartRuleException(str('Failed to create'))

Unit test:

class TestColdstartAPI(IsolatedAsyncioTestCase):

    @patch('service.coldstart_management_service.ColdstartMgmtService', autospec=True)
    @patch('configuration.application_config_parser.AppConfigParser', autospec=True)
    def setUp(self, mock_app_conf, cm_service):

        mock_cm_service = cm_service.return_value
        mock_cm_service.get_cold_start_data.return_value = {"cold_start_data": True}
        mock_cm_service.get_cold_start_sorted_data.return_value = {"cold_start_data": True}
        mock_cm_service.update_cold_start_data.return_value = {"cold_start_data_updated": True}
        if self._testMethodName == "test_coldstart_post_failure_response":
            mock_cm_service.add_cold_start_data.side_effect = SearchRankingException(message="invalid conn exception")
        else:
            mock_cm_service.add_cold_start_data.return_value = {"cold_start_data_added": True}
        mock_cm_service.delete_cold_start_rule.return_value = {"cold_start_rule_deleted": True}
        mock_cm_service.delete_cold_start_data.return_value = {"cold_start_data_deleted": True}

        self.obj = {
        "product_id": "6001926991"
        }
        
        from src.main.com.lowes.ranking.api.coldstart_management_api import router as app
        self.client = TestClient(app)

    def test_coldstart_post_failure_response(self):
        try:
            self.client.post("/cold-start/rule", json=[self.obj])
        except Exception as e:
            self.assertEqual(e.status_code, 500)


    def test_coldstart_post_success_response(self):
        response = self.client.post("/cold-start/rule", json=[self.obj])
        self.assertEqual(response.status_code, 201)
        self.assertDictEqual(response.json(), {"cold_start_data_added": True})

2

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT