How can I make mock-0.6 return a sequence of values?

I am using the mock-0.6 library from http://www.voidspace.org.uk/python/mock/mock.html to use up the scope for testing, and I want to have the mock method return a series of values ​​every time it calls.

Right now, this is what I decided 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 output of the log is as follows:

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

So, a side effect is returned by the generator, not the next value, which seems wrong. Where am I mistaken?

+3
source share
2 answers

Here is the solution found by trial and error:

The returnList function should create a generator and use its method nextto provide answers:

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
+2

, , mock == 0.8.0 :

import mock 

m = mock.Mock() 
m = side_effect = [ 
    ['a', 'b', 'c'], 
    ['d', 'e', 'f'], 
] 

print "First: %s" % m() 
print "Second: %s" % m() 

:

First: ['a', 'b', 'c']
Second: ['d', 'e', 'f']

, :

m = mock.Mock() 
m.return_value = ['a', 'b', 'c']
print m('foo') 
print m('bar') 
print m('baz') 
+5

Source: https://habr.com/ru/post/1738696/


All Articles