【问题标题】:How to define class instances per unit test?如何定义每个单元测试的类实例?
【发布时间】:2022-01-13 22:02:56
【问题描述】:

我有以下类,我想为它写几个单元测试:

class JsonSchemaValidator:
    def __init__(self, json_file):
        self.json_file = json_file
        self.schema = json.load(open(json_file))

    def check_json_schema(self):
        print(self.json_file)
        Draft3Validator.check_schema(self.schema)

如上所示,该类有self.json_fileself.schema 两个实例,我想为每个测试定义架构。如何设置测试,以便可以为每个测试用例定义架构?

class TestValidator(TestCase):
    def test_check_json_schema1(self):
        schema = {
            "type": "object",
            "properties": {
                "key1": {"type": "string"}
            },
        }
        actual = JsonSchemaValidator.check_json_schema() ##??
        self.assertIsNone(actual)

    def test_check_json_schema2(self):
        schema = {
            "type": "object",
            "properties": {
                "key2": {"type": "SOME_TYPE"}
            },
        }
        self.assertRaises(SchemaError, JsonSchemaValidator.check_json_schema, schema) ##??

【问题讨论】:

    标签: python class python-unittest python-class


    【解决方案1】:

    问题是您不希望您的代码实际上open 磁盘上的一个文件和load 它,您只想提供结果。 一种方法是mock openjson.load 引用 TestValidator 使用,像这样:

    import json
    import unittest
    import unittest.mock as mocking
    
    
    class JsonSchemaValidator:
        def __init__(self, json_file_path):
            self.json_file_path = json_file_path
            self.schema = json.load(open(json_file_path))
    
        def check(self):
            print(self.json_file_path)
            # do the validation here
    
    
    class TestValidator(unittest.TestCase):
        def test_check_json_schema1(self):
            schema = {
                "type": "object",
                "properties": {
                    "key1": {"type": "string"}
                },
            }
            with mocking.patch("builtins.open"), \
                    mocking.patch.object(json, "load", new=mocking.Mock(return_value=schema)):
    
                validator = JsonSchemaValidator("/blah")
                print(validator.schema)  # exactly what we wanted : {'type': 'object', 'properties': {'key1': {'type': 'string'}}}
    
                # do your test here
                validator.check()
                ...
    

    您可以通过将print(json.load, open) 添加到JsonSchemaValidator.__init__ 来检查,您会得到类似的内容:

    <Mock id='139724038827840'> <MagicMock name='open' id='139724039146992'>
    

    因为当您在上下文管理器 (with) 中时,它们已被嘲笑。

    (我将json_file 重命名为json_file_path,因为我认为这样更清楚)

    【讨论】:

    • @Marc 解决了你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2012-10-13
    • 2018-11-01
    • 2012-06-07
    • 1970-01-01
    相关资源
    最近更新 更多