You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3与pytest报错:jinja2.exceptions.TemplateNotFound: index.html

问题:单元测试中Jinja2模板找不到index.html

测试用例test_views_home.py::test_index执行失败,报错信息为:

jinja2.exceptions.TemplateNotFound: index.html

测试代码片段:

templates = Jinja2Templates('templates')

def test_index():
    @router.get('/', include_in_schema=False)
    async def index(request: Request):
        return templates.TemplateResponse('index.html', {'request': request})

    client = TestClient(router)
    response = client.get("/")
    assert response.status_code == 200
    assert '<!DOCTYPE html>' in response.text

项目目录结构:

root/
├── views/
│   ├── index.py
├── templates/
│   ├── index.html
├── tests/
│   ├── test_sorullo.py

猜测问题出在templates = Jinja2Templates('templates')的路径配置上,但无法确定具体原因,求指出操作错误。


解决方法

问题根源是:你的测试脚本在tests/目录下运行,此时工作目录是tests/,而你写的templates是相对路径,Jinja2会去tests/templates/找文件,当然找不到项目根目录下的templates文件夹。

给你两种靠谱的修正方式:

  • 用绝对路径指定模板目录,借助pathlib可以轻松实现,不用硬编码路径:
    from pathlib import Path
    # 从当前测试文件(tests/test_sorullo.py)往上退两级就是项目根目录root
    BASE_DIR = Path(__file__).parent.parent
    templates = Jinja2Templates(str(BASE_DIR / "templates"))
    
  • 运行测试时切换到项目根目录root/再执行命令,比如cd root && pytest tests/,但这种方式依赖运行环境,不如第一种通用。

另外建议你在实际项目里,把模板目录的路径配置成全局常量(比如放在项目的配置文件里),测试代码直接复用这个常量,避免重复定义路径导致这类问题。


内容的提问来源于stack exchange,提问作者emboole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:15:30