Skip to content

Commit

Permalink
Merge pull request #23 from jacobtomlinson/support_objects_with_to_dict
Browse files Browse the repository at this point in the history
Add support for validating objects with a to_dict method
  • Loading branch information
willthames authored Dec 9, 2023
2 parents 191ac17 + 8e9222c commit 526bb8c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/kubernetes_validate/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
import re
import sys
from distutils.version import LooseVersion
from typing import Any, Dict, Generator, List
from typing import Any, Dict, Generator, List, Union
from typing_extensions import Protocol

import jsonschema
import pkg_resources
Expand All @@ -15,6 +16,10 @@
from kubernetes_validate.version import __version__


class SupportsToDict(Protocol):
def to_dict(self) -> dict: ... # noqa: E704


class ValidationError(jsonschema.ValidationError):
def __init__(self, caught: Exception, version: str):
self.version = version
Expand Down Expand Up @@ -58,7 +63,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], SupportsToDict], 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:]
Expand Down
13 changes: 13 additions & 0 deletions tests/test_validate_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 526bb8c

Please sign in to comment.