Sometimes, it's easier to just pass some "s3 engine" as a parameter and pass some simple mock-object instead when it's a test (and provide it's return values). Sometimes you need to call lots of random functions that cause side-effects (for example, if you would work with s3, get current time, do some sql-queries, open some files and more), and here it wouldn't be nice to pass it all as function-parameters (since it isn't needed except for testability), I'd suggest you to use mockstar to declaratively describe your side-effects. Your code would then something like this:
def foobar():
foo = get_from_database()
bar = read_from_file()
baz = read_from_s3()
if foo > 10:
return foo + bar + baz
else:
return foo - bar - baz
# And your test would look something like this:
from mockstar import prefixed_p
from nose.tools import assert_equal
ppatch = prefixed_p('module.with.foobar.func')
class TestFoobar(BaseTestCase):
@ppatch('get_from_database')
@ppatch('read_from_file')
@ppatch('read_from_s3')
def side_effects(self, se):
se.read_from_file.return_value = 10 # default behaviour
se.read_from_s3.return_value = 0 # also default behaviour
return self.invoke(se)
def test_should_get_30(self, se):
se.get_from_database.return_value = 20
# do
result = foobar()
assert_equal(result, 30)
def test_should_get_minus5(self, se):
se.get_from_database.return_value = 5
# do
result = foobar()
assert_equal(result, -5)
foobaris not the real name of my method. – Bon Ami Aug 1 '11 at 2:45