Python unittest导入问题

时间:2017-09-23 13:49:37

标签: python unit-testing packages

我很难理解软件包,特别是如何在软件包中使用unittest。我看了这个问题(),但对这个问题的正确答案并没有解决我的问题。我有以下结构:

$scope.data = {

        name: 'name',
        email: 'example@gmail.com'
    };
$http.post(uploadUrl, data)
        .success(function(response){
            //execute some code...
        });

使用以下文件/导入:

模型/ __ INIT __ PY:

model
|-- __init__.py
|-- boardmodel.py
|
|-- exceptions
|   |
|   |-- __init__.py
|   |-- exceptions.py
|
|-- test
    |-- __init__.py
    |-- test_boardmodel.py

模型/异常/ __ INIT __吡啶

不包含任何内容

模型/测试/ __初始化__ PY:

不包含任何内容

导入 boardmodel.py:

import model.exceptions.exceptions
import model.boardmodel

test_boardmodel.py:

内导入
from model.exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError

我将自己置于模型目录中并运行import unittest from model.boardmodel import Board, Ball, Wall from model.exceptions.exceptions import ProximityError 。我收到以下消息:

python -m unittest test.test_boardmodel.py

我执行导入语句时导入的工作方式和模块/包的位置有点丢失。为什么找不到ERROR: test_boardmodel (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: test_boardmodel Traceback (most recent call last): File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) File "/Users/sahandzarrinkoub/Documents/Programming/pythonfun/BouncingBalls/balls/src/model/test/test_boardmodel.py", line 3, in <module> from model.boardmodel import Board, Ball, Wall ModuleNotFoundError: No module named 'model'

我要补充一点,如果我从列出的所有导入中删除model,测试都会起作用,但我无法使用&#34;外部&#34;了:

model.

visual.py:

src
|-- visual.py
|
|-- model
    |-- __init__.py
    |-- boardmodel.py
    |
    |-- exceptions
    |   |
    |   |-- __init__.py
    |   |-- exceptions.py
    |
    |-- test
        |-- __init__.py
        |-- test_boardmodel.py

2 个答案:

答案 0 :(得分:3)

我遇到了同样的问题,能够从多个文件导入一些模块,但不能从测试文件导入,所以我看到了这个解决方案:

  

如果你有test / my_test.py,测试应该运行:

python -m test.my_test

之后,我导入了我想要的内容并且没有错误。

答案 1 :(得分:0)

我相信标准包装结构是

  myproject
  ├── myproject
  ├── tests
  └── scripts

如果要在不安装软件包的情况下运行测试,请从顶部的myproject文件夹运行它们,以使import myproject在测试中成功。 (与脚本类似。)为此,请在myproject中使用绝对导入或显式相对导入。