作为装饰器的mock.patch()和上下文管理器之间的区别

时间:2019-12-06 10:05:44

标签: python unit-testing mocking aiohttp

我有一个模拟问题,使用装饰器@mock.patch时无法解决数小时,但是在尝试使用上下文管理器时立即解决了。我想问的是,它在引擎盖下的工作方式是否还有其他差异?说到 more ,我的意思不仅仅是设置模拟上下文。

我的示例是关于模拟aiohttp服务器的数据库连接。测试如下:

backend / tests / test_server.py

# source: https://docs.aiohttp.org/en/stable/testing.html#unittest

from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from alchemy_mock.mocking import AlchemyMagicMock
from backend.app import create_app
from datetime import datetime
from unittest import mock

import aiohttp
import asyncio
import json


class MyAppTestCase(AioHTTPTestCase):
    """
    Class for testing aiohttp server

    Methods
    -------
    ...
    test_get_version()
        Test response for GET /version
    """

    @mock.patch('backend.app.SessionProvider')
    async def get_application(self, mock_sess_prov):
        mock_sess_prov.session = AlchemyMagicMock()
        mock_sess_prov.start_session = lambda: None
        return create_app()

...


    @unittest_run_loop
    async def test_get_version(self):
        """Test response for GET /version

            ------------
            Verification
            Answer comparison
        """
        resp: aiohttp.ClientResponse =\
            await self.client.request("GET", "/version")
        assert resp.status == 200
        text = await resp.text()
        assert "Project version is 0.1" in text

所以问题出在get_application()方法上。当我如上所述进行模拟时,由于没有模拟目标类SessionProvider并尝试创建SqlAlchemy会话对象,所以我收到错误消息。当我重建时提到的功能如下:

async def get_application(self):
    with mock.patch('backend.app.SessionProvider') as mock_sess_prov:
        mock_sess_prov.session = AlchemyMagicMock()
        mock_sess_prov.start_session = lambda: None
        return create_app()

一切都很好。为了提供有关我的应用程序工作方式的更多信息,我粘贴了我的应用程序代码和会话管理器:

后端/后端/app.py:

from aiohttp import web
from backend.schema import ReservationSchema
import marshmallow.exceptions
from backend.models import Reservation, ValidationError
from backend.session_provider import SessionProvider
from sqlalchemy.exc import IntegrityError

import json
import logging


async def version(request) -> web.Response:
    """GET /version endpoint

    Returns API version

    Returns
    -------
    web.Response
        Http response object
    """
    text: str = "Project version is 0.1"
    return web.Response(text=text)


async def new_reservation(request) -> web.Response:
    """POST /new-reservation endpoint

    Create new reservation

    Returns
    -------
    web.Response
        Http response object
    """

    # TODO: How to check that object?
    body = await request.json()
    # json_obj = json.loads(body)
    if type(body) is str:
        body = json.loads(body)
    try:
        reservation: Reservation = ReservationSchema().load(body)
        SessionProvider.session.add(reservation)
        SessionProvider.session.commit()
        return web.Response(text='OK')
    except IntegrityError:
        return web.Response(text='ERR: No restaurant has given id')
    except marshmallow.exceptions.ValidationError as e:
        return web.Response(text='ERR: Failed validation:\n' + str(e))
    except ValidationError as e:
        return web.Response(text='ERR: Failed validation:\n' + str(e))


def create_app() -> web.Application:
    """Creates application object with routing

    Returns
    -------
    web.Application
        Application object
    """
    SessionProvider.start_session()
    app = web.Application()
    app.add_routes([web.get('/version', version),
                    web.post('/new-reservation', new_reservation)])
    return app


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    app = create_app()
    web.run_app(app, port=8000)

后端/后端/session_provider.py:

from backend.config import DATABASE_URI
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


class SessionProvider:

    engine = None
    sess_maker = None
    session = None

    @classmethod
    def start_session(cls):
        # DATABASE_URI = f"postgres+psycopg2://postgres:example@localhost:5433/restro"
        cls._engine = create_engine(DATABASE_URI)
        cls.sess_maker = sessionmaker(bind=cls._engine)
        # create a Session
        cls.session = cls.sess_maker()

所以我的第一个猜测可能是与路径有关,但是当我发现与上下文管理器完全相同的mock.patch('backend.app.SessionProvider')可以正常工作时,我开始怀疑它。您是否知道为什么一种方法不起作用而第二种方法却不起作用?最后,我想分享我的项目树,也许这可以帮助我们找到答案:

project tree

0 个答案:

没有答案