我正在使用SQLAlchemy查询我的项目数据库。同时,我对单元测试还不熟悉,正在尝试学习如何编写单元测试来测试我的数据库。我尝试使用模拟库进行测试,但目前看来,这似乎非常困难。
因此,我编写了一段代码来创建一个
如您在单元测试中所见,我无法测试从第
上述编写单元测试用例的方法是否正确?是否有更好的方法?
因此,我编写了一段代码来创建一个
Session
对象。这个对象用于连接数据库。from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exc import OperationalError, ArgumentError
test_db_string = 'postgresql+psycopg2://testdb:hello@localhost/' \
'test_databasetable'
def get_session(database_connection_string):
try:
Base = declarative_base()
engine = create_engine(database_connection_string)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
connection = session.connection()
return session
except OperationalError:
return None
except ArgumentError:
return None
因此,我为这个函数编写了一个单元测试用例:
import mock
import unittest
from mock import sentinel
import get_session
class TestUtilMock(unittest.TestCase):
@mock.patch('app.Utilities.util.create_engine') # mention the whole path
@mock.patch('app.Utilities.util.sessionmaker')
@mock.patch('app.Utilities.util.declarative_base')
def test_get_session1(self, mock_delarative_base, mock_sessionmaker,
mock_create_engine):
mock_create_engine.return_value = sentinel.engine
get_session('any_path')
mock_delarative_base.called
mock_create_engine.assert_called_once_with('any_path')
mock_sessionmaker.assert_called_once_with(bind=sentinel.engine)
如您在单元测试中所见,我无法测试从第
session = DBSession()
行开始的get_session()
代码。到目前为止,在搜索后,我无法找出返回的模拟值是否也可以用于模拟函数调用 - 类似于,我模拟session
对象并验证是否调用了session.connection()
。上述编写单元测试用例的方法是否正确?是否有更好的方法?