3

I have a test function (inside a unitttest.TestCase) that looks something like this:

@patch('some.list')
def test_thing(self, mocklist):
  # some setup code
  mocklist.__iter__.return_value = self.preCreatedList
  with patch('some.other.object', new=self.preCreatedObject):
    #some.other.object uses the mocked list internally
    self.assertEqual(some.other.object.sut('foo'), fooResult)
    self.assertEqual(some.other.object.sut('bar'), barResult)
    mocklist.__iter__.return_value = ['bogusList']
    self.assertEqual(some.other.object.sut('foo'), failureResult)

With the last assertion, of course, I want to confirm correct behavior if the list contains an invalid item.

The problem is this: when I print the list from inside the function under test, it is always equal to preCreatedList. In spite of the assignment before the final assertion, it does not get set to ['bogusList']. Why?

Python 2.7.5, running tests with nose2.

Note: Please set aside the question of whether these assertions should all be in the same test; I understand the arguments for splitting them up, and that might in fact address this problem—but I'd really like to understand the behavior I'm observing.


Update: When I modify the code like this, it works:

@patch('some.list')
def test_thing(self, mocklist):
  # some setup code
  mocklist.__iter__.return_value = self.preCreatedList
  with patch('some.other.object', new=self.preCreatedObject):
    #some.other.object uses the mocked list internally
    self.assertEqual(some.other.object.sut('foo'), fooResult)
    self.assertEqual(some.other.object.sut('bar'), barResult)
  mocklist.__iter__.return_value = ['bogusList']
  with patch('some.other.object', new=self.preCreatedObject):
    self.assertEqual(some.other.object.sut('foo'), failureResult)

Clearly there's a context issue.

However, to further complicate things, this test seems to work in isolation but fails when I run all of my tests (many of which are nearly identical to this, but for different functions). It's not at all clear to me what I've done to make the tests interdependent.

eaj
  • 2,576
  • 1
  • 20
  • 42

0 Answers0