【问题标题】:Importing source files into test file将源文件导入测试文件
【发布时间】:2019-05-30 19:28:04
【问题描述】:

我的目录结构如下:

Project
├── README.md
├── app
│   ├── __init__.py
│   └── main.py
│   
├── tests
│   ├── __init__.py
│   └── test_one.py

我想在 test_one 中导入 app.main。我经历了类似的 stackoverflow 问题,并尝试在 test_one.py 文件中添加 app 文件夹的路径,如下所示:

sys.path.append('/path to project/app')

但是,我收到以下错误:

ModuleNotFoundError: 没有名为“app”的模块

如何将应用程序中的文件导入 test_one.py 文件?有没有简单的from ... import 语句来实现这一点?

【问题讨论】:

    标签: python unit-testing python-import python-3.7


    【解决方案1】:

    您没有提及您使用的是什么单元测试框架,但如果您使用的是pytest,它已经支持the tests are outside the application code 所在的那种应用/测试组织。

    setup.py
    mypkg/
        __init__.py
        app.py
        view.py
    tests/
        test_app.py
        test_view.py
        ... 
    
    • ..
    • 如果您没有setup.py 文件并且依赖于以下事实 Python默认将当前目录放在sys.path中导入 你的包,你可以执行python -m pytest 来执行测试 直接针对本地副本,不使用pip

    您的代码结构已经正确。您无需手动设置sys.path。您可以正常使用from app import main(请参阅下面的示例test_one.py)。我唯一要添加的是 pytest.ini 来指定测试文件的测试路径和模式。

    目录结构

    Project
    ├── pytest.ini
    ├── app
    │   ├── __init__.py
    │   └── main.py
    │   
    ├── tests
    │   ├── __init__.py
    │   └── test_one.py
    

    pytest.ini

    [pytest]
    addopts = -v
    console_output_style = count
    python_files = test_*.py
    testpaths = tests
    

    示例ma​​in.py

    def calculate(x, y):
        return x + y
    

    示例test_one.py

    from app import main
    
    def test_calculate():
        assert(3 == main.calculate(1, 2))
    

    运行 pytest:

    $ pytest tests
    =============================================================================== test session starts ===============================================================================
    platform linux -- Python 3.7.2, pytest-4.6.2, py-1.8.0, pluggy-0.12.0 -- /home/gino/.virtualenvs/test-py37/bin/python3.7
    cachedir: .pytest_cache
    rootdir: /home/gino/Project, inifile: pytest.ini, testpaths: tests
    collected 1 item                                                                                                                                                                  
    
    tests/test_one.py::test_calculate PASSED                                                                                                                                     [1/1]
    
    ============================================================================ 1 passed in 0.01 seconds =============================================================================
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多