【问题标题】:How to read data from JSON file in ddt Python如何在 ddt Python 中从 JSON 文件中读取数据
【发布时间】:2020-07-06 13:43:03
【问题描述】:

我在 python 中使用 ddt。 我有读取 csv 的代码,看起来像这样 -

import csv

def getcsvdata(filename):
    rows = []
    datafile = open(filename, "r")
    reader = csv.reader(datafile)
    next(reader)
    for row in reader:
        rows.append(row)
    return rows

如何将行从“指定的行数”跳过到“指定的行数”? 在上面的代码中,下一个(读者)正在跳过标题行。

我还需要知道如何从 JSON 文件中读取数据? 示例 JSON 文件-

{
    {
        "email": "amit@some.com",
        "passowrd": "123@123"
    },
    {
        "email": "tanvi@some.com",
        "passowrd": "123@456"
    },
    {
        "email": "tc.u@some.io",
        "passowrd": "123@789"
    }
}

【问题讨论】:

    标签: python python-unittest ddt


    【解决方案1】:

    您唯一需要的是库json

    Python 通常附带此库。

    import json
    
    def getJsonData(filepath):
        return json.load(open(filepath))
    
    data = getJsonData("the/file/path.json")
    for item in data:
        print(f"email -> {item['email']}")
        print(f"password -> {item['password']}")
    
    # output:
    # email -> amit@some.com
    # password -> 123@123
    # email -> tanvi@some.com
    # password -> 123@456
    # email -> tc.u@some.io
    # password -> 123@789
    

    【讨论】:

    • 我在测试中使用@file_data(filepath) 注释。返回 json.load 不起作用。我需要返回一个列表。
    • @CharuJain 你能更详细地解释一下你在说什么吗?
    • 对不起,我忘了提到 @file_data 装饰器。我正在使用 @file_data 装饰器进行测试,它以 json 文件的路径为参数。装饰器如何为给定的 json 格式工作。
    • 这个装饰器到底应该做什么? @CharuJain
    • 这个装饰器用于从 json 或 yml 文件中读取数据。
    【解决方案2】:

    这是我使用 json 和 ddt 所做的。

    [
        {
            "email": "amit@some.com",
            "passowrd": "123@123"
        },
        {
            "email": "tanvi@some.com",
            "passowrd": "123@456"
        },
        {
            "email": "tc.u@some.io",
            "passowrd": "123@789"
        }
    ]
    

    然后像这样编写你的测试。

    import unittest
    from ddt import ddt, data, unpack, file_data
    
    @ddt
    class TestCase(unittest.TestCase):
    """Some test case """
    
        @file_data('test.json')
        def test_email_and_username(self, email, password):
            """This tests some stuff"""
            do some assertions here
    

    【讨论】:

      【解决方案3】:

      需要使用json。

      import json
      json.loads(file object)
      

      【讨论】:

        猜你喜欢
        • 2022-12-11
        • 2022-01-17
        • 1970-01-01
        • 2018-04-07
        • 2021-08-19
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多