运行模块导入错误py.测试在路径上有模块

2024-09-27 18:00:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法以我想要的方式导入我的模块进行测试。我在2.7.2的虚拟机上运行所有这些

我有一个目录结构

/api
    /api
        __init__.py
        my_module.py
    /tests
        my_module_test.py

我将PYTHONPATH设置为/Path/api/。将CD放入/Path/api并运行以下命令

^{pr2}$

在以下情况下不起作用:

  1. 当我在模块的顶部有以下内容时_测试.pyfrom api.my_module import my_function

它在以下情况下有效:

  1. 当我在模块的顶部有以下内容时_测试.pyfrom my_module import my_function

为什么我不能像案例1那样导入我的模块?在


Tags: 模块pathpyimport目录apiinitmy
3条回答

从py文本文档,您应该先安装:

pip install -e .

我用PYTHONPATH作为

PYTHONPATH=`pwd` py.test tests/my_module_test.py

我创造这个是为了回答你的问题和我自己的困惑。我希望有帮助。注意py.test命令行和tox.ini中的PYTHONPATH。在

示例项目是here,并且如下所示:

mymodule.py

import boto3

def stuff():
    print "Yep!"

tests/text_syntax_errors.py

^{pr2}$

tox.ini

[tox]
skipsdist = True
envlist = py27

[flake8]
max-line-length = 119

[testenv]
deps= -r{toxinidir}/requirements.txt
commands=py.test
setenv =
    PYTHONPATH = {toxinidir}

requirements.txt

boto3
pytest

来自我的README.md

How-to run these examples

My initial motivation for testing my code was that I had misspelled an imported module in a script that I was writing for work.

If you edit mymodule.py and remove the b from "boto3" you will see the commands below fail. And this is a good thing. Likewise if you would like to see an actual test fail, simple edit tests/test_syntax_errors.py and change 1 == 1 to 1 == 0.

py.测试

mbp0 pytest_test[master+*] $ PYTHONPATH=. py.test
========================== test session starts ==========================
platform darwin   Python 2.7.11, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /Users/jmacdonald/w/pytest_test, inifile:
collected 1 items

tests/test_syntax_errors.py .

======================= 1 passed in 0.11 seconds ========================
mbp0 pytest_test[master+*] $

毒物

mbp0 pytest_test[master+*] $ tox
py27 installed: boto3==1.3.1,botocore==1.4.37,docutils==0.12,futures==3.0.5,jmespath==0.9.0,py==1.4.31,pytest==2.9.2,python-dateutil==2.5.3,six==1.10.0
py27 runtests: PYTHONHASHSEED='713732044'
py27 runtests: commands[0] | py.test
========================== test session starts ==========================
platform darwin   Python 2.7.11, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /Users/jmacdonald/w/pytest_test, inifile:
collected 1 items

tests/test_syntax_errors.py .

======================= 1 passed in 0.11 seconds ========================
________________________________ summary ________________________________
  py27: commands succeeded
  congratulations :)
mbp0 pytest_test[master+*] $

相关问题 更多 >

    热门问题