【问题标题】:Pytest - Can't access imported class' attributes?Pytest - 无法访问导入的类的属性?
【发布时间】:2021-01-04 01:31:40
【问题描述】:

问题总结: 当尝试访问我尝试测试的类/Luigi 任务的类方法时,它指出该类没有我尝试使用的方法。

更多详情: 我正在尝试测试我编写的类/Luigi 任务。我正在尝试将我正在测试的类导入测试文件以使用其方法。但是,当我尝试导入它时,我只能访问该类,而不能访问其中的方法。它的任何方法都不可访问。我知道我可以成功导入该类,因为当我打印它的一个实例时,它会显示具有正确属性名称的对象。

以下是我认为可能提供上下文并可能有助于为解决此问题提供线索的任何细节:

项目文件结构:

src
|
| - <folder containing code>
| | - foo.py
|
| - tests
| | - resources
|   | - count.csv
|
| | - test_example.py
| - pytest.ini

foo.py 包含我正在测试的类。该类具有以下结构:

import luigi

class Foo(luigi.Task):
   attr1 = luigi.Parameter()
   attr2 = luigi.ListParameter()

   def requires(self):
       None

   def output(self):
      <not important>

   def _helper_method_1():
      <CODE>

   def _helper_method_2():
      <CODE>

   def run(self):

      <code that uses all the helper methods>

            .
            .
            .


我正在尝试运行测试来测试此类中的辅助方法。

这是我在test_example.py 中的代码:

import pytest
import sys
sys.path.append('../<folder containing code>/')
from <folder containing code>.foo import Foo

@pytest.fixture
def base():
    return Foo('hi',[])

def test_me(base):
    print(base)
    value = base._helper_method_1('./resources/count.csv')
    assert value == 3

运行 pytest 出现以下错误:

FAILED tests/test_example.py::test_me - AttributeError: 'Foo' object has no attribute '_helper_method_1'

然后打印以下内容: Foo(attr1='', attr2=[]) 这表明该类至少在某种程度上是导入的,因为它将属性名称映射到我为基本夹具输入的参数。

我一直坚持这一点,尝试不同的方式在test_example.py中导入类:

只导入文件:

sys.path.append('../<folder containing code>/')
from <folder containing code> import foo

只导入类:

sys.path.append('../<folder containing code>/')
from <folder containing code> import Foo

如果您对我可能未包含的可能有帮助的信息有任何建议或问题,请告诉我。

谢谢!

【问题讨论】:

  • 你的辅助方法有这个名字吗,或者你使用的是 double 下划线?在这种情况下,名称将被破坏。
  • 使用您提供的少量代码在我的机器上测试它,我得到TypeError: _helper_method_1() takes 0 positional arguments but 2 were given。一旦通过在_helper_method_1 中声明参数来修复此错误,测试将失败但不会导致错误。问题可能出在您认为不相关的部分代码中。尝试提供一个功能齐全的最小示例来重现您的问题(我们可以简单地复制/粘贴并执行),它可以帮助您自己找出真正的问题。
  • 我有同样的问题,我可以很好地导入类,但是在 pytest 中使用它时,它给了我一个响亮的AttributeError: module 'xxx' has no attribute 'MyClass'。是pytest高还是什么?

标签: python python-3.x unit-testing pytest luigi


【解决方案1】:

_helper_method_1 的定义缺少self 参数。要调用base._helper_method_1(...),您需要添加self,或者用@classmethod@staticmethod 标记它。我期待另一个错误消息,但也许 pytest 混淆了它。

【讨论】:

    【解决方案2】:

    我也有同样的问题。我所做的是在您的 tests/ 文件夹中创建一个空的 tests/conftest.py 文件。它清除了一切。我欢迎解释为什么这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-07
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      相关资源
      最近更新 更多