首页 > 解决方案 > Pytest 在测试文件夹中找不到文件

问题描述

我正在尝试使用 moto 在 pytest 创建一个测试,以使用 boto3 将 Cloud Formation 上传到 AWS。

我正在做的测试是这个:

def test_main_success(self, cf):
    'Test upload with a new stack'
    sys.stdout = mystdout = io.StringIO()
    expected_return = (
                    "Criando teste\n"
                    "...aguardando resposta da aws...\n"
                    "Sucesso\n"
                    )

    main(["teste", "teste.yaml"])
    content = mystdout.getvalue()
    assert content == expected_return

问题是它找不到文件。

FileNotFoundError: [Errno 2] No such file or directory: './resources/teste.yaml'

但是文件在那里,当我尝试脚本时它运行得很好,并获取了文件。

它试图获取的文件位于脚本文件夹中,而不是测试文件夹中

├── cl_uploader
│   ├── cl_uploader.py
│   ├── __init__.py
│   └── resources
│       ├── 1-ec2-with-sg-eip.yaml
│       └── teste.yaml
└── tests
    ├── resources
    │   └── teste.yaml
    └── test_cl_uploader.py

pytest 不会从测试所在的文件夹中获取文件?

标签: pythonpython-3.xpytest

解决方案


你需要添加一个

__init__.py

在您的测试文件夹中

您的存储库应如下所示:

├── cl_uploader
│   ├── cl_uploader.py
│   ├── __init__.py
│   └── resources
│       ├── 1-ec2-with-sg-eip.yaml
│       └── teste.yaml
└── tests
    ├── resources
    │   └── teste.yaml
    ├── __init__.py # init here ! :)
    └── test_cl_uploader.py```

验证您的 pytest 配置文件(又名 pytest.ini)是否为相同模式定义了发现策略y


推荐阅读