【发布时间】:2021-09-09 09:48:32
【问题描述】:
我一直在尝试看看我是否在这个非常小的课程上犯了一个愚蠢的错误,但这似乎是 VSCode 的问题。
#planetoids.py
from collections import namedtuple
Vector2D = namedtuple("Vector2D", ['x', 'y'])
class Player:
def __init__(self, coords):
self._pos = Vector2D(*coords)
@property
def pos(self):
return self._pos
@pos.setter
def pos(self, coords):
self._pos = Vector2D(*coords)
#test_planetoids.py
import unittest
import planetoids
class TestPlayer(unittest.TestCase):
def setUp(self):
self.player = planetoids.Player([2,3])
def test_has_pos(self):
self.assertTrue(hasattr(self.player, "pos"))
pos = self.player.pos
self.assertTrue(hasattr(pos, 'x'))
self.assertTrue(hasattr(pos, 'y'))
def test_maintains_pos(self):
self.assertEqual(self.player.pos.x, 2)
self.assertEqual(self.player.pos.y, 3)
self.player.pos = [7,9]
self.test_has_pos()
self.assertEqual(self.player.pos.x, 7)
self.assertEqual(self.player.pos.y, 9)
在 Visual Studio Code 中,两个测试都通过了调试器,但是当我正常运行时,一个测试失败了。
一些打印语句显示,当我在终端中运行 test_planetoids 时,self.player.pos = [7,9] 将列表分配给 pos,就好像我没有编写 pos setter 一样。但是当我设置断点时,它会按预期直接进入设置器。
我尝试在 IDLE 中运行它,所有三个测试都通过了。
此代码是否在某些方面不稳定,导致其行为不可预测?如果不是,什么 VSCode 配置或终端配置可能会导致这种情况?
我不确定是否要切换到 IDLE 作为开发环境,因为它的功能较少,但这很成问题。
编辑:按要求输出错误。我会说我认为输出有点误导。就像我之前说的,它的出现是因为列表是直接传递的。
.F
======================================================================
FAIL: test_maintains_pos (__main__.TestPlayer)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_planetoids.py", line 19, in test_maintains_pos
self.test_has_pos()
File "test_planetoids.py", line 12, in test_has_pos
self.assertTrue(hasattr(pos, 'x'))
AssertionError: False is not true
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1)
Edit2:我让 VSCode 为另一个班级做这件事。显然 Vector2D(*list_with_2_elements) 要么不可靠,要么与我的 VSCode 或我不知道的机器的某些配置冲突。
【问题讨论】:
-
请将错误输出添加到问题中!
-
可能不是你的问题,但 test_maintains_pos 中的两个 asserttrue 应该是 assertequal 的。
-
为什么要在构造函数中复制setter代码
-
仅供参考,我使用
Python 3.6.9在虚拟环境中的 Ubuntu 上的 VS Code 中运行您的代码,并且测试顺利通过。我使用if __name__ == '__main__': unittest.main()运行它 EDIT 在Python 3.9.5中进行了快速测试,它也运行了... EDIT2 使用python -m unittest test_planetoids.py运行测试也同样有效 -
这就是为什么你应该总是使用 virtualenv
标签: python visual-studio-code zsh python-decorators vscode-debugger