jeudi 21 avril 2016

Testing return value of SQLAlchemy parent-child relationship query

Say I have two models set up like so:

class ParentFoo(SqlBase):
  __tablename__ = "parents"

  id = Column(String, primary_key=True)
  children = relationship("ChildFoo", backref="parents")

class ChildFoo(SqlBase):
  __tablename__ = "children"

  id = Column(String, primary_key=True)

Now in a request handler, say I want to get all children entities from the database given a parent:

class RequestHandler():

  def get(self, parent_id):
    parent = database.query(parent_id)
    children = parent.children
    send_response(children)

The SQLAlchemy ORM API allows this type of query. The problem for me is when I'm writing my tests. I have a generic RequestHandler class that takes a ParentFoo and a ChildFoo class as arguments in the constructor. So my request handler class actually looks like this:

class GenericRequestHandler():

  def __init__(self, parent_class, child_class):
    self.parent_class = parent_class
    self.child_class = child_class

  def get(self, parent_id):
    parent = database.query(self.parent_class, parent_id)
    children = parent.getattr(self.child_class.__tablename__, None)

As long as the column name on the parent matches the __tablename__ for the child entities, this will work. I enforce this convention. The problem is testing this.

Python's mock library doesn't seem to provide for return values on attribute lookups and I don't want to mock out the getattr function, because it's used elsewhere in my get method.

Any thoughts?

Aucun commentaire:

Enregistrer un commentaire