From 5d14ccecae9b869b46698011134e3afab9e55d2f Mon Sep 17 00:00:00 2001 From: Jacob Tomlinson Date: Mon, 4 Dec 2023 10:32:55 +0000 Subject: [PATCH] Add support for validating objects with a to_dict method --- src/kubernetes_validate/utils.py | 9 +++++++-- tests/test_validate_resources.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/kubernetes_validate/utils.py b/src/kubernetes_validate/utils.py index 4da989d0..884484ab 100644 --- a/src/kubernetes_validate/utils.py +++ b/src/kubernetes_validate/utils.py @@ -6,7 +6,7 @@ import re import sys from distutils.version import LooseVersion -from typing import Any, Dict, Generator, List +from typing import Any, Dict, Generator, List, Union import jsonschema import pkg_resources @@ -58,7 +58,12 @@ def latest_version() -> str: return all_versions()[-1] -def validate(data: Dict[str, Any], desired_version: str, strict: bool = False) -> str: +def validate(data: Union[Dict[str, Any], object], desired_version: str, strict: bool = False) -> str: + if not isinstance(data, dict): + try: + data = data.to_dict() + except AttributeError: + raise TypeError("data must be a dict or object with a to_dict() method") # strip initial v from version (I keep forgetting, so other people will too) if desired_version.startswith('v'): desired_version = desired_version[1:] diff --git a/tests/test_validate_resources.py b/tests/test_validate_resources.py index 2ce56973..cfd95b63 100644 --- a/tests/test_validate_resources.py +++ b/tests/test_validate_resources.py @@ -43,3 +43,16 @@ def test_validate_version_too_new(): assert False except utils.VersionNotSupportedError: assert True + +def test_validate_object_resource(): + resources = utils.resources_from_file(os.path.join(parent, 'resource.yaml')) + + class ResourceObject(object): + def __init__(self, resource): + self.resource = resource + + def to_dict(self): + return self.resource + + for version in VERSIONS: + utils.validate(ResourceObject(resources[0]), version, strict=False)