【问题标题】:Using doctest on class property with py.test通过 py.test 在类属性上使用 doctest
【发布时间】:2018-06-25 00:55:29
【问题描述】:

我尝试在 py.test 中使用 doctest 测试一个属性,但我得到一个 NameError 说该类未定义。

这是一个小例子:

class ExampleClass:

    def __init__(self, attribute):
        self.attribute = attribute

    @property
    def attribute_squared(self):
        """
        Examples:
            >>> ExampleClass(attribute=2).attribute_squared
            4
        """
        return self.attribute ** 2

当我在 py.test 中运行它时:

Error
**********************************************************************
Line 3, in ExampleClass
Failed example:
    ExampleClass(attribute=2)
Exception raised:
    Traceback (most recent call last):
      File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.5\helpers\pycharm\docrunner.py", line 140, in __run
        compileflags, 1), test.globs)
      File "<doctest ExampleClass[0]>", line 1, in <module>
        ExampleClass(attribute=2).attribute_squared
    NameError: name 'ExampleClass' is not defined

有没有办法测试类属性,或者我应该编写一个真正的测试?

【问题讨论】:

  • 看起来这是 PyCharm 的配置问题。如果我复制您的示例(并修复 doctest 错误),则测试通过 pytest --doctest-modules 成功。

标签: python unit-testing properties pytest doctest


【解决方案1】:

最后我发现只有当我在 Pycharm 中右键单击/运行“Doctest attribute_squared”时测试才通过。 运行pytest时,测试通过。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 2019-05-30
  • 1970-01-01
  • 2017-01-02
相关资源
最近更新 更多