如何对这个序列化进行测试,当它没有合并所有属性时会失败?

问题描述 投票:0回答:1

我在 Python 3.12.0 中有以下类:

class MyFile:
    def __init__(self,filepath: str):
        self._file_path = filepath
        self._file_size: str = None
        self._tags = set()
        self._collection:str = None
        self._file_hash: str = "" # Prob use SHA
        self._previous_filepaths = [] #Latest last
        self._device = ""


    def to_dict(self):
        return {
            "file_path": self._file_path,
            "file_size": self._file_size,
            "tags": list(self._tags),
            "collection": self._collection,
            "file_hash": self._file_hash,
            "previous_filepaths": self._previous_filepaths,
            "device": self._device

        }

我遇到的问题是,如果我去向类添加一个新属性,如下所示:

class MyFile:
    def __init__(self,filepath: str):
        self._file_path = filepath
        self._file_size: str = None
        self._tags = set()
        self._NEW_ATTRIBUTE: str = None
        self._collection:str = None
        self._file_hash: str = "" # Prob use SHA
        self._previous_filepaths = [] #Latest last
        self._device = ""

当我运行程序时,数据将准备通过

to_dict()
进行序列化,但缺少 _NEW_ATTRIBUTE。这将默默地导致程序在下次加载时出现故障,因为该属性不会被反序列化并加载到内存中,因为它实际上从未被序列化过。

如何缓解这个问题?我想过尝试编写一个单元测试,但意识到如果我这样做,也会出现同样的问题,因为我也会忘记使用新属性更新单元测试。有没有办法测试类属性是否与某些提供的

to_dict()
方法返回匹配?

请注意:这个类没有嵌入其他复杂的类对象,但我有其他类,例如,类属性是其他类对象的列表,所以我认为简单的

.__dict__
不起作用。

python json unit-testing class serialization
1个回答
0
投票

您可以添加一个潜在的测试:

vars(file).keys() == file.to_dict().keys()
© www.soinside.com 2019 - 2024. All rights reserved.