我正在使用Python進行一系列單元測試,其中一些依賴於配置變量的值。這些變量存儲在全局Python配置文件中,並用於其他模塊。我想爲配置變量的不同值編寫單元測試,但尚未找到實現此目的的方法。在Python單元測試框架中修改全局變量
我沒有可能重寫我正在測試的方法的簽名。
這是我想什麼來實現:
from my_module import my_function_with_global_var
class TestSomething(self.unittest):
def test_first_case(self):
from config import MY_CONFIG_VARIABLE
MY_CONFIG_VARIABLE = True
self.assertEqual(my_function_with_global_var(), "First result")
def test_second_case(self):
from config import MY_CONFIG_VARIABLE
MY_CONFIG_VARIABLE = False
self.assertEqual(my_function_with_global_var(), "Second result")
感謝。
編輯:使示例代碼更明確。
太棒了。這確實有效。 – badzil 2011-06-08 16:59:50
@badzil:非常好。現在你有單元測試的覆蓋範圍,你可以刪除(需要)全局變量;-) – Johnsyweb 2011-06-09 00:39:42
我希望我可以。 – badzil 2011-06-09 17:29:54