简体   繁体   English

如何在 Python 3 单元测试中模拟“with connect”SQL 查询?

[英]How do I mock a "with connect" SQL query in a Python 3 unit testing?

For a function like the below, where engine is a SQLAlchemy engine like,对于如下所示的 function,其中引擎是 SQLAlchemy 引擎,例如,

from sqlalchemy import create_engine
engine = create_engine(f'mysql+pymysql://{db_username}:{db_password}@{db_host}:{db_port}/{db_name}', pool_recycle=3600)
def pull(engine, afield):
    query = f"SELECT col1, col2 FROM mydatabase WHERE field='{afield}'"
    with engine.connect() as conn:
        result = conn.execute(query)
    return result

How do I mock the query result from the "with" statement in a unit test?如何模拟单元测试中“with”语句的查询结果?

Assuming the above function is in a file named datapull.py and located in the same directory as this unit test code, then the below is an example of mocking the SQL result.假设上面的 function 在一个名为datapull.py的文件中并且与这个单元测试代码位于同一目录中,那么下面是 mocking SQL 结果的示例。

Mocking the engine and connection are fairly simple, but mocking the engine to return the connection is trickier. Mocking 引擎和连接相当简单,但是 mocking返回连接的引擎比较棘手。

The with statement (described for Python 3 here ) returns the connection after __enter__ is called on the engine. with 语句(描述为 Python 3 here )在引擎上调用__enter__后返回连接。

Thus mock_engine.connect.return_value.__enter__.return_value = mock_conn will properly return the mock connection in the above code's with statement.因此mock_engine.connect.return_value.__enter__.return_value = mock_conn将在上述代码的 with 语句中正确返回模拟连接。

import mock
import unittest
import datapull


class TestQueryRDS(unittest.TestCase):
    def test_happy_day(self):
        """Test happy day query"""
        mock_conn = mock.MagicMock()
        mock_conn.execute.return_value = [['c1', 'c2'], ['a1', 'a2']]
        mock_engine = mock.MagicMock()
        mock_engine.connect.return_value.__enter__.return_value = mock_conn
        actual = datapull.pull(mock_engine, '1234abcd')
        assert actual == [['c1', 'c2'], ['a1', 'a2']]
        exp_sql = "SELECT col1, col2 FROM mydatabase WHERE field='1234abcd'"
        mock_conn.execute.assert_called_once_with(exp_sql)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM