测试服务器时如何模拟来自集成服务的响应

时间:2020-04-12 14:50:54

标签: python testing mocking

长话短说,我正在构建一个充当聊天机器人的服务器。服务器使用Google对话框流程。现在,我暴露了一个端点,当我点击该端点时,它可以与我的服务器进行对话,同时会调用google auth和google对话框流。我正在尝试模拟对话流的响应,同时离开实际的服务器以响应网络调用。到目前为止,我的测试看起来像这样。

这是我的基本测试文件:

import unittest
import mock


class BaseTest(unittest.TestCase, object):
    def __init__(self, *args, **kwargs):
        super(BaseTest, self).__init__(*args, *kwargs)

    def auto_patch(self, patch_target):
        patcher = mock.patch(patch_target)
        patched = patcher.start()
        self.addCleanup(patcher.stop)
        return patched

这是我的测试文件:

import json
import uuid
from os import path
from tests.base_test import BaseTest
from agent.api_service import app
import requests_mock
import pytest
from hamcrest import assert_that, has_items, equal_to

CWD = path.dirname(path.realpath(__file__))


class TestAudio(BaseTest):
    def test__interact__full_no_stt(self):
        payload = json.load(open("tests/json_payloads/test__interact__full_audio.json"))
        u_session_id = str(uuid.uuid1())
        payload["session_id"] = u_session_id

        #mock a 500 back from STT
        with open("tests/json_payloads/stt_500.json", "r") as issues_file:
            mock_response = issues_file.read()

        with requests_mock.Mocker() as m:
            m.register_uri('POST', 'https://speech.googleapis.com/v1/speech:recognize', text=mock_response)



        request, response = app.test_client.post("/agent_service/interact", data=json.dumps(payload))
        self.assertEqual(200, response.status)

这是我的Google stt文件:

import json
import requests
from agent.exceptions import GoogleSTTException
from agent.integrations.google.google_auth_service import get_auth_token
from agent.integrations.google.google_stt_request import GoogleSTTRequest
from agent.integrations.google.google_stt_response import GoogleSTTResponse


def speech_to_text(audio_string):
    try:
        google_stt_request = GoogleSTTRequest(audio_string).to_payload()

        request_headers = dict()
        request_headers['Authorization'] = 'Bearer ' + get_auth_token()
        request_headers['Content-Type'] = 'application/json'

        url = 'https://speech.googleapis.com/v1/speech:recognize'
        google_response = requests.post(url, data=json.dumps(google_stt_request), headers=request_headers)
        response = GoogleSTTResponse(google_response.json())
        return response

    except Exception as e:
        raise GoogleSTTException('Received an error invoking google stt {}'.format(e))

有人对我如何模拟Google stt调用的响应而不接触google auth调用或服务器调用本身有任何想法吗?我尝试了一些事情,但到目前为止还没有运气。我要么什么都没有嘲笑,要么既是Google stt又是auth调用。

1 个答案:

答案 0 :(得分:0)

所以我最终离开了最初的实现,但这就是让我到那里的原因。

    @responses.activate
    def test__interact__full_no_stt(self):
        payload = json.load(open("tests/json_payloads/test__interact__full_audio.json"))
        u_session_id = str(uuid.uuid1())
        payload["session_id"] = u_session_id

        #mock a 500 back from STT
        responses.add(responses.POST,
                      'https://speech.googleapis.com/v1/speech:recognize',
                      json={'error': 'broken'}, status=500)



        request, response = app.test_client.post("/agent_service/interact", data=json.dumps(payload))
        self.assertEqual(200, response.status)
        result = response.json

响应使这一过程变得更加容易,只需确保在测试的顶部包括注释即可。