如何读取和发送CSV列数据到PyTest测试案例中

0 人关注

我们有一个调用API并将其响应保存为CSV的工具。该CSV( resp.csv )有API请求(列 A )以及头文件 (列 C )和有效载荷(列 B )在里面。同时,他们的响应主体也被存储在 D 列中,响应代码在 E 列中(在CSV图片中不可见)。

The CSV file looks like this:

我想把每个响应传递给一组PyTest测试案例,这些案例将有一些针对响应的断言。

对于检查状态代码,我可以通过一个函数调用来完成,在写到CSV之前返回响应代码。但我们的要求是从CSV中读取响应,并将其用于断言/测试案例。

@pytest.mark.parametrize('test_input', check_response)
def test_APIResponse(test_input):
    print(check_response)
    assert test_input == 200, "Test pass"

我如何调用存储在CSV(列D)的响应体,并通过使用PyTest测试案例做断言?

谁能为我提供指导?

4 个评论
你实际上是在哪里调用API的?
请避免 张贴文字图片 .更好的做法是转录它们。
stackoverflow.com/users/6789321/accdias 在创建表格时,文本编辑器在发布问题时出现了错误。我将再次尝试。
python
csv
pytest
Maddy9
Maddy9
发布于 2022-01-13
2 个回答
Ilya
Ilya
发布于 2022-01-14
已采纳
0 人赞同

Check this out, I think it might help docs .对于你的具体例子,你可以这样做

import pytest
def load_cases():
    # read_csv
    class Case:
        def __init__(self, number):
            self.i = number
        def __repr__(self):
            return '{number}'.format(number=self.i)
    return [Case(i) for i in range(5)]
def parametrize(name, values):
    # function for readable description
    return pytest.mark.parametrize(name, values, ids=map(repr, values))
@parametrize("case", load_cases())
def test_responses(case):
    print(case.i)

你正在创建Case类,并在这个类中存储你需要的一切,然后从测试中访问属性。你也可以玩玩indirect参数化的固定装置,但不要使你的代码过于复杂。

要读取一个特定的列,请使用如下方法大熊猫 or just split your string.

Kale Kundert
Kale Kundert
发布于 2022-01-14
0 人赞同

我写了一个包,叫做 从文件参数化 可以用来做这件事。 我举了一个详细的例子,说明如何 从一个XLSX文件中加载测试参数 在另一篇Stack Overflow的帖子中,但我将在这里简要地重申重要观点。

唯一复杂的是 从文件参数化 希望能够以字典列表的形式加载测试用例(更多信息见文档)。 这种布局对YAML/TOML/NestedText文件是有意义的,但对XLSX/CSV文件则没有意义。 所以我们需要提供一个函数来加载相关的XSLX/CSV文件并将其转换为预期的格式。 替换代码0】使这一点很容易做到,如果你愿意添加依赖关系的话,否则自己写一些东西可能不会太难。

编辑:这里有一个更具体的例子。 首先,这里是CSV文件可能的样子。

request_,payload,header,response,code
http://localhost:8080/c/u/t,{"ci":""},{},{"ss":""},200
http://localhost:8080/c/u/t?Id=x,{"ci":""},{},{"res":""},200

有几件事需要注意。

  • The first row gives a name to each column. The code I've written relies on this, and use those same names as the arguments to the parametrized test function. If your file doesn't have these headers, you would need to hard-code names each column.
  • The name "request" is reserved by pytest, so we have to use "request_" here.
  • 下面是相应的测试脚本可能是什么样子的。

    import parametrize_from_file as pff
    from csv import DictReader
    from collections import defaultdict
    def load_csv(path):
        with open(path) as f:
            cases = list(DictReader(f))
        return defaultdict(lambda: cases)
    pff.add_loader('.csv', load_csv)
    @pff.parametrize
    def test_api_request_response(request_, payload, header, response, code):
        assert request_ == ...
        assert payload == ...
        assert headers == ...
        assert response == ...
        assert code == ...