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

Python使用pytest创建参数化测试用例失败,报错TypeError

pytest参数化测试用例报错排查:TypeError: string indices must be integers

问题场景

作为Python新手,编写pytest参数化测试用例后,执行命令:

CONFIG_LOCAL=../config_test.py pytest --setup-show tests/functional/test_create.py

抛出TypeError: string indices must be integers错误。对比仓库中结构类似的可运行代码,未发现明显差异,需排查错误原因。

错误测试代码

import pytest

from tests.fixtures import create_empty_database 

class TestCreateMssql(object):

    @pytest.mark.parametrize("table, item_names, item_types, ddl" [
     ("special", ["id"], ["INTEGER"], """create or replace TABLE {table} (\n\t"id" NUMBER(38,0));"""),
     ("regular", ["id"], ["INTEGER"], """create or replace TABLE {table} (\n\t"id" NUMBER(38,0));"""
    ])
    def test_create(self, create_empty_database, table, item_names, item_types, ddl):
        pass

报错信息

@pytest.mark.parametrize("table, item_names, item_types, ddl" [
E   TypeError: string indices must be integers

可运行参考代码

@pytest.mark.parametrize("schema, expected", [
    ("dbo", {"tables": ["regular", "special"]}),
    ("non_existing", {"tables": []}),
    ])
    def test_list_tables(self, create_empty_database, schema, expected):

错误原因分析

报错由两处语法错误导致:

  1. 缺少参数分隔逗号:@pytest.mark.parametrize的第一个参数(参数名字符串)和第二个参数(测试数据列表)之间必须用逗号分隔。代码中直接在字符串后写[,Python会将字符串视为可索引对象,尝试用[后的内容索引字符串,从而触发string indices must be integers错误。
  2. 元组未闭合:第二条测试数据的元组末尾缺少闭合括号),导致语法不完整。

修正后的代码

import pytest

from tests.fixtures import create_empty_database 

class TestCreateMssql(object):

    @pytest.mark.parametrize("table, item_names, item_types, ddl", [
     ("special", ["id"], ["INTEGER"], """create or replace TABLE {table} (\n\t"id" NUMBER(38,0));"""),
     ("regular", ["id"], ["INTEGER"], """create or replace TABLE {table} (\n\t"id" NUMBER(38,0));""")
    ])
    def test_create(self, create_empty_database, table, item_names, item_types, ddl):
        pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:23:33