正在加载...

fudge文档翻译-2

Fake objects without patches (dependency injection)

如果你不需要任何补丁,你可以使用fudge.test()装饰器。这将捕获任何一个被抛出的非预期的异常。这是一个例子:

>>> def send_msg(api):
...     if False: # a mistake
...         api.UpdateStatus('hello')
...
>>> @fudge.test
... def test_msg():
...     FakeOAuthApi = (fudge.Fake('OAuthApi')
...                          .is_callable()
...                          .expects('UpdateStatus'))
...     api = FakeOAuthApi()
...     send_msg(api)
...
>>> test_msg()
Traceback (most recent call last):
...
AssertionError: fake:OAuthApi.UpdateStatus() was not called

Stubs Without Expectations

如果你想要一个fake对象,可以被调用但是它不是一定被调用,除了用Fake.provides()代替Fake.expects()外,代码完全一样。这是一个调用isloggedin()永远返回True的例子:

>>> def show_secret_word():
...     import auth
...     user = auth.current_user()
...     if user.is_logged_in():
...         print "Bird is the word"
...     else:
...         print "Access denied"
...
>>> @fudge.patch('auth.current_user')
... def test_secret_word(current_user):
...     user = current_user.expects_call().returns_fake()
...     user = user.provides('is_logged_in').returns(True)
...     show_secret_word()
...
>>> test_secret_word()
Bird is the word

注意,如果user.isloggedin()没有被调用,不会有任何的异常被抛出。因为它是'提供'(provided),不是'期望'(expected)。

Replacing A Method

有时候,返回一个静态的值不是完全足够的。你真正需要运行一些代码。你可以使用Fake.calls(),就像这样:

>>> auth = fudge.Fake()
>>> def check_user(username):
...     if username=='bert':
...         print "Bird is the word"
...     else:
...         print "Access denied"
...
>>> auth = auth.provides('show_secret_word_for_user').calls(check_user)
>>> # Now, the check_user function gets called instead:
>>> auth.show_secret_word_for_user("bert")
Bird is the word
>>> auth.show_secret_word_for_user("ernie")
Access denied