如何定义每个单元测试的类实例



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

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) ##??

问题是,您不希望您的代码实际上open是磁盘上的一个文件,而load是它,您只想提供结果。一种方法是模拟TestValidator使用的openjson.load引用,如下所示:

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,因为我认为这会让事情变得更清楚(

最新更新