2014-10-09 89 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一些信息。