【问题标题】:Setting up a simple python app with pytest getting error NameError and AttributeError使用 pytest 设置一个简单的 python 应用程序得到错误 NameError 和 AttributeError
【发布时间】:2017-03-21 16:20:56
【问题描述】:

我想获得有关使用 pytest 设置简单应用的最佳方法的建议。

我可以在单个文件上正常运行 pytest,但我想使用以下方式引导 Python 应用程序:

mypkg/
    __init__.py
    app.py
tests/
    __init__.py
    test_app.py

但是当我运行pytest 时出现错误:

NameError: name 'func' is not defined

mypkg/__init__.py 文件

# content of __init__.py
# Empty init file

mypkg/app.py 文件

# content of app.py
class mypkg:
    def func(x):
        return x + 1

测试/__init__.py 文件

# content of __init__.py
# Empty init file

测试/test_app.py 文件

# content of test_app.py
import pytest
import mypkg

def test_answer():
    assert func(4) == 5

我使用的是 Python 3.5。

我需要setup.py,如果我尝试调用mypkg.func(4),我会得到AttributeError: modulemypkghas no attribute 'func'

非常感谢任何帮助。

【问题讨论】:

    标签: python python-3.x pytest


    【解决方案1】:

    这个问题与 pytest 无关,或者根本与测试无关。 Python 中的一条基本规则是,如果要访问名称,则需要导入它;你还没有导入func,所以它给出了一个名称错误。

    但是,由于某种原因,您将func 定义为类的一部分。您不能将方法与其类分开导入;但是,没有理由让它成为类中的一个方法。只需将其定义为独立函数,然后导入即可。

    注意,即使独立存在,func 也在 app 内部,而不是直接在 mypkg 内部。所以你需要将它导入到它实际所在的位置。

    from mypkg.app import func
    

    【讨论】:

    • 谢谢 Daniel :) 我现在明白 mypkg 和 app 之间的时间段 = mypkg/app 目录。另外,我已经删除了这个类,现在让这个方法独立了。
    【解决方案2】:

    您在 mypkg 模块内的 mypkg 类中声明了 func,因此您需要按如下方式重写您的测试

    # content of test_app.py
    import pytest
    import mypkg
    
    def test_answer():
        obj = mypkg.app.mypkg()
        assert obj.func(4) == 5
    

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2016-01-13
      • 2019-02-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      相关资源
      最近更新 更多