Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for validating objects with a to_dict method #23

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading