Skip to content

Instantly share code, notes, and snippets.

@mitgr81
Last active March 19, 2021 12:55
Show Gist options
  • Save mitgr81/6358501 to your computer and use it in GitHub Desktop.
Save mitgr81/6358501 to your computer and use it in GitHub Desktop.
Unit testing sqlalchemy filters
#...somewhere above self.model = some SQLAlchemy model
def shoes(self):
filter1 = self.model.shoe == 'donkey'
self.model.query.filter(filter1)
def shoes2(self):
filters = []
# filters.append(self.model.shoe <= 'donkey')
filters.append(getattr(operator, 'le')(self.model.shoe, 'donkey'))
filters.append(getattr(operator, 'eq')(self.model.donkey, 'shoe'))
filters.append(self.model.donkey.like('shoe'))
self.model.query.filter(*filters)
import unittest
from mock import MagicMock
from controller import BaseController # SUT
class TestWBCoreControllersList(unittest.TestCase):
maxDiff = None
def setUp(self):
self.controller = BaseController()
self.mock_model = self.controller.model = MagicMock()
self.mock_model.return_value = self.mock_model
self.mock_model.__name__ = 'ThingyModel'
def test_idea(self):
shoe_eq = self.mock_model.shoe.__eq__ = MagicMock('shoe equal')
self.controller.shoes()
shoe_eq.assert_called_once_with('donkey')
self.mock_model.query.filter.assert_called_once_with(self.mock_model.shoe.__eq__.return_value)
def test_idea2(self):
shoe_eq = self.mock_model.shoe.__le__ = MagicMock('shoe less equal')
donkey_eq = self.mock_model.donkey.__eq__ = MagicMock('donkey equal')
donkey_like = self.mock_model.donkey.like = MagicMock('donkey like')
self.controller.shoes2()
shoe_eq.assert_called_once_with('donkey')
donkey_eq.assert_called_once_with('shoe')
donkey_like.assert_called_once_with('shoe')
self.mock_model.query.filter.assert_called_once_with(shoe_eq.return_value, donkey_eq.return_value, donkey_like.return_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment