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 EnrichingProxy to run enrichment during !Lookups #45

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
22 changes: 22 additions & 0 deletions emrichen/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,25 @@ def add_variables(self, *variable_sources, **override_variables) -> None:
self.update(yaml_document)

self.update(override_variables)


class EnrichingProxy:
__slots__ = ('_context', '_target')

def __init__(self, context, target):
self._context = context
self._target = target

def __getitem__(self, key):
return EnrichingProxy(
context=self._context,
target=self._context.enrich(self._target[key]),
)

def __len__(self):
return len(self._target)

@classmethod
def unwrap(cls, obj):
assert isinstance(obj, cls)
return obj._target
7 changes: 5 additions & 2 deletions emrichen/tags/lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import jsonpath_rw

from ..context import Context
from ..context import Context, EnrichingProxy
from .base import BaseTag


Expand All @@ -13,7 +13,10 @@ def parse_jsonpath(expr: str):


def find_jsonpath_in_context(jsonpath_str: str, context: Context) -> List[jsonpath_rw.DatumInContext]:
return parse_jsonpath(jsonpath_str).find(context)
result = parse_jsonpath(jsonpath_str).find(EnrichingProxy(context, context))
for datum in result:
datum.value = EnrichingProxy.unwrap(datum.value)
return result


class Lookup(BaseTag):
Expand Down
15 changes: 14 additions & 1 deletion tests/test_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ def test_lookup_no_match():
assert 'no matches for' in str(ei.value)


@pytest.mark.xfail
def test_late_enrich():
template = Template.parse(
'''
Expand Down Expand Up @@ -103,3 +102,17 @@ def test_lookup_enrich():
'''
)
assert template.enrich({}) == [{'should_contain_5': [5]}]


@pytest.mark.xfail
def test_recursive_data_structure():
template = Template.parse('''
!Defaults
x:
y: 5
x: !Var x
---
five: !Lookup x.y
also_five: !Lookup x.x.x.x.x.y
''')
assert template.enrich({}) == [{'five': 5, 'also_five': 5}]