【发布时间】: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