如何在 SQLAlchemy 中测试查询?例如假设我们有这个models.py
from sqlalchemy import (
Column,
Integer,
String,
)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Panel(Base):
__tablename__ = 'Panels'
id = Column(Integer, primary_key=True)
category = Column(Integer, nullable=False)
platform = Column(String, nullable=False)
region = Column(String, nullable=False)
def __init__(self, category, platform, region):
self.category = category
self.platform = platform
self.region = region
def __repr__(self):
return (
"<Panel('{self.category}', '{self.platform}', "
"'{self.region}')>".format(self=self)
)
还有这个tests.py
import unittest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base, Panel
class TestQuery(unittest.TestCase):
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
self.session.add(Panel(1, 'ion torrent', 'start'))
self.session.commit()
def tearDown(self):
Base.metadata.drop_all(self.engine)
def test_query_panel(self):
expected = [Panel(1, 'ion torrent', 'start')]
result = self.session.query(Panel).all()
self.assertEqual(result, expected)
当我们尝试运行测试时,它失败了,即使两个面板看起来相同。
$ nosetests
F
======================================================================
FAIL: test_query_panel (tests.TestQuery)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/clasher/tmp/tests.py", line 31, in test_query_panel
self.assertEqual(result, expected)
AssertionError: Lists differ: [<Panel('1', 'ion torrent', 's... != [<Panel('1', 'ion torrent', 's...
First differing element 0:
<Panel('1', 'ion torrent', 'start')>
<Panel('1', 'ion torrent', 'start')>
[<Panel('1', 'ion torrent', 'start')>, <Panel('2', 'ion torrent', 'end')>]
----------------------------------------------------------------------
Ran 1 test in 0.063s
FAILED (failures=1)
我发现的一个解决方案是对我希望在查询中找到的每个实例进行查询:
class TestQuery(unittest.TestCase):
...
def test_query_panel(self):
expected = [
(1, 'ion torrent', 'start'),
(2, 'ion torrent', 'end')
]
successful = True
# Check to make sure every expected item is in the query
try:
for category, platform, region in expected:
self.session.query(Panel).filter_by(
category=category, platform=platform,
region=region).one()
except (NoResultFound, MultipleResultsFound):
successful = False
self.assertTrue(successful)
# Check to make sure no unexpected items are in the query
self.assertEqual(self.session.query(Panel).count(),
len(expected))
不过,这让我觉得非常难看,而且我什至没有达到我想要测试的复杂过滤查询的地步。有没有更优雅的解决方案,还是我总是必须手动进行一堆单独的查询?