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

Python单元测试:test_read_flat函数404失败排查求助

Python单元测试GET接口返回404的排查方案

问题场景

执行pytest后,test_create_flat测试通过,但test_read_flat函数调用GET接口/flats/get/1/时返回404状态码,导致断言失败。测试脚本如下:

import json

def test_create_flat(client):
    data = {
        "title": "SDE super",
        "company": "doogle",
        "company_url": "www.doogle.com",
        "location": "USA,NY",
        "description": "python",
        "date_posted": "2022-03-20"
        }
    response = client.post("/flats/create-flat/",json.dumps(data))
    assert response.status_code == 200 
    assert response.json()["company"] == "doogle"
    assert response.json()["description"] == "python"

def test_read_flat(client):     #new test
    data = {
        "title": "SDE super",
        "company": "doogle",
        "company_url": "www.doogle.com",
        "location": "USA,NY",
        "description": "python",
        "date_posted": "2022-03-20"
        }
    response = client.post("/flats/create-flat/",json.dumps(data))

    response = client.get("/flats/get/1/")
    assert response.status_code == 200
    assert response.json()['title'] == "SDE super"

排查与解决要点

  • 不要硬编码资源ID:创建数据后,从POST响应中获取实际生成的ID,而非默认假设为1。测试环境的ID序列可能因前置操作或测试夹具重置逻辑发生变化,硬编码会导致资源匹配失败。修改代码如下:

    # 创建数据后提取返回的ID
    created_response = client.post("/flats/create-flat/", json=data)
    flat_id = created_response.json()["id"]
    # 使用真实ID发起GET请求
    response = client.get(f"/flats/get/{flat_id}/")
    
  • 修正POST请求参数格式:多数Web框架(如Flask、Django)的测试客户端支持直接传入json参数,无需手动调用json.dumps()。如果接口期望接收JSON格式请求体,手动dump的字符串可能导致数据解析异常,数据未正确入库。修改POST请求:

    response = client.post("/flats/create-flat/", json=data)
    
  • 验证测试数据的持久性:检查测试夹具的事务逻辑,确保test_read_flat中创建的数据不会因自动回滚被清除。同时确认后端创建接口是否正确提交了数据库事务(如Django的obj.save()、SQLAlchemy的db.session.commit()),未提交的事务会导致数据仅存在于内存中,GET请求无法读取。

  • 核对路由匹配规则:确认后端GET接口的路由定义与测试中的/flats/get/1/完全一致,避免拼写错误或路径格式差异(比如是否应为/flats/detail/<int:pk>/)。

  • 打印响应调试信息:在test_read_flat的POST请求后添加打印语句,查看返回的JSON内容,确认数据是否成功创建、ID是否正确:

    print(response.json())
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:35:16