python unittest中的NameError

RPT

我正在尝试测试 a 的 python 方法,file-A它在file-A. 我的file-A方法是这样的:

def rotate(self, rotation):
    self.current_face = board.positions[(board.positions.index(self.current_face) + rotation) % 4]

注意:这是在课堂A-1file-A

mainfile-A这个样子的:

if __name__ == '__main__':
    inp = Input("input.txt")       # create Input object
    board = Board(inp.lines[0])    # create board object -----> NOTE
    rover_objects(inp.lines[1:])   # create rover objects
    process_and_print()            # process and print output

因此,当我运行时file-A,它的工作方式与我希望它的工作方式完全一样。


现在,我试图def rotate(self, rotation)file-A我的测试代码中进行测试如下所示:

class RoverTest(unittest.TestCase):
   def setUp(self):
       description = '1 2 N'
       moves = 'LMLMLMLMM'
       self.testRover = Rover(description, moves)
   def test_coordinates(self):
       self.testRover.rotate(rotation = 4)   -----> Problem
       self.assertEqual(self.testRover.current_face, 'N')

问题是,rotate方法file-A使用对象boardmainfile-A我不知道如何传递boardrotate函数从测试。

如果我现在运行我的测试,我会抛出一个错误:

NameError:未定义名称“board”

我该如何解决这个错误?

丹尼尔罗斯曼

如果您正在编写一个依赖于其他现有类的类,您应该让它接受这些依赖项作为初始化的参数,而不仅仅是希望它们是全局定义的。例如:

class A1(object):
    def __init__(self, inputfile):
        self.inp = Input(inputfile)
        self.board = Board(self.inp.lines[0])

    def rotate(self, rotation):
        self.current_face = self.board.positions[(self.board.positions.index(self.current_face) + rotation) % 4]

现在,在主文件和测试文件中,您都可以通过传递输入文件直接实例化 A1。

这当然只是一个例子;您可能希望在类外实例化 Board 对象并直接将其传入。无论哪种方式都可以,重要的是您要传递任何依赖项。

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章