2014-10-22 19 views
0

我正在寫一個簡單的Pong遊戲,並且在測試中遇到了導入問題。我的項目結構如下:從Python中的測試文件夾導入

app/ 
    __init__.py 
    src/ 
     __init__.py 
     Side.py 
     Ball.py 
    test/ 
     __init__.py 
     SideTests.py 
在Side.py

,我有:

from math import sqrt, pow 

class Side: 
    def __init__(self, start, end): 
     self.start = start 
     self.end = end 

    def collision(self, ball): 
     # returns True if there is a collision 
     # returns False otherwise 

(該算法的細節並不重要)。在Ball.py,我有:

class Ball: 
    def __init__(self, position, direction, speed, radius): 
     self.position = position 
     self.direction = direction 
     self.speed = speed 
     self.radius = radius 
在SideTests.py

,我有:

import unittest 
from src.Side import Side 
from src.Ball import Ball 

class SideTests(unittest.TestCase): 

    def setUp(self): 
     self.side = Side([0, 0], [0, 2]) 
     self.ball_col = Ball([1, 1], [0, 0], 0, 1) 

    def test_collision(self): 
    self.assertTrue(self.side.collision(self.ball_col))  

當我運行:

python test/SideTests.py 

從應用程序/,我得到:

Traceback (most recent call last): 
    File "tests/SideTests.py", line 15, in test_collision 
    self.assertTrue(self.side.collision(self.ball_col)) 
AttributeError: Side instance has no attribute 'collision' 

我知道這可能是一個非常簡單的導入錯誤,bu t我看過的例子都沒有幫助解決這個問題。

回答

1

首先,固定縮進和進口在SideTests.py

import unittest 
from app.Side import Side 
from app.Ball import Ball 

class SideTests(unittest.TestCase): 

    def setUp(self): 
     self.side = Side([0, 0], [0, 2]) 
     self.ball_col = Ball([1, 1], [0, 0], 0, 1) 

你也不需要test/__init__.py

現在運行這個程序,你需要在virtualenv或者全局安裝一個名爲app的軟件包,或者使用一個工具在運行測試之前爲你收集相關的導入信息,比如你可以安裝pid的nosetest。

~/app $ nosetests . 
---------------------------------------------------------------------- 
Ran 1 test in 0.000s 

OK 
+0

我最終創建了一個我的項目包,按照http://www.scotttorborg.com/python-packaging/minimal.html中的說明解決了我的問題。 – Sam 2014-10-23 01:00:05