1
0

test_schema.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501
  1. # -*- coding: utf-8 -*-
  2. # pylint: disable=function-redefined,missing-docstring
  3. # TODO: Remove the following PyLint disable as soon as we support YAML and RST rendering
  4. # pylint: disable=abstract-method
  5. # Import python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import copy
  8. # Import Salt Libs
  9. import salt.utils.json
  10. import salt.utils.schema as schema
  11. import salt.utils.stringutils
  12. import salt.utils.yaml
  13. from salt.ext import six
  14. from salt.utils.versions import LooseVersion as _LooseVersion
  15. # Import Salt Testing Libs
  16. from tests.support.unit import TestCase, skipIf
  17. # Import 3rd-party libs
  18. try:
  19. import jsonschema
  20. import jsonschema.exceptions
  21. HAS_JSONSCHEMA = True
  22. JSONSCHEMA_VERSION = _LooseVersion(jsonschema.__version__)
  23. except ImportError:
  24. HAS_JSONSCHEMA = False
  25. JSONSCHEMA_VERSION = _LooseVersion("0")
  26. # pylint: disable=unused-import
  27. try:
  28. import rfc3987
  29. HAS_RFC3987 = True
  30. except ImportError:
  31. HAS_RFC3987 = False
  32. try:
  33. import strict_rfc3339
  34. HAS_STRICT_RFC3339 = True
  35. except ImportError:
  36. HAS_STRICT_RFC3339 = False
  37. # pylint: enable=unused-import
  38. class ConfigTestCase(TestCase):
  39. """
  40. TestCase for salt.utils.config module
  41. """
  42. def test_configuration_subclass_inherits_items(self):
  43. class BaseConfig(schema.Schema):
  44. base = schema.BooleanItem(default=True, required=True)
  45. class SubClassedConfig(BaseConfig):
  46. hungry = schema.BooleanItem(
  47. title="Hungry", description="Are you hungry?", required=True
  48. )
  49. self.assertDictEqual(
  50. SubClassedConfig.serialize(),
  51. {
  52. "$schema": "http://json-schema.org/draft-04/schema#",
  53. "type": "object",
  54. "properties": {
  55. "base": {"default": True, "type": "boolean", "title": "base"},
  56. "hungry": {
  57. "type": "boolean",
  58. "description": "Are you hungry?",
  59. "title": "Hungry",
  60. },
  61. },
  62. "required": ["base", "hungry"],
  63. "x-ordering": ["base", "hungry"],
  64. "additionalProperties": False,
  65. },
  66. )
  67. class MergedConfigClass(schema.Schema):
  68. thirsty = schema.BooleanItem(
  69. title="Thirsty", description="Are you thirsty?", required=True
  70. )
  71. merge_subclassed = SubClassedConfig(flatten=True)
  72. expected = {
  73. "$schema": "http://json-schema.org/draft-04/schema#",
  74. "type": "object",
  75. "properties": {
  76. "thirsty": {
  77. "type": "boolean",
  78. "description": "Are you thirsty?",
  79. "title": "Thirsty",
  80. },
  81. "base": {"default": True, "type": "boolean", "title": "base"},
  82. "hungry": {
  83. "type": "boolean",
  84. "description": "Are you hungry?",
  85. "title": "Hungry",
  86. },
  87. },
  88. "required": ["thirsty", "base", "hungry"],
  89. "x-ordering": ["thirsty", "base", "hungry"],
  90. "additionalProperties": False,
  91. }
  92. self.assertDictContainsSubset(
  93. MergedConfigClass.serialize()["properties"], expected["properties"]
  94. )
  95. self.assertDictContainsSubset(expected, MergedConfigClass.serialize())
  96. def test_configuration_items_order(self):
  97. class One(schema.Schema):
  98. one = schema.BooleanItem()
  99. class Three(schema.Schema):
  100. three = schema.BooleanItem()
  101. class Final(One):
  102. two = schema.BooleanItem()
  103. three = Three(flatten=True)
  104. self.assertEqual(Final.serialize()["x-ordering"], ["one", "two", "three"])
  105. def test_optional_requirements_config(self):
  106. class BaseRequirements(schema.Schema):
  107. driver = schema.StringItem(default="digitalocean", format="hidden")
  108. class SSHKeyFileSchema(schema.Schema):
  109. ssh_key_file = schema.StringItem(
  110. title="SSH Private Key",
  111. description="The path to an SSH private key which will be used "
  112. "to authenticate on the deployed VMs",
  113. )
  114. class SSHKeyNamesSchema(schema.Schema):
  115. ssh_key_names = schema.StringItem(
  116. title="SSH Key Names",
  117. description="The names of an SSH key being managed on "
  118. "DigitalOcean account which will be used to "
  119. "authenticate on the deployed VMs",
  120. )
  121. class Requirements(BaseRequirements):
  122. title = "DigitalOcean"
  123. description = "DigitalOcean Cloud VM configuration requirements."
  124. personal_access_token = schema.StringItem(
  125. title="Personal Access Token",
  126. description="This is the API access token which can be generated "
  127. "under the API/Application on your account",
  128. required=True,
  129. )
  130. requirements_definition = schema.AnyOfItem(
  131. items=(
  132. SSHKeyFileSchema.as_requirements_item(),
  133. SSHKeyNamesSchema.as_requirements_item(),
  134. ),
  135. )(flatten=True)
  136. ssh_key_file = SSHKeyFileSchema(flatten=True)
  137. ssh_key_names = SSHKeyNamesSchema(flatten=True)
  138. expected = {
  139. "$schema": "http://json-schema.org/draft-04/schema#",
  140. "title": "DigitalOcean",
  141. "description": "DigitalOcean Cloud VM configuration requirements.",
  142. "type": "object",
  143. "properties": {
  144. "driver": {
  145. "default": "digitalocean",
  146. "format": "hidden",
  147. "type": "string",
  148. "title": "driver",
  149. },
  150. "personal_access_token": {
  151. "type": "string",
  152. "description": "This is the API access token which can be "
  153. "generated under the API/Application on your account",
  154. "title": "Personal Access Token",
  155. },
  156. "ssh_key_file": {
  157. "type": "string",
  158. "description": "The path to an SSH private key which will "
  159. "be used to authenticate on the deployed VMs",
  160. "title": "SSH Private Key",
  161. },
  162. "ssh_key_names": {
  163. "type": "string",
  164. "description": "The names of an SSH key being managed on DigitalOcean "
  165. "account which will be used to authenticate on the deployed VMs",
  166. "title": "SSH Key Names",
  167. },
  168. },
  169. "anyOf": [{"required": ["ssh_key_file"]}, {"required": ["ssh_key_names"]}],
  170. "required": ["personal_access_token"],
  171. "x-ordering": [
  172. "driver",
  173. "personal_access_token",
  174. "ssh_key_file",
  175. "ssh_key_names",
  176. ],
  177. "additionalProperties": False,
  178. }
  179. self.assertDictEqual(expected, Requirements.serialize())
  180. class Requirements2(BaseRequirements):
  181. title = "DigitalOcean"
  182. description = "DigitalOcean Cloud VM configuration requirements."
  183. personal_access_token = schema.StringItem(
  184. title="Personal Access Token",
  185. description="This is the API access token which can be generated "
  186. "under the API/Application on your account",
  187. required=True,
  188. )
  189. ssh_key_file = schema.StringItem(
  190. title="SSH Private Key",
  191. description="The path to an SSH private key which will be used "
  192. "to authenticate on the deployed VMs",
  193. )
  194. ssh_key_names = schema.StringItem(
  195. title="SSH Key Names",
  196. description="The names of an SSH key being managed on "
  197. "DigitalOcean account which will be used to "
  198. "authenticate on the deployed VMs",
  199. )
  200. requirements_definition = schema.AnyOfItem(
  201. items=(
  202. schema.RequirementsItem(requirements=["ssh_key_file"]),
  203. schema.RequirementsItem(requirements=["ssh_key_names"]),
  204. ),
  205. )(flatten=True)
  206. expected = {
  207. "$schema": "http://json-schema.org/draft-04/schema#",
  208. "title": "DigitalOcean",
  209. "description": "DigitalOcean Cloud VM configuration requirements.",
  210. "type": "object",
  211. "properties": {
  212. "driver": {
  213. "default": "digitalocean",
  214. "format": "hidden",
  215. "type": "string",
  216. "title": "driver",
  217. },
  218. "personal_access_token": {
  219. "type": "string",
  220. "description": "This is the API access token which can be "
  221. "generated under the API/Application on your account",
  222. "title": "Personal Access Token",
  223. },
  224. "ssh_key_file": {
  225. "type": "string",
  226. "description": "The path to an SSH private key which will "
  227. "be used to authenticate on the deployed VMs",
  228. "title": "SSH Private Key",
  229. },
  230. "ssh_key_names": {
  231. "type": "string",
  232. "description": "The names of an SSH key being managed on DigitalOcean "
  233. "account which will be used to authenticate on the deployed VMs",
  234. "title": "SSH Key Names",
  235. },
  236. },
  237. "anyOf": [{"required": ["ssh_key_file"]}, {"required": ["ssh_key_names"]}],
  238. "required": ["personal_access_token"],
  239. "x-ordering": [
  240. "driver",
  241. "personal_access_token",
  242. "ssh_key_file",
  243. "ssh_key_names",
  244. ],
  245. "additionalProperties": False,
  246. }
  247. self.assertDictContainsSubset(expected, Requirements2.serialize())
  248. class Requirements3(schema.Schema):
  249. title = "DigitalOcean"
  250. description = "DigitalOcean Cloud VM configuration requirements."
  251. merge_reqs = Requirements(flatten=True)
  252. expected = {
  253. "$schema": "http://json-schema.org/draft-04/schema#",
  254. "title": "DigitalOcean",
  255. "description": "DigitalOcean Cloud VM configuration requirements.",
  256. "type": "object",
  257. "properties": {
  258. "driver": {
  259. "default": "digitalocean",
  260. "format": "hidden",
  261. "type": "string",
  262. "title": "driver",
  263. },
  264. "personal_access_token": {
  265. "type": "string",
  266. "description": "This is the API access token which can be "
  267. "generated under the API/Application on your account",
  268. "title": "Personal Access Token",
  269. },
  270. "ssh_key_file": {
  271. "type": "string",
  272. "description": "The path to an SSH private key which will "
  273. "be used to authenticate on the deployed VMs",
  274. "title": "SSH Private Key",
  275. },
  276. "ssh_key_names": {
  277. "type": "string",
  278. "description": "The names of an SSH key being managed on DigitalOcean "
  279. "account which will be used to authenticate on the deployed VMs",
  280. "title": "SSH Key Names",
  281. },
  282. },
  283. "anyOf": [{"required": ["ssh_key_file"]}, {"required": ["ssh_key_names"]}],
  284. "required": ["personal_access_token"],
  285. "x-ordering": [
  286. "driver",
  287. "personal_access_token",
  288. "ssh_key_file",
  289. "ssh_key_names",
  290. ],
  291. "additionalProperties": False,
  292. }
  293. self.assertDictContainsSubset(expected, Requirements3.serialize())
  294. class Requirements4(schema.Schema):
  295. title = "DigitalOcean"
  296. description = "DigitalOcean Cloud VM configuration requirements."
  297. merge_reqs = Requirements(flatten=True)
  298. ssh_key_file_2 = schema.StringItem(
  299. title="SSH Private Key",
  300. description="The path to an SSH private key which will be used "
  301. "to authenticate on the deployed VMs",
  302. )
  303. ssh_key_names_2 = schema.StringItem(
  304. title="SSH Key Names",
  305. description="The names of an SSH key being managed on "
  306. "DigitalOcean account which will be used to "
  307. "authenticate on the deployed VMs",
  308. )
  309. requirements_definition_2 = schema.AnyOfItem(
  310. items=(
  311. schema.RequirementsItem(requirements=["ssh_key_file_2"]),
  312. schema.RequirementsItem(requirements=["ssh_key_names_2"]),
  313. ),
  314. )(flatten=True)
  315. expected = {
  316. "$schema": "http://json-schema.org/draft-04/schema#",
  317. "title": "DigitalOcean",
  318. "description": "DigitalOcean Cloud VM configuration requirements.",
  319. "type": "object",
  320. "properties": {
  321. "driver": {
  322. "default": "digitalocean",
  323. "format": "hidden",
  324. "type": "string",
  325. "title": "driver",
  326. },
  327. "personal_access_token": {
  328. "type": "string",
  329. "description": "This is the API access token which can be "
  330. "generated under the API/Application on your account",
  331. "title": "Personal Access Token",
  332. },
  333. "ssh_key_file": {
  334. "type": "string",
  335. "description": "The path to an SSH private key which will "
  336. "be used to authenticate on the deployed VMs",
  337. "title": "SSH Private Key",
  338. },
  339. "ssh_key_names": {
  340. "type": "string",
  341. "description": "The names of an SSH key being managed on DigitalOcean "
  342. "account which will be used to authenticate on the deployed VMs",
  343. "title": "SSH Key Names",
  344. },
  345. "ssh_key_file_2": {
  346. "type": "string",
  347. "description": "The path to an SSH private key which will "
  348. "be used to authenticate on the deployed VMs",
  349. "title": "SSH Private Key",
  350. },
  351. "ssh_key_names_2": {
  352. "type": "string",
  353. "description": "The names of an SSH key being managed on DigitalOcean "
  354. "account which will be used to authenticate on the deployed VMs",
  355. "title": "SSH Key Names",
  356. },
  357. },
  358. "anyOf": [
  359. {"required": ["ssh_key_file"]},
  360. {"required": ["ssh_key_names"]},
  361. {"required": ["ssh_key_file_2"]},
  362. {"required": ["ssh_key_names_2"]},
  363. ],
  364. "required": ["personal_access_token"],
  365. "x-ordering": [
  366. "driver",
  367. "personal_access_token",
  368. "ssh_key_file",
  369. "ssh_key_names",
  370. "ssh_key_file_2",
  371. "ssh_key_names_2",
  372. ],
  373. "additionalProperties": False,
  374. }
  375. self.assertDictContainsSubset(expected, Requirements4.serialize())
  376. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  377. def test_optional_requirements_config_validation(self):
  378. class BaseRequirements(schema.Schema):
  379. driver = schema.StringItem(default="digitalocean", format="hidden")
  380. class SSHKeyFileSchema(schema.Schema):
  381. ssh_key_file = schema.StringItem(
  382. title="SSH Private Key",
  383. description="The path to an SSH private key which will be used "
  384. "to authenticate on the deployed VMs",
  385. )
  386. class SSHKeyNamesSchema(schema.Schema):
  387. ssh_key_names = schema.StringItem(
  388. title="SSH Key Names",
  389. description="The names of an SSH key being managed on "
  390. "Digial Ocean account which will be used to "
  391. "authenticate on the deployed VMs",
  392. )
  393. class Requirements(BaseRequirements):
  394. title = "DigitalOcean"
  395. description = "DigitalOcean Cloud VM configuration requirements."
  396. personal_access_token = schema.StringItem(
  397. title="Personal Access Token",
  398. description="This is the API access token which can be generated "
  399. "under the API/Application on your account",
  400. required=True,
  401. )
  402. requirements_definition = schema.AnyOfItem(
  403. items=(
  404. SSHKeyFileSchema.as_requirements_item(),
  405. SSHKeyNamesSchema.as_requirements_item(),
  406. ),
  407. )(flatten=True)
  408. ssh_key_file = SSHKeyFileSchema(flatten=True)
  409. ssh_key_names = SSHKeyNamesSchema(flatten=True)
  410. try:
  411. jsonschema.validate(
  412. {
  413. "personal_access_token": "foo",
  414. "ssh_key_names": "bar",
  415. "ssh_key_file": "test",
  416. },
  417. Requirements.serialize(),
  418. )
  419. except jsonschema.exceptions.ValidationError as exc:
  420. self.fail("ValidationError raised: {0}".format(exc))
  421. try:
  422. jsonschema.validate(
  423. {"personal_access_token": "foo", "ssh_key_names": "bar"},
  424. Requirements.serialize(),
  425. )
  426. except jsonschema.exceptions.ValidationError as exc:
  427. self.fail("ValidationError raised: {0}".format(exc))
  428. try:
  429. jsonschema.validate(
  430. {"personal_access_token": "foo", "ssh_key_file": "test"},
  431. Requirements.serialize(),
  432. )
  433. except jsonschema.exceptions.ValidationError as exc:
  434. self.fail("ValidationError raised: {0}".format(exc))
  435. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  436. jsonschema.validate(
  437. {"personal_access_token": "foo"}, Requirements.serialize()
  438. )
  439. if JSONSCHEMA_VERSION >= _LooseVersion("3.0.0"):
  440. self.assertIn(
  441. "'ssh_key_file' is a required property", excinfo.exception.message
  442. )
  443. else:
  444. self.assertIn(
  445. "is not valid under any of the given schemas", excinfo.exception.message
  446. )
  447. def test_boolean_config(self):
  448. item = schema.BooleanItem(title="Hungry", description="Are you hungry?")
  449. self.assertDictEqual(
  450. item.serialize(),
  451. {"type": "boolean", "title": item.title, "description": item.description},
  452. )
  453. item = schema.BooleanItem(
  454. title="Hungry", description="Are you hungry?", default=False
  455. )
  456. self.assertDictEqual(
  457. item.serialize(),
  458. {
  459. "type": "boolean",
  460. "title": item.title,
  461. "description": item.description,
  462. "default": item.default,
  463. },
  464. )
  465. item = schema.BooleanItem(
  466. title="Hungry", description="Are you hungry?", default=schema.Null
  467. )
  468. self.assertDictEqual(
  469. item.serialize(),
  470. {
  471. "type": "boolean",
  472. "title": item.title,
  473. "description": item.description,
  474. "default": None,
  475. },
  476. )
  477. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  478. def test_boolean_config_validation(self):
  479. class TestConf(schema.Schema):
  480. item = schema.BooleanItem(title="Hungry", description="Are you hungry?")
  481. try:
  482. jsonschema.validate({"item": False}, TestConf.serialize())
  483. except jsonschema.exceptions.ValidationError as exc:
  484. self.fail("ValidationError raised: {0}".format(exc))
  485. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  486. jsonschema.validate({"item": 1}, TestConf.serialize())
  487. self.assertIn("is not of type", excinfo.exception.message)
  488. def test_string_config(self):
  489. item = schema.StringItem(title="Foo", description="Foo Item")
  490. self.assertDictEqual(
  491. item.serialize(),
  492. {"type": "string", "title": item.title, "description": item.description},
  493. )
  494. item = schema.StringItem(
  495. title="Foo", description="Foo Item", min_length=1, max_length=3
  496. )
  497. self.assertDictEqual(
  498. item.serialize(),
  499. {
  500. "type": "string",
  501. "title": item.title,
  502. "description": item.description,
  503. "minLength": item.min_length,
  504. "maxLength": item.max_length,
  505. },
  506. )
  507. item = schema.StringItem(
  508. title="Foo",
  509. description="Foo Item",
  510. min_length=1,
  511. max_length=3,
  512. default="foo",
  513. )
  514. self.assertDictEqual(
  515. item.serialize(),
  516. {
  517. "type": "string",
  518. "title": item.title,
  519. "description": item.description,
  520. "minLength": item.min_length,
  521. "maxLength": item.max_length,
  522. "default": "foo",
  523. },
  524. )
  525. item = schema.StringItem(
  526. title="Foo",
  527. description="Foo Item",
  528. min_length=1,
  529. max_length=3,
  530. enum=("foo", "bar"),
  531. )
  532. self.assertDictEqual(
  533. item.serialize(),
  534. {
  535. "type": "string",
  536. "title": item.title,
  537. "description": item.description,
  538. "minLength": item.min_length,
  539. "maxLength": item.max_length,
  540. "enum": ["foo", "bar"],
  541. },
  542. )
  543. item = schema.StringItem(
  544. title="Foo",
  545. description="Foo Item",
  546. min_length=1,
  547. max_length=3,
  548. enum=("foo", "bar"),
  549. enumNames=("Foo", "Bar"),
  550. )
  551. self.assertDictEqual(
  552. item.serialize(),
  553. {
  554. "type": "string",
  555. "title": item.title,
  556. "description": item.description,
  557. "minLength": item.min_length,
  558. "maxLength": item.max_length,
  559. "enum": ["foo", "bar"],
  560. "enumNames": ["Foo", "Bar"],
  561. },
  562. )
  563. item = schema.StringItem(
  564. title="Foo", description="Foo Item", pattern=r"^([\w_-]+)$"
  565. )
  566. self.assertDictEqual(
  567. item.serialize(),
  568. {
  569. "type": "string",
  570. "title": item.title,
  571. "description": item.description,
  572. "pattern": item.pattern,
  573. },
  574. )
  575. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  576. def test_string_config_validation(self):
  577. class TestConf(schema.Schema):
  578. item = schema.StringItem(title="Foo", description="Foo Item")
  579. try:
  580. jsonschema.validate({"item": "the item"}, TestConf.serialize())
  581. except jsonschema.exceptions.ValidationError as exc:
  582. self.fail("ValidationError raised: {0}".format(exc))
  583. class TestConf(schema.Schema):
  584. item = schema.StringItem(
  585. title="Foo", description="Foo Item", min_length=1, max_length=10
  586. )
  587. try:
  588. jsonschema.validate({"item": "the item"}, TestConf.serialize())
  589. except jsonschema.exceptions.ValidationError as exc:
  590. self.fail("ValidationError raised: {0}".format(exc))
  591. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  592. jsonschema.validate({"item": 3}, TestConf.serialize())
  593. self.assertIn("is not of type", excinfo.exception.message)
  594. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  595. jsonschema.validate({"item": "the item the item"}, TestConf.serialize())
  596. self.assertIn("is too long", excinfo.exception.message)
  597. class TestConf(schema.Schema):
  598. item = schema.StringItem(
  599. title="Foo", description="Foo Item", min_length=10, max_length=100
  600. )
  601. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  602. jsonschema.validate({"item": "the item"}, TestConf.serialize())
  603. self.assertIn("is too short", excinfo.exception.message)
  604. class TestConf(schema.Schema):
  605. item = schema.StringItem(
  606. title="Foo", description="Foo Item", enum=("foo", "bar")
  607. )
  608. try:
  609. jsonschema.validate({"item": "foo"}, TestConf.serialize())
  610. except jsonschema.exceptions.ValidationError as exc:
  611. self.fail("ValidationError raised: {0}".format(exc))
  612. class TestConf(schema.Schema):
  613. item = schema.StringItem(
  614. title="Foo", description="Foo Item", enum=("foo", "bar")
  615. )
  616. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  617. jsonschema.validate({"item": "bin"}, TestConf.serialize())
  618. self.assertIn("is not one of", excinfo.exception.message)
  619. class TestConf(schema.Schema):
  620. item = schema.StringItem(
  621. title="Foo", description="Foo Item", pattern=r"^([\w_-]+)$"
  622. )
  623. try:
  624. jsonschema.validate(
  625. {"item": "the-item"},
  626. TestConf.serialize(),
  627. format_checker=jsonschema.FormatChecker(),
  628. )
  629. except jsonschema.exceptions.ValidationError as exc:
  630. self.fail("ValidationError raised: {0}".format(exc))
  631. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  632. jsonschema.validate(
  633. {"item": "the item"},
  634. TestConf.serialize(),
  635. format_checker=jsonschema.FormatChecker(),
  636. )
  637. self.assertIn("does not match", excinfo.exception.message)
  638. def test_email_config(self):
  639. item = schema.EMailItem(title="Foo", description="Foo Item")
  640. self.assertDictEqual(
  641. item.serialize(),
  642. {
  643. "type": "string",
  644. "title": item.title,
  645. "description": item.description,
  646. "format": item.format,
  647. },
  648. )
  649. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  650. def test_email_config_validation(self):
  651. class TestConf(schema.Schema):
  652. item = schema.EMailItem(title="Item", description="Item description")
  653. try:
  654. jsonschema.validate(
  655. {"item": "nobody@nowhere.com"},
  656. TestConf.serialize(),
  657. format_checker=jsonschema.FormatChecker(),
  658. )
  659. except jsonschema.exceptions.ValidationError as exc:
  660. self.fail("ValidationError raised: {0}".format(exc))
  661. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  662. jsonschema.validate(
  663. {"item": "3"},
  664. TestConf.serialize(),
  665. format_checker=jsonschema.FormatChecker(),
  666. )
  667. self.assertIn("is not a", excinfo.exception.message)
  668. def test_ipv4_config(self):
  669. item = schema.IPv4Item(title="Foo", description="Foo Item")
  670. self.assertDictEqual(
  671. item.serialize(),
  672. {
  673. "type": "string",
  674. "title": item.title,
  675. "description": item.description,
  676. "format": item.format,
  677. },
  678. )
  679. @skipIf(
  680. JSONSCHEMA_VERSION <= _LooseVersion("2.5.0"),
  681. "Requires jsonschema 2.5.0 or greater",
  682. )
  683. def test_ipv4_config_validation(self):
  684. class TestConf(schema.Schema):
  685. item = schema.IPv4Item(title="Item", description="Item description")
  686. try:
  687. jsonschema.validate(
  688. {"item": "127.0.0.1"},
  689. TestConf.serialize(),
  690. format_checker=jsonschema.FormatChecker(),
  691. )
  692. except jsonschema.exceptions.ValidationError as exc:
  693. self.fail("ValidationError raised: {0}".format(exc))
  694. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  695. jsonschema.validate(
  696. {"item": "3"},
  697. TestConf.serialize(),
  698. format_checker=jsonschema.FormatChecker(),
  699. )
  700. self.assertIn("is not a", excinfo.exception.message)
  701. def test_ipv6_config(self):
  702. item = schema.IPv6Item(title="Foo", description="Foo Item")
  703. self.assertDictEqual(
  704. item.serialize(),
  705. {
  706. "type": "string",
  707. "title": item.title,
  708. "description": item.description,
  709. "format": item.format,
  710. },
  711. )
  712. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  713. def test_ipv6_config_validation(self):
  714. class TestConf(schema.Schema):
  715. item = schema.IPv6Item(title="Item", description="Item description")
  716. try:
  717. jsonschema.validate(
  718. {"item": salt.utils.stringutils.to_str("::1")},
  719. TestConf.serialize(),
  720. format_checker=jsonschema.FormatChecker(),
  721. )
  722. except jsonschema.exceptions.ValidationError as exc:
  723. self.fail("ValidationError raised: {0}".format(exc))
  724. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  725. jsonschema.validate(
  726. {"item": "3"},
  727. TestConf.serialize(),
  728. format_checker=jsonschema.FormatChecker(),
  729. )
  730. self.assertIn("is not a", excinfo.exception.message)
  731. def test_hostname_config(self):
  732. item = schema.HostnameItem(title="Foo", description="Foo Item")
  733. self.assertDictEqual(
  734. item.serialize(),
  735. {
  736. "type": "string",
  737. "title": item.title,
  738. "description": item.description,
  739. "format": item.format,
  740. },
  741. )
  742. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  743. def test_hostname_config_validation(self):
  744. class TestConf(schema.Schema):
  745. item = schema.HostnameItem(title="Item", description="Item description")
  746. try:
  747. jsonschema.validate(
  748. {"item": "localhost"},
  749. TestConf.serialize(),
  750. format_checker=jsonschema.FormatChecker(),
  751. )
  752. except jsonschema.exceptions.ValidationError as exc:
  753. self.fail("ValidationError raised: {0}".format(exc))
  754. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  755. jsonschema.validate(
  756. {"item": "3"},
  757. TestConf.serialize(),
  758. format_checker=jsonschema.FormatChecker(),
  759. )
  760. self.assertIn("is not a", excinfo.exception.message)
  761. def test_datetime_config(self):
  762. item = schema.DateTimeItem(title="Foo", description="Foo Item")
  763. self.assertDictEqual(
  764. item.serialize(),
  765. {
  766. "type": "string",
  767. "title": item.title,
  768. "description": item.description,
  769. "format": item.format,
  770. },
  771. )
  772. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  773. @skipIf(not HAS_STRICT_RFC3339, "The 'strict_rfc3339' library is missing")
  774. def test_datetime_config_validation(self):
  775. class TestConf(schema.Schema):
  776. item = schema.DateTimeItem(title="Item", description="Item description")
  777. try:
  778. jsonschema.validate(
  779. {"item": "2015-07-01T18:05:27+01:00"},
  780. TestConf.serialize(),
  781. format_checker=jsonschema.FormatChecker(),
  782. )
  783. except jsonschema.exceptions.ValidationError as exc:
  784. self.fail("ValidationError raised: {0}".format(exc))
  785. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  786. jsonschema.validate(
  787. {"item": "3"},
  788. TestConf.serialize(),
  789. format_checker=jsonschema.FormatChecker(),
  790. )
  791. self.assertIn("is not a", excinfo.exception.message)
  792. def test_secret_config(self):
  793. item = schema.SecretItem(title="Foo", description="Foo Item")
  794. self.assertDictEqual(
  795. item.serialize(),
  796. {
  797. "type": "string",
  798. "title": item.title,
  799. "description": item.description,
  800. "format": item.format,
  801. },
  802. )
  803. def test_uri_config(self):
  804. item = schema.UriItem(title="Foo", description="Foo Item")
  805. self.assertDictEqual(
  806. item.serialize(),
  807. {
  808. "type": "string",
  809. "title": item.title,
  810. "description": item.description,
  811. "format": item.format,
  812. },
  813. )
  814. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  815. @skipIf(HAS_RFC3987 is False, "The 'rfc3987' library is missing")
  816. def test_uri_config_validation(self):
  817. class TestConf(schema.Schema):
  818. item = schema.UriItem(title="Item", description="Item description")
  819. try:
  820. jsonschema.validate(
  821. {"item": "ssh://localhost"},
  822. TestConf.serialize(),
  823. format_checker=jsonschema.FormatChecker(),
  824. )
  825. except jsonschema.exceptions.ValidationError as exc:
  826. self.fail("ValidationError raised: {0}".format(exc))
  827. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  828. jsonschema.validate(
  829. {"item": "3"},
  830. TestConf.serialize(),
  831. format_checker=jsonschema.FormatChecker(),
  832. )
  833. self.assertIn("is not a", excinfo.exception.message)
  834. def test_number_config(self):
  835. item = schema.NumberItem(title="How many dogs", description="Question")
  836. self.assertDictEqual(
  837. item.serialize(),
  838. {"type": "number", "title": item.title, "description": item.description},
  839. )
  840. item = schema.NumberItem(
  841. title="How many dogs", description="Question", minimum=0, maximum=10
  842. )
  843. self.assertDictEqual(
  844. item.serialize(),
  845. {
  846. "type": "number",
  847. "title": item.title,
  848. "description": item.description,
  849. "minimum": item.minimum,
  850. "maximum": item.maximum,
  851. },
  852. )
  853. item = schema.NumberItem(
  854. title="How many dogs", description="Question", multiple_of=2
  855. )
  856. self.assertDictEqual(
  857. item.serialize(),
  858. {
  859. "type": "number",
  860. "title": item.title,
  861. "description": item.description,
  862. "multipleOf": item.multiple_of,
  863. },
  864. )
  865. item = schema.NumberItem(
  866. title="How many dogs",
  867. description="Question",
  868. minimum=0,
  869. exclusive_minimum=True,
  870. maximum=10,
  871. exclusive_maximum=True,
  872. )
  873. self.assertDictEqual(
  874. item.serialize(),
  875. {
  876. "type": "number",
  877. "title": item.title,
  878. "description": item.description,
  879. "minimum": item.minimum,
  880. "maximum": item.maximum,
  881. "exclusiveMinimum": True,
  882. "exclusiveMaximum": True,
  883. },
  884. )
  885. item = schema.NumberItem(
  886. title="How many dogs",
  887. description="Question",
  888. minimum=0,
  889. maximum=10,
  890. default=0,
  891. )
  892. self.assertDictEqual(
  893. item.serialize(),
  894. {
  895. "type": "number",
  896. "title": item.title,
  897. "description": item.description,
  898. "minimum": item.minimum,
  899. "maximum": item.maximum,
  900. "default": 0,
  901. },
  902. )
  903. item = schema.NumberItem(
  904. title="How many dogs",
  905. description="Question",
  906. minimum=0,
  907. maximum=10,
  908. default=0,
  909. enum=(0, 2, 4, 6),
  910. )
  911. self.assertDictEqual(
  912. item.serialize(),
  913. {
  914. "type": "number",
  915. "title": item.title,
  916. "description": item.description,
  917. "minimum": item.minimum,
  918. "maximum": item.maximum,
  919. "default": 0,
  920. "enum": [0, 2, 4, 6],
  921. },
  922. )
  923. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  924. def test_number_config_validation(self):
  925. class TestConf(schema.Schema):
  926. item = schema.NumberItem(title="How many dogs", description="Question")
  927. try:
  928. jsonschema.validate({"item": 2}, TestConf.serialize())
  929. except jsonschema.exceptions.ValidationError as exc:
  930. self.fail("ValidationError raised: {0}".format(exc))
  931. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  932. jsonschema.validate({"item": "3"}, TestConf.serialize())
  933. self.assertIn("is not of type", excinfo.exception.message)
  934. class TestConf(schema.Schema):
  935. item = schema.NumberItem(
  936. title="How many dogs", description="Question", multiple_of=2.2
  937. )
  938. try:
  939. jsonschema.validate({"item": 4.4}, TestConf.serialize())
  940. except jsonschema.exceptions.ValidationError as exc:
  941. self.fail("ValidationError raised: {0}".format(exc))
  942. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  943. jsonschema.validate({"item": 4}, TestConf.serialize())
  944. self.assertIn("is not a multiple of", excinfo.exception.message)
  945. class TestConf(schema.Schema):
  946. item = schema.NumberItem(
  947. title="Foo", description="Foo Item", minimum=1, maximum=10
  948. )
  949. try:
  950. jsonschema.validate({"item": 3}, TestConf.serialize())
  951. except jsonschema.exceptions.ValidationError as exc:
  952. self.fail("ValidationError raised: {0}".format(exc))
  953. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  954. jsonschema.validate({"item": 11}, TestConf.serialize())
  955. self.assertIn("is greater than the maximum of", excinfo.exception.message)
  956. class TestConf(schema.Schema):
  957. item = schema.NumberItem(
  958. title="Foo", description="Foo Item", minimum=10, maximum=100
  959. )
  960. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  961. jsonschema.validate({"item": 3}, TestConf.serialize())
  962. self.assertIn("is less than the minimum of", excinfo.exception.message)
  963. class TestConf(schema.Schema):
  964. item = schema.NumberItem(
  965. title="How many dogs",
  966. description="Question",
  967. minimum=0,
  968. exclusive_minimum=True,
  969. maximum=10,
  970. exclusive_maximum=True,
  971. )
  972. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  973. jsonschema.validate({"item": 0}, TestConf.serialize())
  974. self.assertIn(
  975. "is less than or equal to the minimum of", excinfo.exception.message
  976. )
  977. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  978. jsonschema.validate({"item": 10}, TestConf.serialize())
  979. self.assertIn(
  980. "is greater than or equal to the maximum of", excinfo.exception.message
  981. )
  982. class TestConf(schema.Schema):
  983. item = schema.NumberItem(
  984. title="Foo", description="Foo Item", enum=(0, 2, 4, 6)
  985. )
  986. try:
  987. jsonschema.validate({"item": 4}, TestConf.serialize())
  988. except jsonschema.exceptions.ValidationError as exc:
  989. self.fail("ValidationError raised: {0}".format(exc))
  990. class TestConf(schema.Schema):
  991. item = schema.NumberItem(
  992. title="Foo", description="Foo Item", enum=(0, 2, 4, 6)
  993. )
  994. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  995. jsonschema.validate({"item": 3}, TestConf.serialize())
  996. self.assertIn("is not one of", excinfo.exception.message)
  997. def test_integer_config(self):
  998. item = schema.IntegerItem(title="How many dogs", description="Question")
  999. self.assertDictEqual(
  1000. item.serialize(),
  1001. {"type": "integer", "title": item.title, "description": item.description},
  1002. )
  1003. item = schema.IntegerItem(
  1004. title="How many dogs", description="Question", minimum=0, maximum=10
  1005. )
  1006. self.assertDictEqual(
  1007. item.serialize(),
  1008. {
  1009. "type": "integer",
  1010. "title": item.title,
  1011. "description": item.description,
  1012. "minimum": item.minimum,
  1013. "maximum": item.maximum,
  1014. },
  1015. )
  1016. item = schema.IntegerItem(
  1017. title="How many dogs", description="Question", multiple_of=2
  1018. )
  1019. self.assertDictEqual(
  1020. item.serialize(),
  1021. {
  1022. "type": "integer",
  1023. "title": item.title,
  1024. "description": item.description,
  1025. "multipleOf": item.multiple_of,
  1026. },
  1027. )
  1028. item = schema.IntegerItem(
  1029. title="How many dogs",
  1030. description="Question",
  1031. minimum=0,
  1032. exclusive_minimum=True,
  1033. maximum=10,
  1034. exclusive_maximum=True,
  1035. )
  1036. self.assertDictEqual(
  1037. item.serialize(),
  1038. {
  1039. "type": "integer",
  1040. "title": item.title,
  1041. "description": item.description,
  1042. "minimum": item.minimum,
  1043. "maximum": item.maximum,
  1044. "exclusiveMinimum": True,
  1045. "exclusiveMaximum": True,
  1046. },
  1047. )
  1048. item = schema.IntegerItem(
  1049. title="How many dogs",
  1050. description="Question",
  1051. minimum=0,
  1052. maximum=10,
  1053. default=0,
  1054. )
  1055. self.assertDictEqual(
  1056. item.serialize(),
  1057. {
  1058. "type": "integer",
  1059. "title": item.title,
  1060. "description": item.description,
  1061. "minimum": item.minimum,
  1062. "maximum": item.maximum,
  1063. "default": 0,
  1064. },
  1065. )
  1066. item = schema.IntegerItem(
  1067. title="How many dogs",
  1068. description="Question",
  1069. minimum=0,
  1070. maximum=10,
  1071. default=0,
  1072. enum=(0, 2, 4, 6),
  1073. )
  1074. self.assertDictEqual(
  1075. item.serialize(),
  1076. {
  1077. "type": "integer",
  1078. "title": item.title,
  1079. "description": item.description,
  1080. "minimum": item.minimum,
  1081. "maximum": item.maximum,
  1082. "default": 0,
  1083. "enum": [0, 2, 4, 6],
  1084. },
  1085. )
  1086. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  1087. def test_integer_config_validation(self):
  1088. class TestConf(schema.Schema):
  1089. item = schema.IntegerItem(title="How many dogs", description="Question")
  1090. try:
  1091. jsonschema.validate({"item": 2}, TestConf.serialize())
  1092. except jsonschema.exceptions.ValidationError as exc:
  1093. self.fail("ValidationError raised: {0}".format(exc))
  1094. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1095. jsonschema.validate({"item": 3.1}, TestConf.serialize())
  1096. self.assertIn("is not of type", excinfo.exception.message)
  1097. class TestConf(schema.Schema):
  1098. item = schema.IntegerItem(
  1099. title="How many dogs", description="Question", multiple_of=2
  1100. )
  1101. try:
  1102. jsonschema.validate({"item": 4}, TestConf.serialize())
  1103. except jsonschema.exceptions.ValidationError as exc:
  1104. self.fail("ValidationError raised: {0}".format(exc))
  1105. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1106. jsonschema.validate({"item": 3}, TestConf.serialize())
  1107. self.assertIn("is not a multiple of", excinfo.exception.message)
  1108. class TestConf(schema.Schema):
  1109. item = schema.IntegerItem(
  1110. title="Foo", description="Foo Item", minimum=1, maximum=10
  1111. )
  1112. try:
  1113. jsonschema.validate({"item": 3}, TestConf.serialize())
  1114. except jsonschema.exceptions.ValidationError as exc:
  1115. self.fail("ValidationError raised: {0}".format(exc))
  1116. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1117. jsonschema.validate({"item": 11}, TestConf.serialize())
  1118. self.assertIn("is greater than the maximum of", excinfo.exception.message)
  1119. class TestConf(schema.Schema):
  1120. item = schema.IntegerItem(
  1121. title="Foo", description="Foo Item", minimum=10, maximum=100
  1122. )
  1123. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1124. jsonschema.validate({"item": 3}, TestConf.serialize())
  1125. self.assertIn("is less than the minimum of", excinfo.exception.message)
  1126. class TestConf(schema.Schema):
  1127. item = schema.IntegerItem(
  1128. title="How many dogs",
  1129. description="Question",
  1130. minimum=0,
  1131. exclusive_minimum=True,
  1132. maximum=10,
  1133. exclusive_maximum=True,
  1134. )
  1135. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1136. jsonschema.validate({"item": 0}, TestConf.serialize())
  1137. self.assertIn(
  1138. "is less than or equal to the minimum of", excinfo.exception.message
  1139. )
  1140. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1141. jsonschema.validate({"item": 10}, TestConf.serialize())
  1142. self.assertIn(
  1143. "is greater than or equal to the maximum of", excinfo.exception.message
  1144. )
  1145. class TestConf(schema.Schema):
  1146. item = schema.IntegerItem(
  1147. title="Foo", description="Foo Item", enum=(0, 2, 4, 6)
  1148. )
  1149. try:
  1150. jsonschema.validate({"item": 4}, TestConf.serialize())
  1151. except jsonschema.exceptions.ValidationError as exc:
  1152. self.fail("ValidationError raised: {0}".format(exc))
  1153. class TestConf(schema.Schema):
  1154. item = schema.IntegerItem(
  1155. title="Foo", description="Foo Item", enum=(0, 2, 4, 6)
  1156. )
  1157. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1158. jsonschema.validate({"item": 3}, TestConf.serialize())
  1159. self.assertIn("is not one of", excinfo.exception.message)
  1160. def test_array_config(self):
  1161. string_item = schema.StringItem(title="Dog Name", description="The dog name")
  1162. item = schema.ArrayItem(
  1163. title="Dog Names", description="Name your dogs", items=string_item
  1164. )
  1165. self.assertDictEqual(
  1166. item.serialize(),
  1167. {
  1168. "type": "array",
  1169. "title": item.title,
  1170. "description": item.description,
  1171. "items": {
  1172. "type": "string",
  1173. "title": string_item.title,
  1174. "description": string_item.description,
  1175. },
  1176. },
  1177. )
  1178. integer_item = schema.IntegerItem(title="Dog Age", description="The dog age")
  1179. item = schema.ArrayItem(
  1180. title="Dog Names",
  1181. description="Name your dogs",
  1182. items=(string_item, integer_item),
  1183. )
  1184. self.assertDictEqual(
  1185. item.serialize(),
  1186. {
  1187. "type": "array",
  1188. "title": item.title,
  1189. "description": item.description,
  1190. "items": [
  1191. {
  1192. "type": "string",
  1193. "title": string_item.title,
  1194. "description": string_item.description,
  1195. },
  1196. {
  1197. "type": "integer",
  1198. "title": integer_item.title,
  1199. "description": integer_item.description,
  1200. },
  1201. ],
  1202. },
  1203. )
  1204. item = schema.ArrayItem(
  1205. title="Dog Names",
  1206. description="Name your dogs",
  1207. items=(schema.StringItem(), schema.IntegerItem()),
  1208. min_items=1,
  1209. max_items=3,
  1210. additional_items=False,
  1211. unique_items=True,
  1212. )
  1213. self.assertDictEqual(
  1214. item.serialize(),
  1215. {
  1216. "type": "array",
  1217. "title": item.title,
  1218. "description": item.description,
  1219. "minItems": item.min_items,
  1220. "maxItems": item.max_items,
  1221. "uniqueItems": item.unique_items,
  1222. "additionalItems": item.additional_items,
  1223. "items": [{"type": "string"}, {"type": "integer"}],
  1224. },
  1225. )
  1226. class HowManyConfig(schema.Schema):
  1227. item = schema.IntegerItem(title="How many dogs", description="Question")
  1228. item = schema.ArrayItem(
  1229. title="Dog Names", description="Name your dogs", items=HowManyConfig()
  1230. )
  1231. self.assertDictEqual(
  1232. item.serialize(),
  1233. {
  1234. "type": "array",
  1235. "title": item.title,
  1236. "description": item.description,
  1237. "items": HowManyConfig.serialize(),
  1238. },
  1239. )
  1240. class AgesConfig(schema.Schema):
  1241. item = schema.IntegerItem()
  1242. item = schema.ArrayItem(
  1243. title="Dog Names",
  1244. description="Name your dogs",
  1245. items=(HowManyConfig(), AgesConfig()),
  1246. )
  1247. self.assertDictEqual(
  1248. item.serialize(),
  1249. {
  1250. "type": "array",
  1251. "title": item.title,
  1252. "description": item.description,
  1253. "items": [HowManyConfig.serialize(), AgesConfig.serialize()],
  1254. },
  1255. )
  1256. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  1257. def test_array_config_validation(self):
  1258. class TestConf(schema.Schema):
  1259. item = schema.ArrayItem(
  1260. title="Dog Names",
  1261. description="Name your dogs",
  1262. items=schema.StringItem(),
  1263. )
  1264. try:
  1265. jsonschema.validate(
  1266. {"item": ["Tobias", "Óscar"]},
  1267. TestConf.serialize(),
  1268. format_checker=jsonschema.FormatChecker(),
  1269. )
  1270. except jsonschema.exceptions.ValidationError as exc:
  1271. self.fail("ValidationError raised: {0}".format(exc))
  1272. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1273. jsonschema.validate(
  1274. {"item": ["Tobias", "Óscar", 3]},
  1275. TestConf.serialize(),
  1276. format_checker=jsonschema.FormatChecker(),
  1277. )
  1278. self.assertIn("is not of type", excinfo.exception.message)
  1279. class TestConf(schema.Schema):
  1280. item = schema.ArrayItem(
  1281. title="Dog Names",
  1282. description="Name your dogs",
  1283. items=schema.StringItem(),
  1284. min_items=1,
  1285. max_items=2,
  1286. )
  1287. try:
  1288. jsonschema.validate(
  1289. {"item": ["Tobias", "Óscar"]},
  1290. TestConf.serialize(),
  1291. format_checker=jsonschema.FormatChecker(),
  1292. )
  1293. except jsonschema.exceptions.ValidationError as exc:
  1294. self.fail("ValidationError raised: {0}".format(exc))
  1295. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1296. jsonschema.validate(
  1297. {"item": ["Tobias", "Óscar", "Pepe"]},
  1298. TestConf.serialize(),
  1299. format_checker=jsonschema.FormatChecker(),
  1300. )
  1301. self.assertIn("is too long", excinfo.exception.message)
  1302. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1303. jsonschema.validate(
  1304. {"item": []},
  1305. TestConf.serialize(),
  1306. format_checker=jsonschema.FormatChecker(),
  1307. )
  1308. self.assertIn("is too short", excinfo.exception.message)
  1309. class TestConf(schema.Schema):
  1310. item = schema.ArrayItem(
  1311. title="Dog Names",
  1312. description="Name your dogs",
  1313. items=schema.StringItem(),
  1314. uniqueItems=True,
  1315. )
  1316. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1317. jsonschema.validate(
  1318. {"item": ["Tobias", "Tobias"]},
  1319. TestConf.serialize(),
  1320. format_checker=jsonschema.FormatChecker(),
  1321. )
  1322. self.assertIn("has non-unique elements", excinfo.exception.message)
  1323. class TestConf(schema.Schema):
  1324. item = schema.ArrayItem(items=(schema.StringItem(), schema.IntegerItem()))
  1325. try:
  1326. jsonschema.validate(
  1327. {"item": ["Óscar", 4]},
  1328. TestConf.serialize(),
  1329. format_checker=jsonschema.FormatChecker(),
  1330. )
  1331. except jsonschema.exceptions.ValidationError as exc:
  1332. self.fail("ValidationError raised: {0}".format(exc))
  1333. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1334. jsonschema.validate(
  1335. {"item": ["Tobias", "Óscar"]},
  1336. TestConf.serialize(),
  1337. format_checker=jsonschema.FormatChecker(),
  1338. )
  1339. self.assertIn("is not of type", excinfo.exception.message)
  1340. class TestConf(schema.Schema):
  1341. item = schema.ArrayItem(
  1342. items=schema.ArrayItem(
  1343. items=(schema.StringItem(), schema.IntegerItem())
  1344. )
  1345. )
  1346. try:
  1347. jsonschema.validate(
  1348. {"item": [["Tobias", 8], ["Óscar", 4]]},
  1349. TestConf.serialize(),
  1350. format_checker=jsonschema.FormatChecker(),
  1351. )
  1352. except jsonschema.exceptions.ValidationError as exc:
  1353. self.fail("ValidationError raised: {0}".format(exc))
  1354. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1355. jsonschema.validate(
  1356. {"item": [["Tobias", 8], ["Óscar", "4"]]},
  1357. TestConf.serialize(),
  1358. format_checker=jsonschema.FormatChecker(),
  1359. )
  1360. self.assertIn("is not of type", excinfo.exception.message)
  1361. class TestConf(schema.Schema):
  1362. item = schema.ArrayItem(items=schema.StringItem(enum=["Tobias", "Óscar"]))
  1363. try:
  1364. jsonschema.validate(
  1365. {"item": ["Óscar"]},
  1366. TestConf.serialize(),
  1367. format_checker=jsonschema.FormatChecker(),
  1368. )
  1369. except jsonschema.exceptions.ValidationError as exc:
  1370. self.fail("ValidationError raised: {0}".format(exc))
  1371. try:
  1372. jsonschema.validate(
  1373. {"item": ["Tobias"]},
  1374. TestConf.serialize(),
  1375. format_checker=jsonschema.FormatChecker(),
  1376. )
  1377. except jsonschema.exceptions.ValidationError as exc:
  1378. self.fail("ValidationError raised: {0}".format(exc))
  1379. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1380. jsonschema.validate(
  1381. {"item": ["Pepe"]},
  1382. TestConf.serialize(),
  1383. format_checker=jsonschema.FormatChecker(),
  1384. )
  1385. self.assertIn("is not one of", excinfo.exception.message)
  1386. def test_dict_config(self):
  1387. item = schema.DictItem(
  1388. title="Poligon",
  1389. description="Describe the Poligon",
  1390. properties={"sides": schema.IntegerItem()},
  1391. )
  1392. self.assertDictEqual(
  1393. item.serialize(),
  1394. {
  1395. "type": "object",
  1396. "title": item.title,
  1397. "description": item.description,
  1398. "properties": {"sides": {"type": "integer"}},
  1399. },
  1400. )
  1401. item = schema.DictItem(
  1402. title="Poligon",
  1403. description="Describe the Poligon",
  1404. properties={"sides": schema.IntegerItem()},
  1405. min_properties=1,
  1406. max_properties=2,
  1407. )
  1408. self.assertDictEqual(
  1409. item.serialize(),
  1410. {
  1411. "type": "object",
  1412. "title": item.title,
  1413. "description": item.description,
  1414. "properties": {"sides": {"type": "integer"}},
  1415. "minProperties": 1,
  1416. "maxProperties": 2,
  1417. },
  1418. )
  1419. item = schema.DictItem(
  1420. title="Poligon",
  1421. description="Describe the Poligon",
  1422. pattern_properties={"s.*": schema.IntegerItem()},
  1423. min_properties=1,
  1424. max_properties=2,
  1425. )
  1426. self.assertDictEqual(
  1427. item.serialize(),
  1428. {
  1429. "type": "object",
  1430. "title": item.title,
  1431. "description": item.description,
  1432. "patternProperties": {"s.*": {"type": "integer"}},
  1433. "minProperties": 1,
  1434. "maxProperties": 2,
  1435. },
  1436. )
  1437. item = schema.DictItem(
  1438. title="Poligon",
  1439. description="Describe the Poligon",
  1440. properties={"color": schema.StringItem(enum=["red", "green", "blue"])},
  1441. pattern_properties={"s*": schema.IntegerItem()},
  1442. min_properties=1,
  1443. max_properties=2,
  1444. )
  1445. self.assertDictEqual(
  1446. item.serialize(),
  1447. {
  1448. "type": "object",
  1449. "title": item.title,
  1450. "description": item.description,
  1451. "properties": {
  1452. "color": {"type": "string", "enum": ["red", "green", "blue"]}
  1453. },
  1454. "patternProperties": {"s*": {"type": "integer"}},
  1455. "minProperties": 1,
  1456. "maxProperties": 2,
  1457. },
  1458. )
  1459. item = schema.DictItem(
  1460. title="Poligon",
  1461. description="Describe the Poligon",
  1462. properties={"color": schema.StringItem(enum=["red", "green", "blue"])},
  1463. pattern_properties={"s*": schema.IntegerItem()},
  1464. additional_properties=True,
  1465. min_properties=1,
  1466. max_properties=2,
  1467. )
  1468. self.assertDictEqual(
  1469. item.serialize(),
  1470. {
  1471. "type": "object",
  1472. "title": item.title,
  1473. "description": item.description,
  1474. "properties": {
  1475. "color": {"type": "string", "enum": ["red", "green", "blue"]}
  1476. },
  1477. "patternProperties": {"s*": {"type": "integer"}},
  1478. "minProperties": 1,
  1479. "maxProperties": 2,
  1480. "additionalProperties": True,
  1481. },
  1482. )
  1483. item = schema.DictItem(
  1484. title="Poligon",
  1485. description="Describe the Poligon",
  1486. properties={"sides": schema.IntegerItem()},
  1487. additional_properties=schema.OneOfItem(
  1488. items=[schema.BooleanItem(), schema.StringItem()]
  1489. ),
  1490. )
  1491. self.assertDictEqual(
  1492. item.serialize(),
  1493. {
  1494. "type": "object",
  1495. "title": item.title,
  1496. "description": item.description,
  1497. "properties": {"sides": {"type": "integer"}},
  1498. "additionalProperties": {
  1499. "oneOf": [{"type": "boolean"}, {"type": "string"}]
  1500. },
  1501. },
  1502. )
  1503. class TestConf(schema.Schema):
  1504. item = schema.DictItem(
  1505. title="Poligon",
  1506. description="Describe the Poligon",
  1507. properties={"sides": schema.IntegerItem(required=True)},
  1508. additional_properties=schema.OneOfItem(
  1509. items=[schema.BooleanItem(), schema.StringItem()]
  1510. ),
  1511. )
  1512. self.assertDictContainsSubset(
  1513. TestConf.serialize(),
  1514. {
  1515. "$schema": "http://json-schema.org/draft-04/schema#",
  1516. "type": "object",
  1517. "properties": {
  1518. "item": {
  1519. "title": "Poligon",
  1520. "description": "Describe the Poligon",
  1521. "type": "object",
  1522. "properties": {"sides": {"type": "integer"}},
  1523. "additionalProperties": {
  1524. "oneOf": [{"type": "boolean"}, {"type": "string"}]
  1525. },
  1526. "required": ["sides"],
  1527. }
  1528. },
  1529. "x-ordering": ["item"],
  1530. "additionalProperties": False,
  1531. },
  1532. )
  1533. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  1534. def test_dict_config_validation(self):
  1535. class TestConf(schema.Schema):
  1536. item = schema.DictItem(
  1537. title="Poligon",
  1538. description="Describe the Poligon",
  1539. properties={"sides": schema.IntegerItem()},
  1540. )
  1541. try:
  1542. jsonschema.validate({"item": {"sides": 1}}, TestConf.serialize())
  1543. except jsonschema.exceptions.ValidationError as exc:
  1544. self.fail("ValidationError raised: {0}".format(exc))
  1545. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1546. jsonschema.validate({"item": {"sides": "1"}}, TestConf.serialize())
  1547. self.assertIn("is not of type", excinfo.exception.message)
  1548. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1549. jsonschema.validate({"item": 2}, TestConf.serialize())
  1550. self.assertIn("is not of type", excinfo.exception.message)
  1551. class TestConf(schema.Schema):
  1552. item = schema.DictItem(
  1553. title="Poligon",
  1554. description="Describe the Poligon",
  1555. properties={"color": schema.StringItem(enum=["red", "green", "blue"])},
  1556. pattern_properties={"si.*": schema.IntegerItem()},
  1557. )
  1558. try:
  1559. jsonschema.validate(
  1560. {"item": {"sides": 1, "color": "red"}}, TestConf.serialize()
  1561. )
  1562. except jsonschema.exceptions.ValidationError as exc:
  1563. self.fail("ValidationError raised: {0}".format(exc))
  1564. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1565. jsonschema.validate(
  1566. {"item": {"sides": "4", "color": "blue"}}, TestConf.serialize()
  1567. )
  1568. self.assertIn("is not of type", excinfo.exception.message)
  1569. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1570. jsonschema.validate({"item": 2}, TestConf.serialize())
  1571. self.assertIn("is not of type", excinfo.exception.message)
  1572. class TestConf(schema.Schema):
  1573. item = schema.DictItem(
  1574. title="Poligon",
  1575. description="Describe the Poligon",
  1576. properties={"color": schema.StringItem(enum=["red", "green", "blue"])},
  1577. pattern_properties={"si.*": schema.IntegerItem()},
  1578. additional_properties=False,
  1579. )
  1580. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1581. jsonschema.validate(
  1582. {"item": {"color": "green", "sides": 4, "surfaces": 4}},
  1583. TestConf.serialize(),
  1584. )
  1585. if JSONSCHEMA_VERSION < _LooseVersion("2.6.0"):
  1586. self.assertIn(
  1587. "Additional properties are not allowed", excinfo.exception.message
  1588. )
  1589. else:
  1590. self.assertIn(
  1591. "'surfaces' does not match any of the regexes",
  1592. excinfo.exception.message,
  1593. )
  1594. class TestConf(schema.Schema):
  1595. item = schema.DictItem(
  1596. title="Poligon",
  1597. description="Describe the Poligon",
  1598. properties={"color": schema.StringItem(enum=["red", "green", "blue"])},
  1599. additional_properties=schema.OneOfItem(
  1600. items=[schema.BooleanItem(), schema.IntegerItem()]
  1601. ),
  1602. )
  1603. try:
  1604. jsonschema.validate(
  1605. {"item": {"sides": 1, "color": "red", "rugged_surface": False}},
  1606. TestConf.serialize(),
  1607. )
  1608. except jsonschema.exceptions.ValidationError as exc:
  1609. self.fail("ValidationError raised: {0}".format(exc))
  1610. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1611. jsonschema.validate(
  1612. {"item": {"sides": "4", "color": "blue"}}, TestConf.serialize()
  1613. )
  1614. if JSONSCHEMA_VERSION >= _LooseVersion("3.0.0"):
  1615. self.assertIn("'4'", excinfo.exception.message)
  1616. self.assertIn("is not of type", excinfo.exception.message)
  1617. self.assertIn("'boolean'", excinfo.exception.message)
  1618. else:
  1619. self.assertIn(
  1620. "is not valid under any of the given schemas", excinfo.exception.message
  1621. )
  1622. class TestConf(schema.Schema):
  1623. item = schema.DictItem(
  1624. title="Poligon",
  1625. description="Describe the Poligon",
  1626. properties={"color": schema.StringItem(enum=["red", "green", "blue"])},
  1627. additional_properties=schema.OneOfItem(
  1628. items=[schema.BooleanItem(), schema.IntegerItem()]
  1629. ),
  1630. min_properties=2,
  1631. max_properties=3,
  1632. )
  1633. try:
  1634. jsonschema.validate(
  1635. {"item": {"color": "red", "sides": 1}}, TestConf.serialize()
  1636. )
  1637. except jsonschema.exceptions.ValidationError as exc:
  1638. self.fail("ValidationError raised: {0}".format(exc))
  1639. try:
  1640. jsonschema.validate(
  1641. {"item": {"sides": 1, "color": "red", "rugged_surface": False}},
  1642. TestConf.serialize(),
  1643. )
  1644. except jsonschema.exceptions.ValidationError as exc:
  1645. self.fail("ValidationError raised: {0}".format(exc))
  1646. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1647. jsonschema.validate({"item": {"color": "blue"}}, TestConf.serialize())
  1648. self.assertIn("does not have enough properties", excinfo.exception.message)
  1649. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1650. jsonschema.validate(
  1651. {
  1652. "item": {
  1653. "sides": 4,
  1654. "color": "blue",
  1655. "rugged_surface": False,
  1656. "opaque": True,
  1657. }
  1658. },
  1659. TestConf.serialize(),
  1660. )
  1661. self.assertIn("has too many properties", excinfo.exception.message)
  1662. class TestConf(schema.Schema):
  1663. item = schema.DictItem(
  1664. title="Poligon",
  1665. description="Describe the Poligon",
  1666. properties={"sides": schema.IntegerItem(required=True)},
  1667. additional_properties=schema.OneOfItem(
  1668. items=[schema.BooleanItem(), schema.StringItem()]
  1669. ),
  1670. )
  1671. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1672. jsonschema.validate(
  1673. {"item": {"color": "blue", "rugged_surface": False, "opaque": True}},
  1674. TestConf.serialize(),
  1675. )
  1676. self.assertIn("'sides' is a required property", excinfo.exception.message)
  1677. class Props(schema.Schema):
  1678. sides = schema.IntegerItem(required=True)
  1679. class TestConf(schema.Schema):
  1680. item = schema.DictItem(
  1681. title="Poligon",
  1682. description="Describe the Poligon",
  1683. properties=Props(),
  1684. additional_properties=schema.OneOfItem(
  1685. items=[schema.BooleanItem(), schema.StringItem()]
  1686. ),
  1687. )
  1688. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1689. jsonschema.validate(
  1690. {"item": {"color": "blue", "rugged_surface": False, "opaque": True}},
  1691. TestConf.serialize(),
  1692. )
  1693. self.assertIn("'sides' is a required property", excinfo.exception.message)
  1694. def test_oneof_config(self):
  1695. item = schema.OneOfItem(
  1696. items=(
  1697. schema.StringItem(title="Yes", enum=["yes"]),
  1698. schema.StringItem(title="No", enum=["no"]),
  1699. )
  1700. )
  1701. self.assertEqual(
  1702. item.serialize(), {"oneOf": [i.serialize() for i in item.items]}
  1703. )
  1704. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  1705. def test_oneof_config_validation(self):
  1706. class TestConf(schema.Schema):
  1707. item = schema.ArrayItem(
  1708. title="Hungry",
  1709. description="Are you hungry?",
  1710. items=schema.OneOfItem(
  1711. items=(
  1712. schema.StringItem(title="Yes", enum=["yes"]),
  1713. schema.StringItem(title="No", enum=["no"]),
  1714. )
  1715. ),
  1716. )
  1717. try:
  1718. jsonschema.validate({"item": ["no"]}, TestConf.serialize())
  1719. except jsonschema.exceptions.ValidationError as exc:
  1720. self.fail("ValidationError raised: {0}".format(exc))
  1721. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1722. jsonschema.validate({"item": ["maybe"]}, TestConf.serialize())
  1723. if JSONSCHEMA_VERSION >= _LooseVersion("3.0.0"):
  1724. self.assertIn("'maybe'", excinfo.exception.message)
  1725. self.assertIn("is not one of", excinfo.exception.message)
  1726. self.assertIn("'yes'", excinfo.exception.message)
  1727. else:
  1728. self.assertIn(
  1729. "is not valid under any of the given schemas", excinfo.exception.message
  1730. )
  1731. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1732. jsonschema.validate({"item": 2}, TestConf.serialize())
  1733. self.assertIn("is not of type", excinfo.exception.message)
  1734. def test_anyof_config(self):
  1735. item = schema.AnyOfItem(
  1736. items=(
  1737. schema.StringItem(title="Yes", enum=["yes"]),
  1738. schema.StringItem(title="No", enum=["no"]),
  1739. )
  1740. )
  1741. self.assertEqual(
  1742. item.serialize(),
  1743. {"anyOf": [i.serialize() for i in item.items]}, # pylint: disable=E1133
  1744. )
  1745. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  1746. def test_anyof_config_validation(self):
  1747. class TestConf(schema.Schema):
  1748. item = schema.ArrayItem(
  1749. title="Hungry",
  1750. description="Are you hungry?",
  1751. items=schema.AnyOfItem(
  1752. items=(
  1753. schema.StringItem(title="Yes", enum=["yes"]),
  1754. schema.StringItem(title="No", enum=["no"]),
  1755. schema.BooleanItem(),
  1756. )
  1757. ),
  1758. )
  1759. try:
  1760. jsonschema.validate({"item": ["no"]}, TestConf.serialize())
  1761. except jsonschema.exceptions.ValidationError as exc:
  1762. self.fail("ValidationError raised: {0}".format(exc))
  1763. try:
  1764. jsonschema.validate({"item": ["yes"]}, TestConf.serialize())
  1765. except jsonschema.exceptions.ValidationError as exc:
  1766. self.fail("ValidationError raised: {0}".format(exc))
  1767. try:
  1768. jsonschema.validate({"item": [True]}, TestConf.serialize())
  1769. except jsonschema.exceptions.ValidationError as exc:
  1770. self.fail("ValidationError raised: {0}".format(exc))
  1771. try:
  1772. jsonschema.validate({"item": [False]}, TestConf.serialize())
  1773. except jsonschema.exceptions.ValidationError as exc:
  1774. self.fail("ValidationError raised: {0}".format(exc))
  1775. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1776. jsonschema.validate({"item": ["maybe"]}, TestConf.serialize())
  1777. if JSONSCHEMA_VERSION >= _LooseVersion("3.0.0"):
  1778. self.assertIn("'maybe'", excinfo.exception.message)
  1779. self.assertIn("is not one of", excinfo.exception.message)
  1780. self.assertIn("'yes'", excinfo.exception.message)
  1781. else:
  1782. self.assertIn(
  1783. "is not valid under any of the given schemas", excinfo.exception.message
  1784. )
  1785. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1786. jsonschema.validate({"item": 2}, TestConf.serialize())
  1787. self.assertIn("is not of type", excinfo.exception.message)
  1788. def test_allof_config(self):
  1789. item = schema.AllOfItem(
  1790. items=(schema.StringItem(min_length=2), schema.StringItem(max_length=3))
  1791. )
  1792. self.assertEqual(
  1793. item.serialize(),
  1794. {"allOf": [i.serialize() for i in item.items]}, # pylint: disable=E1133
  1795. )
  1796. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  1797. def test_allof_config_validation(self):
  1798. class TestConf(schema.Schema):
  1799. item = schema.ArrayItem(
  1800. title="Hungry",
  1801. description="Are you hungry?",
  1802. items=schema.AllOfItem(
  1803. items=(
  1804. schema.StringItem(min_length=2),
  1805. schema.StringItem(max_length=3),
  1806. )
  1807. ),
  1808. )
  1809. try:
  1810. jsonschema.validate({"item": ["no"]}, TestConf.serialize())
  1811. except jsonschema.exceptions.ValidationError as exc:
  1812. self.fail("ValidationError raised: {0}".format(exc))
  1813. try:
  1814. jsonschema.validate({"item": ["yes"]}, TestConf.serialize())
  1815. except jsonschema.exceptions.ValidationError as exc:
  1816. self.fail("ValidationError raised: {0}".format(exc))
  1817. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1818. jsonschema.validate({"item": ["maybe"]}, TestConf.serialize())
  1819. self.assertIn("is too long", excinfo.exception.message)
  1820. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1821. jsonschema.validate({"item": ["hmmmm"]}, TestConf.serialize())
  1822. self.assertIn("is too long", excinfo.exception.message)
  1823. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1824. jsonschema.validate({"item": 2}, TestConf.serialize())
  1825. self.assertIn("is not of type", excinfo.exception.message)
  1826. def test_not_config(self):
  1827. item = schema.NotItem(item=schema.BooleanItem())
  1828. self.assertEqual(item.serialize(), {"not": item.item.serialize()})
  1829. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  1830. def test_not_config_validation(self):
  1831. class TestConf(schema.Schema):
  1832. item = schema.ArrayItem(
  1833. title="Hungry",
  1834. description="Are you hungry?",
  1835. items=schema.NotItem(item=schema.BooleanItem()),
  1836. )
  1837. try:
  1838. jsonschema.validate({"item": ["no"]}, TestConf.serialize())
  1839. except jsonschema.exceptions.ValidationError as exc:
  1840. self.fail("ValidationError raised: {0}".format(exc))
  1841. try:
  1842. jsonschema.validate({"item": ["yes"]}, TestConf.serialize())
  1843. except jsonschema.exceptions.ValidationError as exc:
  1844. self.fail("ValidationError raised: {0}".format(exc))
  1845. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1846. jsonschema.validate({"item": [True]}, TestConf.serialize())
  1847. self.assertIn("is not allowed for", excinfo.exception.message)
  1848. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  1849. jsonschema.validate({"item": [False]}, TestConf.serialize())
  1850. self.assertIn("is not allowed for", excinfo.exception.message)
  1851. def test_item_name_override_class_attrname(self):
  1852. class TestConf(schema.Schema):
  1853. item = schema.BooleanItem(
  1854. name="hungry", title="Hungry", description="Are you hungry?"
  1855. )
  1856. expected = {
  1857. "$schema": "http://json-schema.org/draft-04/schema#",
  1858. "type": "object",
  1859. "properties": {
  1860. "hungry": {
  1861. "type": "boolean",
  1862. "description": "Are you hungry?",
  1863. "title": "Hungry",
  1864. }
  1865. },
  1866. "x-ordering": ["hungry"],
  1867. "additionalProperties": False,
  1868. }
  1869. self.assertDictEqual(TestConf.serialize(), expected)
  1870. def test_config_name_override_class_attrname(self):
  1871. class TestConf(schema.Schema):
  1872. item = schema.BooleanItem(title="Hungry", description="Are you hungry?")
  1873. class TestConf2(schema.Schema):
  1874. a_name = TestConf(name="another_name")
  1875. expected = {
  1876. "$schema": "http://json-schema.org/draft-04/schema#",
  1877. "type": "object",
  1878. "properties": {
  1879. "another_name": {
  1880. "id": "https://non-existing.saltstack.com/schemas/another_name.json#",
  1881. "type": "object",
  1882. "properties": {
  1883. "item": {
  1884. "type": "boolean",
  1885. "description": "Are you hungry?",
  1886. "title": "Hungry",
  1887. }
  1888. },
  1889. "x-ordering": ["item"],
  1890. "additionalProperties": False,
  1891. }
  1892. },
  1893. "x-ordering": ["another_name"],
  1894. "additionalProperties": False,
  1895. }
  1896. self.assertDictEqual(TestConf2.serialize(), expected)
  1897. class ComplexSchemaItem(schema.ComplexSchemaItem):
  1898. _complex_attributes = ["thirsty"]
  1899. thirsty = schema.BooleanItem(title="Thirsty", description="Are you thirsty?")
  1900. class ComplexComplexSchemaItem(schema.ComplexSchemaItem):
  1901. _complex_attributes = ["hungry", "complex_item"]
  1902. hungry = schema.BooleanItem(
  1903. title="Hungry", description="Are you hungry?", required=True
  1904. )
  1905. complex_item = ComplexSchemaItem(definition_name="test_definition")
  1906. class TestComplexDefinitionsSchema(schema.DefinitionsSchema):
  1907. title = "Test Complex Definition Schema"
  1908. complex_item = ComplexSchemaItem()
  1909. class TestOneOfComplexDefinitionsSchema(schema.DefinitionsSchema):
  1910. title = "Test OneOf Complex Definitions Schema"
  1911. one_of_item = schema.OneOfItem(items=[ComplexSchemaItem(), schema.StringItem()])
  1912. class TestArrayComplexDefinitionsSchema(schema.DefinitionsSchema):
  1913. title = "Test Array Complex Definitions Schema"
  1914. array_item = schema.ArrayItem(items=ComplexSchemaItem())
  1915. class TestDictComplexDefinitionsSchema(schema.DefinitionsSchema):
  1916. title = "Test Dict Complex Definitions Schema"
  1917. dict_item = schema.DictItem(
  1918. properties={"complex_obj": ComplexSchemaItem(required=True)},
  1919. additional_properties=ComplexSchemaItem(),
  1920. )
  1921. class TestComplexComplexDefinitionsSchema(schema.DefinitionsSchema):
  1922. title = "Test Complex Complex Definition Schema"
  1923. complex_complex_item = ComplexComplexSchemaItem()
  1924. class ComplexSchemaTestCase(TestCase):
  1925. """ Test cases with definition schemas containing complex items"""
  1926. obj = ComplexSchemaItem()
  1927. complex_obj = ComplexComplexSchemaItem()
  1928. schema = TestComplexDefinitionsSchema()
  1929. one_of_schema = TestOneOfComplexDefinitionsSchema()
  1930. array_schema = TestArrayComplexDefinitionsSchema()
  1931. dict_schema = TestDictComplexDefinitionsSchema()
  1932. complex_schema = TestComplexComplexDefinitionsSchema()
  1933. def test_complex_schema_item_serialize(self):
  1934. obj = copy.deepcopy(self.obj)
  1935. expected_serialized = {"$ref": "#/definitions/ComplexSchemaItem"}
  1936. self.assertDictEqual(obj.serialize(), expected_serialized)
  1937. def test_complex_schema_item_definition(self):
  1938. obj = copy.deepcopy(self.obj)
  1939. expected_def = {
  1940. "type": "object",
  1941. "title": "ComplexSchemaItem",
  1942. "properties": {
  1943. "thirsty": {
  1944. "type": "boolean",
  1945. "title": "Thirsty",
  1946. "description": "Are you thirsty?",
  1947. }
  1948. },
  1949. }
  1950. self.assertDictEqual(obj.get_definition(), expected_def)
  1951. def test_complex_complex_schema_item_definition(self):
  1952. complex_obj = copy.deepcopy(self.complex_obj)
  1953. expected_def = {
  1954. "type": "object",
  1955. "title": "ComplexComplexSchemaItem",
  1956. "properties": {
  1957. "hungry": {
  1958. "type": "boolean",
  1959. "title": "Hungry",
  1960. "description": "Are you hungry?",
  1961. },
  1962. "complex_item": {
  1963. "type": "object",
  1964. "$ref": "#/definitions/test_definition",
  1965. },
  1966. },
  1967. "required": ["hungry"],
  1968. }
  1969. self.assertDictEqual(complex_obj.get_definition(), expected_def)
  1970. def test_complex_definition_schema(self):
  1971. serialized = salt.utils.yaml.safe_load(
  1972. salt.utils.json.dumps(self.schema.serialize())
  1973. )
  1974. expected = {
  1975. "$schema": "http://json-schema.org/draft-04/schema#",
  1976. "title": "Test Complex Definition Schema",
  1977. "type": "object",
  1978. "properties": {"complex_item": {"$ref": "#/definitions/ComplexSchemaItem"}},
  1979. "x-ordering": ["complex_item"],
  1980. "additionalProperties": False,
  1981. "definitions": {
  1982. "ComplexSchemaItem": {
  1983. "type": "object",
  1984. "title": "ComplexSchemaItem",
  1985. "properties": {
  1986. "thirsty": {
  1987. "type": "boolean",
  1988. "title": "Thirsty",
  1989. "description": "Are you thirsty?",
  1990. }
  1991. },
  1992. }
  1993. },
  1994. }
  1995. self.assertDictEqual(serialized, expected)
  1996. def test_one_of_complex_definition_schema(self):
  1997. serialized = salt.utils.yaml.safe_load(
  1998. salt.utils.json.dumps(self.one_of_schema.serialize())
  1999. )
  2000. expected = {
  2001. "$schema": "http://json-schema.org/draft-04/schema#",
  2002. "title": "Test OneOf Complex Definitions Schema",
  2003. "type": "object",
  2004. "properties": {
  2005. "one_of_item": {
  2006. "oneOf": [
  2007. {"$ref": "#/definitions/ComplexSchemaItem"},
  2008. {"type": "string"},
  2009. ]
  2010. }
  2011. },
  2012. "x-ordering": ["one_of_item"],
  2013. "additionalProperties": False,
  2014. "definitions": {
  2015. "ComplexSchemaItem": {
  2016. "type": "object",
  2017. "title": "ComplexSchemaItem",
  2018. "properties": {
  2019. "thirsty": {
  2020. "type": "boolean",
  2021. "title": "Thirsty",
  2022. "description": "Are you thirsty?",
  2023. }
  2024. },
  2025. }
  2026. },
  2027. }
  2028. self.assertDictEqual(serialized, expected)
  2029. def test_array_complex_definition_schema(self):
  2030. serialized = salt.utils.yaml.safe_load(
  2031. salt.utils.json.dumps(self.array_schema.serialize())
  2032. )
  2033. expected = {
  2034. "$schema": "http://json-schema.org/draft-04/schema#",
  2035. "title": "Test Array Complex Definitions Schema",
  2036. "type": "object",
  2037. "properties": {
  2038. "array_item": {
  2039. "type": "array",
  2040. "title": "array_item",
  2041. "items": {"$ref": "#/definitions/ComplexSchemaItem"},
  2042. }
  2043. },
  2044. "x-ordering": ["array_item"],
  2045. "additionalProperties": False,
  2046. "definitions": {
  2047. "ComplexSchemaItem": {
  2048. "type": "object",
  2049. "title": "ComplexSchemaItem",
  2050. "properties": {
  2051. "thirsty": {
  2052. "type": "boolean",
  2053. "title": "Thirsty",
  2054. "description": "Are you thirsty?",
  2055. }
  2056. },
  2057. }
  2058. },
  2059. }
  2060. self.assertDictEqual(serialized, expected)
  2061. def test_dict_complex_definition_schema(self):
  2062. serialized = salt.utils.yaml.safe_load(
  2063. salt.utils.json.dumps(self.dict_schema.serialize())
  2064. )
  2065. expected = {
  2066. "$schema": "http://json-schema.org/draft-04/schema#",
  2067. "title": "Test Dict Complex Definitions Schema",
  2068. "type": "object",
  2069. "properties": {
  2070. "dict_item": {
  2071. "type": "object",
  2072. "title": "dict_item",
  2073. "required": ["complex_obj"],
  2074. "properties": {
  2075. "complex_obj": {"$ref": "#/definitions/ComplexSchemaItem"}
  2076. },
  2077. "additionalProperties": {"$ref": "#/definitions/ComplexSchemaItem"},
  2078. }
  2079. },
  2080. "x-ordering": ["dict_item"],
  2081. "additionalProperties": False,
  2082. "definitions": {
  2083. "ComplexSchemaItem": {
  2084. "type": "object",
  2085. "title": "ComplexSchemaItem",
  2086. "properties": {
  2087. "thirsty": {
  2088. "type": "boolean",
  2089. "title": "Thirsty",
  2090. "description": "Are you thirsty?",
  2091. }
  2092. },
  2093. }
  2094. },
  2095. }
  2096. self.assertDictEqual(serialized, expected)
  2097. def test_complex_complex_definition_schema(self):
  2098. serialized = salt.utils.yaml.safe_load(
  2099. salt.utils.json.dumps(self.complex_schema.serialize())
  2100. )
  2101. expected = {
  2102. "$schema": "http://json-schema.org/draft-04/schema#",
  2103. "title": "Test Complex Complex Definition Schema",
  2104. "type": "object",
  2105. "properties": {
  2106. "complex_complex_item": {
  2107. "$ref": "#/definitions/ComplexComplexSchemaItem"
  2108. }
  2109. },
  2110. "x-ordering": ["complex_complex_item"],
  2111. "additionalProperties": False,
  2112. "definitions": {
  2113. "ComplexComplexSchemaItem": {
  2114. "type": "object",
  2115. "title": "ComplexComplexSchemaItem",
  2116. "properties": {
  2117. "hungry": {
  2118. "type": "boolean",
  2119. "title": "Hungry",
  2120. "description": "Are you hungry?",
  2121. },
  2122. "complex_item": {
  2123. "type": "object",
  2124. "$ref": "#/definitions/test_definition",
  2125. },
  2126. },
  2127. "required": ["hungry"],
  2128. },
  2129. "test_definition": {
  2130. "type": "object",
  2131. "title": "test_definition",
  2132. "properties": {
  2133. "thirsty": {
  2134. "type": "boolean",
  2135. "title": "Thirsty",
  2136. "description": "Are you thirsty?",
  2137. }
  2138. },
  2139. },
  2140. },
  2141. }
  2142. self.assertDictEqual(serialized, expected)
  2143. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  2144. def test_complex_schema_item_thirsty_valid(self):
  2145. serialized = self.schema.serialize()
  2146. try:
  2147. jsonschema.validate({"complex_item": {"thirsty": True}}, serialized)
  2148. except jsonschema.exceptions.ValidationError as exc:
  2149. self.fail("ValidationError raised: {0}".format(exc))
  2150. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  2151. def test_complex_schema_item_thirsty_invalid(self):
  2152. serialized = self.schema.serialize()
  2153. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  2154. jsonschema.validate({"complex_item": {"thirsty": "Foo"}}, serialized)
  2155. expected = (
  2156. "u'Foo' is not of type u'boolean'"
  2157. if six.PY2
  2158. else "'Foo' is not of type 'boolean'"
  2159. )
  2160. self.assertIn(expected, excinfo.exception.message)
  2161. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  2162. def test_complex_complex_schema_item_hungry_valid(self):
  2163. serialized = self.complex_schema.serialize()
  2164. try:
  2165. jsonschema.validate({"complex_complex_item": {"hungry": True}}, serialized)
  2166. except jsonschema.exceptions.ValidationError as exc:
  2167. self.fail("ValidationError raised: {0}".format(exc))
  2168. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  2169. def test_both_complex_complex_schema_all_items_valid(self):
  2170. serialized = self.complex_schema.serialize()
  2171. try:
  2172. jsonschema.validate(
  2173. {
  2174. "complex_complex_item": {
  2175. "hungry": True,
  2176. "complex_item": {"thirsty": True},
  2177. }
  2178. },
  2179. serialized,
  2180. )
  2181. except jsonschema.exceptions.ValidationError as exc:
  2182. self.fail("ValidationError raised: {0}".format(exc))
  2183. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  2184. def test_complex_complex_schema_item_hungry_invalid(self):
  2185. serialized = self.complex_schema.serialize()
  2186. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  2187. jsonschema.validate({"complex_complex_item": {"hungry": "Foo"}}, serialized)
  2188. expected = (
  2189. "u'Foo' is not of type u'boolean'"
  2190. if six.PY2
  2191. else "'Foo' is not of type 'boolean'"
  2192. )
  2193. self.assertIn(expected, excinfo.exception.message)
  2194. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  2195. def test_complex_complex_schema_item_inner_thirsty_invalid(self):
  2196. serialized = self.complex_schema.serialize()
  2197. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  2198. jsonschema.validate(
  2199. {
  2200. "complex_complex_item": {
  2201. "hungry": True,
  2202. "complex_item": {"thirsty": "Bar"},
  2203. }
  2204. },
  2205. serialized,
  2206. )
  2207. expected = (
  2208. "u'Bar' is not of type u'boolean'"
  2209. if six.PY2
  2210. else "'Bar' is not of type 'boolean'"
  2211. )
  2212. self.assertIn(expected, excinfo.exception.message)
  2213. @skipIf(HAS_JSONSCHEMA is False, "The 'jsonschema' library is missing")
  2214. def test_complex_complex_schema_item_missing_required_hungry(self):
  2215. serialized = self.complex_schema.serialize()
  2216. with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo:
  2217. jsonschema.validate(
  2218. {"complex_complex_item": {"complex_item": {"thirsty": True}}},
  2219. serialized,
  2220. )
  2221. self.assertIn("'hungry' is a required property", excinfo.exception.message)