2015-05-08 28 views
1

似乎kwarg任務沒有在mock.patch中被嘲弄,但是如果它在函數內被調用,它就是。模擬不能在kwargs上的對象上工作

任何想法?

import platform 
import mock 


def test(arch=platform.machine()): 
    print "arch = %s" % arch 
    print "machine = %s" % platform.machine() 

with mock.patch.object(platform, "machine", return_value="TEST"): 
    test() 


# This outputs 
# arch = x86_64 
# machine = TEST 

回答

1

當執行函數定義時,函數默認值被設置並存儲在函數對象中。

嘲笑platform.machine工作正常,但arch參數的默認值早已通過調用platform.machine()並使用返回值進行設置。當調用test()時,表達式是而不是

請參閱"Least Astonishment" in Python: The Mutable Default Argument爲什麼是這樣。

你需要補丁platform之前你曾經導入定義函數的模塊;您可以將功能移動到一個新的模塊,這樣做:

import sys 

if 'modulename' in sys.modules: 
    del sys.modules['modulename'] # ensure the cached module is cleared 

with mock.patch.object(platform, "machine", return_value="TEST"): 
    from modulename import sys 
    test() 

del sys.modules['modulename'] # clear the module with the mocked value again 

這是相當麻煩的,如果你要運行的線程測試將失敗。

您可以使用None作爲默認的,而不是和創建默認時test被稱爲替代:

def test(arch=None): 
    if arch is None: 
     arch = platform.machine() 
    print "arch = %s" % arch 
    print "machine = %s" % platform.machine() 
相關問題