【发布时间】:2014-04-18 00:11:51
【问题描述】:
我正在尝试在 Python 上运行我的自动化测试,但一直遇到导入错误。我的目录层次结构如下:
TestingPractice
- bin
- README.txt
- setup.py
- TestingPractice
- __init__.py
- main.py
- tests
- __init__.py
- test_main.py
现在,当我 cd 到顶部的 TestingPractice 并运行鼻子测试时,我发现我在 main.py 中创建的方法未声明,即使在导入 TestingPractice.main 时也是如此
main.py:
def total_hours(hours):
sum = 0
for hour in hours:
sum += hour
return sum
test_main.py:
# Test the hour computation.
from nose.tools import *
import TestingPractice.main
def test_hours():
to_test = [8,8,7,8] # 31
assert_equal(total_hours(to_test), 31)
运行鼻子测试时:
/Documents/Developer/Python/TestingPractice/tests/test_main.py", line 7, in test_hours
assert_equal(total_hours(to_test), 31)
NameError: global name 'total_hours' is not defined
我尝试了许多不同的导入路径,甚至是相对导入(导致相对导入错误),还尝试了 export PYTHONPATH=。无济于事。
【问题讨论】:
-
test目录中通常不需要有__init__.py。即使没有__init__.py,nose(不是nose2)也会找到您的 test_main.py。 -
考虑将
from nose.tools import *更改为from nose.tools import assert_equal。它使您的代码更具可读性,并且通常是一种很好的做法,因为您可以完全控制哪些函数和变量进入您的命名空间。 -
当我有更高级的测试用例时,这种情况会改变吗?我明白你对这个例子的看法,但是当我开始使用不仅仅是 assert_equal 时,导入 * 是否仍然不好?
-
它是关于有清晰的图片,哪个变量或函数来自哪里。如果你只做一个
from something import *,问题不大。但是,一旦你做更多次,你就会弄乱来自多个导入的变量,而且很难说哪个包/模块贡献了你使用的方法/变量。显式from something import alfa, beta让你看清楚这些信息,另一种方式是import something然后使用something.alfa、something.beta等。
标签: python python-2.7 import module nosetests