Skip to content

Instantly share code, notes, and snippets.

@hugochinchilla
Created March 24, 2017 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugochinchilla/60c19fd63bcc3d67fbe24142d4579287 to your computer and use it in GitHub Desktop.
Save hugochinchilla/60c19fd63bcc3d67fbe24142d4579287 to your computer and use it in GitHub Desktop.
SqlAlchemy expression wrapper
from sqlalchemy.sql.elements import BinaryExpression
class C(object):
"""
This class is intend to be used in tests with unittest.mock.call
This class allows to wrap an sqlalchemy BinaryExpression in a way
you can compare a BinaryExpression agains a Wrapped BinaryExpression
to check if they are equivalent, as comparing them directly results
in another BinaryExpression.
e.g.:
operator_1 = ModelClass.name == 'example'
operator_2 = ModelClass.name == 'cool'
operator_3 = ModelClass.name == 'example'
operator_1 == operator_2 # This results in a BinaryExpression
C(operator_1) == operator_2 # This returns False
C(operator_1) == operator_3 # This returns True
C(operator_1) == C(operator_3) # This also returns True
"""
def __init__(self, comp):
if not isinstance(comp, BinaryExpression):
raise TypeError(
'An sqlalchemy.sql.elements.BinaryExpression was expected'
)
self.comp = comp
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.comp.compare(other.comp)
elif not isinstance(other, BinaryExpression):
raise TypeError(
'Right hand value must be sqlalchemy.sql.elements.BinaryExpression' # noqa
)
return self.comp.compare(other)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment