【问题标题】:pytest integration - how to properly importpytest集成-如何正确导入
【发布时间】:2017-03-12 03:45:13
【问题描述】:

我正在使用py.test 来测试我的python 代码。我项目的相关结构是

-myproject
    file.py
    file2.py
    -test/
        input.txt
        input2.dat
        test_part.py
    -regress/
        file2_old.py
        __init__.py
        -test/
            test_file2_regression.py

test_part.py 导入 filefile2test_file2_regression.py 导入 file2regress.file2_old。如果我在控制台中运行pytest,我会收到导入错误,即包不存在。另一方面,运行python -m pytest 工作得很好,但前提是我从myproject/ 目录运行它。

什么是正确的方法来做到这一点,让它在我的项目中的任何地方工作?我已经尝试修改PYTHONPATH,但老实说我不知道​​如何正确地做到这一点。


更多信息:

我没有任何设置文件,我的__init__s 只是空文件。如果有必要操作PYTHONPATH,则需要相对于myproject,因为我在几台机器上使用它。我正在运行 python 2.7。


我已经退房了:

但它并没有真正帮助我。

【问题讨论】:

    标签: python python-import pytest


    【解决方案1】:

    在搜索“执行此操作的最佳方式”时遇到同样的问题和类似的成功,我认为自己尽可能避免这种情况(通过从顶层运行实际脚本),但要回答您的问题,我目前的方法(例如从并行文件夹进行单元测试)是

    from sys import argv, path
    from os.path import dirname, join
    path.append(join(dirname(argv[0]), ".."))
    

    这使得解释器也在上面启动脚本的文件夹中搜索。另一种方法(而不是使用argv)是使用introspect 模块来获取文件名。这些对我来说比使用__file__ 更好,因为后者并不总是被定义。

    编辑 29.10.: argv[0] 的替代方法是使用

    from inspect import getsourcefile
    from sys import path
    from os.path import dirname, join
    
    this_file = getsourcefile(lambda _: None)
    path.append(join(dirname(this_file), ".."))
    

    我希望这至少可以用于所要求的目的,另请参阅How do I get the path of the current executed file in Python?

    最简单的——如果它适用于你的情况——当然是:

    from os.path import dirname, join
    path.append(join(dirname(__file__), ".."))
    

    【讨论】:

    • 你是如何使用这个的? argv[0] 计算为 pytest 的目录。如果用pytest 调用,它会给出/usr/local/bin/pytestpython -m pytest /usr/local/lib/python2.7/dist-packages/pytest.py
    • 是的,我之前没明白。那么,argv[0] 对你来说并不适用。你可以试试inspect.getsourcefile()(见stackoverflow.com/questions/2632199/…,来自ArtsOfWarfare的回答。)
    【解决方案2】:

    适用于项目中任何目录的pytest 命令的解决方案是在导入之前包含在test*.py 文件中:

    import os
    from sys import path
    PATH = os.path.abspath(os.path.dirname(__file__))
    path.append(os.path.join(PATH, os.pardir, os.pardir))
    

    使用正确数量的os.pardir 导航到项目目录,从那里__init__.py 文件允许导入模块。

    argv[0]inspect.getsourcefile 都没有提供必要的信息。 argv[0] 包含使用的 py.test 模块的位置,getsourcefile 方法只返回 None


    编辑:从 Python 3.4 开始,我们可以使用现代的 os.path 代替 pathlib

    from pathlib import Path
    from sys import path
    
    PATH = Path(__file__).resolve()
    path.append(PATH.parents[2])
    

    【讨论】:

      猜你喜欢
      • 2014-11-07
      • 2020-10-11
      • 2017-03-23
      • 1970-01-01
      • 2022-10-25
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多