0

Basically I'm trying to do this:

class SeaLion(object):
    def __iter__(self):
        return self
    def next(self):
        ...

def train():
    sea_lion = SeaLion(...)
    for tooth in sea_lion:
        .. do something

Then in my test file I have:

class TestTrain(TestCase):
    @patch('module.SeaLion')
    def test_train(self, mock_SeaLion):
        mock_SeaLion.return_value = [1,2,3]
        ...

Basically I want sea_lion in the train function to be a list instead of an instance of that class.

With the above code sea_lion is MagicMock(name='SeaLion()')

Greg
  • 45,306
  • 89
  • 231
  • 297
  • `mock_SeaLion = MagicMock()` - you need to go read about [what assignment means in Python](http://nedbatchelder.com/text/names.html), because assigning a new value to your `mock_SeaLion` local variable is obviously wrong. – user2357112 Nov 14 '16 at 18:49
  • Good point. I took that line out. Same issue as before though. – Greg Nov 14 '16 at 18:52
  • Your solution should work. Can you clarify your question if not? – zanseb Nov 14 '16 at 19:02
  • Don't know if you are still having problems. But your code should be working. Is this your exact code? – idjaw Nov 15 '16 at 03:18

1 Answers1

2

Try this:

import unittest
from mock import patch

class SeaLion(object):
    def __iter__(self):
        return self

    def next(self):
        pass

def train():
    sea_lion = SeaLion()
    print(repr(sea_lion))
    for tooth in sea_lion:
        return True

    return False

class TestTrain(unittest.TestCase):
    @patch('__main__.SeaLion')
    def test_train(self, mock_SeaLion):
        mock_SeaLion.return_value = [1]
        self.assertTrue(train())

if __name__ == '__main__':
    unittest.main()

Result:

[1]
.
----------------------------------------------------------------------
Ran 1 test in 0.044s

OK
zanseb
  • 1,275
  • 10
  • 20