2017-04-24 44 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

相關問題