我有以下課程,我想為它撰寫幾個單元測驗:
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_file,self.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) ##??
uj5u.com熱心網友回復:
問題是您不希望您的代碼實際上open是磁盤上的一個檔案,而load您只想提供結果。一種方法是模擬使用的open和json.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因為我認為它使事情更清楚)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411849.html
標籤:
