2014-10-09 83 views
0

我是新來的Python和單位test.following是主要的單元測試的程序來調用作用一個測試用例在單元測試中調用單獨的Python程序

import unittest 
from test import test_support 

class MyTestCase1(unittest.TestCase): 

    def test_feature_one(self): 

     print "testing feature one" 
     execfile("/root/test/add.py") 

def test_main(): 
    test_support.run_unittest(MyTestCase1); 

if __name__ == '__main__': 
    test_main() 

add.py其他的Python程序是基本的程序,增加了兩個不,並顯示它。

#!/usr/bin/env python 
import sys 

def disp(r): 
     print r 
def add(): 
     res = 3+5; 
     disp(res) 
add() 

但是當我從另一個函數調用某個函數時出現問題。當我嘗試運行單元測試(第一個程序)時,我遇到以下錯誤。但是,如果我在單元測試套裝之外運行add.py作爲單個程序,它工作正常。好心需要理解幫助這種情況下

====================================================================== 
ERROR: test_feature_one (__main__.MyTestCase1) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "first.py", line 17, in test_feature_one 
    execfile("/root/test/add.py") 
    File "/root/test/add.py", line 12, in <module> 
    add() 
    File "/root/test/add.py", line 10, in add 
    disp(res) 
NameError: global name 'disp' is not defined 

---------------------------------------------------------------------- 

回答

0

從文檔上的execfile(https://docs.python.org/2/library/functions.html#execfile):

「請記住,在模塊級,全局和當地人一樣的字典 ... 如果當地人字典。省略它默認爲globals字典,如果兩個字典都省略,表達式會在調用execfile()的環境中執行。

我並不是很瞭解全局和本地人究竟是如何工作的,所以我無法給出深入的解釋,但是從我所理解的: 這裏的關鍵是你從函數運行execfile 。如果從模塊級運行它,它會工作:

if __name__ == '__main__': 
    execfile('blah') 

但是如果從功能運行:

def f(): 
    execfile('blah') 

if __name__ == '__main__': 
    f() 

就會失敗。由於與全球和當地人的魔法。

如何解決你的例子:將字典添加到execfile的參數,它將工作(請記住從docs行:「如果本地字典省略它默認爲全局字典。」)。

但是我不建議使用execfile,而是從add.py導入add,然後在測試中調用它。 (這也將要求移動電話在add.py添加FUNC按鍵if __name__ == '__main__':,無法運行增加進口。

這裏的全局和當地人是如何工作的http://www.diveintopython.net/html_processing/locals_and_globals.html一些信息。