小编tim*_*78h的帖子

模拟方法的返回值不起作用

在测试该create_response方法时,我似乎无法模拟该方法的返回值get_external_response

/foo/响应

from abc import ABCMeta, abstractmethod


def create_response(url, type):
    query = create_query(url, type)
    external_response = get_external_response(query)  <-- what I want to mock
    return external_response

def create_query(url, type):
    cc = MyFactory
    return cc.get_concrete_class(url, type)

def get_external_response(cc):
    return cc.make_query()


class MyAbstractClass(metaclass=ABCMeta):
    def __init__(self, url, type):
        self.url = url
        self.type = type
        self.query = self.make_query()

    @abstractmethod
    def make_query(self):
        pass

class MyFactory:
    @staticmethod
    def get_concrete_class(url, type):
        if type == 'A':
            return MyClass(url, type)
        else:
            print("not valid type")

class MyClass(MyAbstractClass): …
Run Code Online (Sandbox Code Playgroud)

mocking python-3.x python-mock

7
推荐指数
1
解决办法
9917
查看次数

How to mock raise urllib errors

After reading this in the python docs, I am catching the HTTPError and URLError exceptions in get_response_from_external_api that the make_request_and_get_response (via urllib's urlopen call) can raise:

foo.main.py

from urllib.request import urlopen
import contextlib
from urllib.error import HTTPError, URLError

def make_request_and_get_response(q):
    with contextlib.closing(urlopen(q)) as response:
        return response.read()

def get_response_from_external_api(q):
    try:
        resp = make_request_and_get_response(q)
        return resp
    except URLError as e:
        print('Got a URLError: ', e)
    except HTTPError as e:
        print('Got a HTTPError: ', e)

if __name__ == "__main__":
    query = …
Run Code Online (Sandbox Code Playgroud)

mocking urllib pytest python-3.x pytest-mock

6
推荐指数
1
解决办法
162
查看次数

标签 统计

mocking ×2

python-3.x ×2

pytest ×1

pytest-mock ×1

python-mock ×1

urllib ×1