【问题标题】:Why doesn't this work in VSCode terminal?为什么这在 VSCode 终端中不起作用?
【发布时间】: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() 运行它 EDITPython 3.9.5 中进行了快速测试,它也运行了... EDIT2 使用python -m unittest test_planetoids.py 运行测试也同样有效
  • 这就是为什么你应该总是使用 virtualenv

标签: python visual-studio-code zsh python-decorators vscode-debugger


【解决方案1】:

我不确定这是否是 macOS 的标准,但“python”与 Python 2 相关联。 VSCode 调试器使用 Python 3 解释器,但是当我使用 python test_planetoids.py 单独执行测试时,它在 Python 2 中执行。

这种情况下的解决方案是使用python3 test_planetoids.py

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2016-04-14
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2022-10-06
    • 2021-12-18
    相关资源
    最近更新 更多