从Python中的测试文件夹导入

山姆

我正在编写一个简单的Pong游戏,并且在测试中遇到一些导入问题。我的项目结构如下:

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

从app /中,我得到:

 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'

我知道这可能是一个非常简单的导入错误,但是我看过的所有示例都没有帮助解决此问题。

丹尼

首先,在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

现在要运行此程序,您既需要安装app在virtualenv中调用的软件包,也可以在全局范围内安装,或者使用一种可以在运行测试之前为您收集相对导入的工具,例如您可以点安装的鼻子测试。

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

OK

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章