模块导入运行py时出错.用Path上的模块进行测试



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

我有一个目录结构像

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

我将PYTHONPATH设置为/Path/api/。I CD到/Path/api,并运行以下命令

 py.test tests/my_module_test.py   

在下列情况下不起作用:

  1. 当我在my_module_test.py from api.my_module import my_function
  2. 的顶部有以下内容时

它在以下情况下有效:

  1. 当我在my_module_test.py from my_module import my_function的顶部有以下内容时

为什么我不能像在情况1中那样导入我的模块?

我使用PYTHONPATH作为

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

文本文档,你应该先安装。

pip install -e .

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

示例项目在这里,也在下面:

mymodule.py:

import boto3
def stuff():
    print "Yep!"

tests/text_syntax_errors.py:

import boto3
import mymodule

# Define a basic test that actually doesn't do much. 
# I just wanted more than zero tests
def test_one_equals_one():
    assert 1 == 1

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

From my README.md:

如何运行这些示例

我测试代码的最初动机是我在为工作编写的脚本中拼错了一个导入模块。

如果您编辑mymodule.py并从"中删除bboto3";您将看到下面的命令失败。这是一件好事。同样,如果您希望看到实际的测试失败,只需编辑tests/test_syntax_errors.py并将1 == 1更改为1 == 0

py . test

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+*] $

最新更新