2017-04-24 38 views
1

这个问题已经被问了上百次,但是我看到的每个解决方案都不适用于我,而且我非常沮丧,所以这里是101。Python - 如何从单元测试的不同目录中导入一个类

鉴于项目目录:

project/ 
    src/ 
    __init__.py 
    student.py 
    test/ 
    __init__.py 
    student_test.py 

我student.py文件:

class Student: 
    def __init__(self, name, age): 
    self.full_name = name 
    self.age = age 

我student_test.py文件:

from nose.tools import * 
import src 
from src import Student 

def test_basic(): 
    print "I RAN!" 

def test_student(): 
    s = Student("Steve", 42) 
    assert s.age == 42 

我收到以下错误:导入内容十分重要的

====================================================================== 
ERROR: Failure: ImportError (cannot import name Student) 
---------------------------------------------------------------------- 
    from src import Student 
ImportError: cannot import name Student 

我试过变化和加入src目录路径,但似乎没有在这里工作。 WTF我做错了吗?

回答

1

如果你被绑定到这个目录结构,这里有一个解决方案让你的测试运行。

from nose.tools import * 
import sys 
sys.path.insert(0, '/Users/daino3/Workspace/student-project/src') # the absolute path of /src directory 
from student import Student 

def test_basic(): 
    print "I RAN!" 

def test_student(): 
    s = Student("Steve", 42) 
    assert s.age == 42 

test_basic() 
test_student() 

或者,将您的测试放在与源相同的目录中,然后简单地from student import Student

相关问题