[QA-Daily] Python Related 库,拯救你满是 dict 的代码,让测试代码更好懂

Related 是一个 python 的仓库,用来序列化和反序列. 对于测试人员来说,选择一个第三方 lib 的使用,最主要的是三点:

下面一张图就把 related 要做的事情表达的比较清楚了:

img

通过以下几个例子说明 related 的用法.

Related: to yml

如何将 python 类转化为 yaml 格式:

@related.immutable
class RoleModels(object):
scientists = related.SetField(Person)


- 把实例转化为yaml格式:

```python
people = [Person(first_name="Grace", last_name="Hopper"),
          Person(first_name="Katherine", last_name="Johnson"),
          Person(first_name="Katherine", last_name="Johnson")]

print(related.to_yaml(RoleModels(scientists=people)))

Related: json 操作

@related.immutable
class StoreData(object):
    name = related.StringField()
    id = related.IntegerField()
    created_on = related.DateTimeField("%m/%d/%Y %H:%M:%S")
    data_from = related.DateTimeField()
    data_to = related.DateTimeField()
    days = related.SequenceField(DayData)
    price = related.DecimalField()
def test_json_from_to():
    json_str = """
    {
    "created_on": "12/21/2017 14:21:55",
    "data_from": "2017-12-18T00:00:00",
    "data_to": "2017-12-19T23:59:59",
    "days": [
        {
            "closed_on": "19:00:00",
            "customers": 487,
            "date": "2017-12-18",
            "day_type": "Normal",
            "logged_on": "19:20",
            "open_at": "08:00:00",
            "sales": 27223.65
        },
        {
            "closed_on": "17:30:00",
            "customers": 192,
            "date": "2017-12-19",
            "day_type": "Holiday",
            "logged_on": "17:50",
            "open_at": "10:30:00"
        }
    ],
    "id": 982,
    "name": "Acme store",
    "price": "98237.448"
    }"""
    json_dict = from_json(json_str)
    print(type(json_dict))
    print(json_dict)
    store_data = to_model(StoreData,json_dict)
    print(store_data.name)
    print(to_json(store_data))

如果更高级的使用,可以参考github-related

也欢迎大家查询公众号:动手吧测试,大家一起相互学习分享测试技术,在测试的路上不孤单.
以上文章也会在动手吧测试公告号发布


↙↙↙阅读原文可查看相关链接,并与作者交流