Question

I want to stub out a database call when I test a method I have in my code. All I want it to do is return me values but I cannot seem to get that far.

def loadSummary(appModel):
    stmt = 'Select * from Table'
    for row in appModel.session.query(*t.columnNames()).from_statement(stmt).all():
        t.append(row)
    return t

def test_loadSummary(self):
    appModel = Mock()
    query = appModel.session.query.return_value
    query.from_statment.return_value = ['test1', 'test2']
    expected = loadSummary(appModel)

I get the following error

for row in appModel.session.query(*t.columnNames()).from_statement(stmt).all():
TypeError: 'Mock' object is not iterable

So its like its not getting passed into the method at all even though it works in the shell no problem.

>>> appModel.session.query('').from_statment('stmt')
['test1', 'test2']

I then tried using mock.patch.object

class MockAppContoller(object):
    def from_from_statement(self, stmt):
        return ['test1', 'test2']

def test_loadSummary(self):
    with mock.patch.object(loadSummary, 'appModel') as mock_appModel:
        mock_appModel.return_value = MockAppContoller()

I get the following error

2014-04-09 13:20:53,276 root ERROR Code failed with error:
<function loadSummary at 0x0D814AF0> does not have the attribute 'appModel'

How can I get around this problem?

Was it helpful?

Solution

Your error appears to be here:

 query.from_statment.return_value = ['test1', 'test2']

Should be:

 query.from_statement.return_value.all.return_value = ['test1', 'test2']

It works in the shell for you because you aren't using the same code

>>> appModel.session.query('').from_statement('stmt')
['test1', 'test2']

Would fail if you actually tried

>>> appModel.session.query('').from_statment('stmt').all()
['test1', 'test2']

OTHER TIPS

Another solution I came up with was this but its not as neat as using Mock

class mockAppModel(object):
    def from_from_statement(self, stmt):       
        t = []
        t.appendRow('row1', 'row2')
        return t

class mockFromStmt(object): #This is the ONE parameter constructor
    def __init__(self):
        self._all = mockAppModel()

    def all(self):  #This is the needed all method
        return self._all.from_from_statement('')

class mockQuery(object): #This is the ONE parameter constructor
    def __init__(self):
        self._from_statement = mockFromStmt()

    def from_statement(self, placeHolder): #This is used to mimic the query.from_statement() call
        return self._from_statement 

class mockSession(object):
    def __init__(self):
        self._query = mockQuery()

    def query(self, *args):  #This is used to mimic the session.query call
        return self._query

class mockAppModel(object):
    def __init__(self):
        self.session = mockSession()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top