python3.6 @ mock.patch不嘲笑request.request

时间:2019-02-27 02:18:18

标签: python unit-testing mocking

我有一个名为test_voting_utils.py的测试类,位于root / mycity / mycity / test / unit_tests / test_voting_utils.py

该类如下:

import mycity.test.unit_tests.base as base
import unittest.mock as patch
import mycity.test.test_constants as test_constants
import mycity.utilities.voting_utils as vote_utils
import mycity.intents.intent_constants as intent_constants


class VotingUtilitiesTestCase(base.BaseTestCase):

    # @mock.patch('mycity.utilities.voting_utils.requests')
    # def test_get_ward_precinct_info(self, mock_get):
    #     mock_resp = self._mock_response(status=200, 
    #         json_data=test_constants.MOCK_WARD_PRECINCT_RESP)
    #     mock_get.return_value = mock_resp
    #     expected_output_text = test_constants.WARD_PRECINCT
    #     result = vote_utils.get_ward_precinct_info(test_constants.COORDS)
    #     self.assertEquals(expected_output_text, result)

    @patch('requests.request')
    def test_get_polling_location(self, mock_get):
        mock_resp = self._mock_response(status=200, 
            json_data=test_constants.MOCK_POLL_RESP)
        mock_get.return_value = mock_resp
        expected_output_text = test_constants.POLL_DATA
        result = vote_utils.get_polling_location(test_constants.WARD_PRECINCT)
        self.assertEquals(expected_output_text, result)

然后,我导入一个我要在上面测试的文件,名为root_mycity / mycity / utilities / voting_utils.py的voting_utils.py。 这是该文件:

import requests
import json
import re


def get_polling_location(ward_precinct):
    """
    Returns dictionary containing location name and address from the provided ward and precinct

    :param ward_precinct: dictionary object containing the ward and precinct
    :return: Dict containing location address string and
        location name string
    """
    requests.request("http://test.com")

现在,我不确定为什么不能在test_get_polling_location方法中模拟我的请求对象。我已经尝试过@mock.patch('mycity.mycity.utilities.voting_utils.requests')和其他各种形式,但是每种形式似乎都不起作用。我可能在滥用补丁程序,但我找不到确切的信息。我自己运行单元测试时出现的错误如下:

o_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 8] nodename nor servname provided, or not known>

我的理解是,我没有正确地模拟对象,而实际上是在尝试调用url。但是我不知道如何使它正常工作。

0 个答案:

没有答案