tags:

views:

13

answers:

1

I'm using the mock-0.6 library from http://www.voidspace.org.uk/python/mock/mock.html to mock out a framework for testing, and I want to have a mock method return a series of values, each time it's called.

Right now, this is what I figured should work:

def returnList(items):
  def sideEffect(*args, **kwargs):
    for item in items:
      yield item
    yield mock.DEFAULT
  return sideEffect

mock = Mock(side_effect=returnList(aListOfValues))
values = mock()
log.info("Got %s", values)

And the log output is this:

subsys: INFO: Got <generator object func at 0x1021db500> 

So, the side effect is returning the generator, not the next value, which seems wrong. Where am I getting this wrong?

A: 

Here's the solution, found by trial and error:

The returnList function must create a generator and use its next method to provide the responses:

def returnList(items):
  log.debug("Creating side effect function for %s", items)
  def func():
    for item in items:
      log.debug("side effect yielding %s", item)
      yield item
    yield mock.DEFAULT

  generator = func()

  def effect(*args, **kwargs):
    return generator.next()

  return effect
Chris R