使用Path上的模块运行py.test的模块导入错误

时间:2013-06-05 16:24:53

标签: python python-2.7 pythonpath pytest

我无法以我想要的方式导入我的模块进行测试。我在2.7.2

的virtualenv中运行所有这些

我有一个像

这样的目录结构
/api
    /api
        __init__.py
        my_module.py
    /tests
        my_module_test.py

我将PYTHONPATH设置为/ Path / api /。我将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
    2. 的顶部有以下内容时

      为什么我无法像案例1那样导入我的模块?

3 个答案:

答案 0 :(得分:14)

我使用 PYTHONPATH 作为

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

答案 1 :(得分:2)

从py.text文档中,您应首先安装。:

pip install -e .

答案 2 :(得分:2)

我创建这个作为你的问题的答案和我自己的困惑。我希望它有所帮助。请注意Private Sub returnFiletoSS() ' This Background worker Process . TestWorker = New BackgroundWorker TestWorker.WorkerReportsProgress = True TestWorker.WorkerSupportsCancellation = True TestWorker.RunWorkerAsync() End Sub ' This event handler deals with the results of the background operation. Private Sub TestWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles TestWorker.RunWorkerCompleted ' First, handle the case where an exception was thrown. If (e.Error IsNot Nothing) Then MessageBox.Show(e.Error.Message) ElseIf e.Cancelled Then ' Next, handle the case where the user canceled the operation. ' Note that due to a race condition in the DoWork event handler, ' the Cancelled flag may not have been set, even though ' CancelAsync was called. Form2.resultLabel("Canceled") Else ' Finally, handle the case where the operation succeeded. ' Form2.resultLabel(e.Result.ToString()) lastRecord = True ' objWriter1.Close() 'Tried closing writer here, but errors. End If 命令行和PYTHONPATH中的py.test

示例项目为here,以及以下内容:

tox.ini

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

  

如何运行这些示例

     

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

     

如果您修改README.md并从“mymodule.py”中删除b,您会看到以下命令失败。这是一件好事。同样,如果您希望看到实际测试失败,只需修改boto3并将tests/test_syntax_errors.py更改为1 == 1

<强> py.test

1 == 0

<强> TOX

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