Python 将类属性上的doctest与py.test一起使用

Python 将类属性上的doctest与py.test一起使用,python,unit-testing,properties,pytest,doctest,Python,Unit Testing,Properties,Pytest,Doctest,我尝试在py.test中使用doctest测试属性,但我收到一个名称错误,表示未定义该类 这里有一个小例子: class ExampleClass: def __init__(self, attribute): self.attribute = attribute @property def attribute_squared(self): """ Examples: >>> E

我尝试在py.test中使用doctest测试属性,但我收到一个名称错误,表示未定义该类

这里有一个小例子:

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
运行whin 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
错误
**********************************************************************
第3行,在ExampleClass中
失败示例:
ExampleClass(属性=2)
提出的例外情况:
回溯(最近一次呼叫最后一次):
文件“C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.5\helpers\PyCharm\docrunner.py”,第140行,在运行中
compileflags,1),test.globs)
文件“”,第1行,在
ExampleClass(属性=2)。属性的平方
NameError:未定义名称“ExampleClass”

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

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

看起来这是PyCharm的配置问题。如果我复制了您的示例(并修复了doctest错误),则测试会成功,并将
pytest--doctest模块
报告为PyCharm中的错误: