def owner(request, resource): if request.param == 'state-changing-cause': cause = ResourceChangingCause( logger=logging.getLogger('kopf.test.fake.logger'), resource=resource, patch=Patch(), memo=ObjectDict(), body=OWNER, initial=False, reason=Reason.NOOP, ) with context([(cause_var, cause)]): yield elif request.param == 'event-watching-cause': cause = ResourceWatchingCause( logger=logging.getLogger('kopf.test.fake.logger'), resource=resource, patch=Patch(), memo=ObjectDict(), body=OWNER, type='irrelevant', raw=Event(type='irrelevant', object=OWNER), ) with context([(cause_var, cause)]): yield else: raise RuntimeError( f"Wrong param for `owner` fixture: {request.param!r}")
def deliver_results( *, outcomes: Mapping[handlers_.HandlerId, HandlerOutcome], patch: patches.Patch, ) -> None: """ Store the results (as returned from the handlers) to the resource. This is not the handlers' state persistence, but the results' persistence. First, the state persistence is stored under ``.status.kopf.progress``, and can (later) be configured to be stored in different fields for different operators operating the same objects: ``.status.kopf.{somename}.progress``. The handlers' result are stored in the top-level ``.status``. Second, the handler results can (also later) be delivered to other objects, e.g. to their owners or label-selected related objects. For this, another class/module will be added. For now, we keep state- and result persistence in one module, but separated. """ for handler_id, outcome in outcomes.items(): if outcome.exception is not None: pass elif outcome.result is None: pass elif isinstance(outcome.result, collections.abc.Mapping): # TODO: merge recursively (patch-merge), do not overwrite the keys if they are present. patch.setdefault('status', {}).setdefault(handler_id, {}).update(outcome.result) else: patch.setdefault('status', {})[handler_id] = copy.deepcopy(outcome.result)
def owner(request, resource): body = Body(copy.deepcopy(OWNER)) if request.param == 'state-changing-cause': cause = ResourceChangingCause( logger=logging.getLogger('kopf.test.fake.logger'), indices=OperatorIndexers().indices, resource=resource, patch=Patch(), memo=Memo(), body=body, initial=False, reason=Reason.NOOP, ) with context([(cause_var, cause)]): yield body elif request.param == 'event-watching-cause': cause = ResourceWatchingCause( logger=logging.getLogger('kopf.test.fake.logger'), indices=OperatorIndexers().indices, resource=resource, patch=Patch(), memo=Memo(), body=body, type='irrelevant', raw=RawEvent(type='irrelevant', object=OWNER), ) with context([(cause_var, cause)]): yield body else: raise RuntimeError( f"Wrong param for `owner` fixture: {request.param!r}")
def append_finalizers( *, body: bodies.Body, patch: patches.Patch, ) -> None: if not has_finalizers(body=body): finalizers = body.get('metadata', {}).get('finalizers', []) patch.setdefault('metadata', {}).setdefault('finalizers', list(finalizers)) patch['metadata']['finalizers'].append(FINALIZER)
def test_removal_of_the_subkey(): patch = Patch() patch['xyz'] = {'abc': None} jsonpatch = patch.as_json_patch() assert jsonpatch == [ { 'op': 'remove', 'path': '/xyz/abc' }, ]
def test_removal_of_the_key(): patch = Patch() patch['xyz'] = None jsonpatch = patch.as_json_patch() assert jsonpatch == [ { 'op': 'remove', 'path': '/xyz' }, ]
def block_deletion( *, body: bodies.Body, patch: patches.Patch, ) -> None: if not is_deletion_blocked(body=body): finalizers = body.get('metadata', {}).get('finalizers', []) patch.setdefault('metadata', {}).setdefault('finalizers', list(finalizers)) patch['metadata']['finalizers'].append(FINALIZER)
def test_addition_of_the_key(): patch = Patch() patch['xyz'] = 123 jsonpatch = patch.as_json_patch() assert jsonpatch == [ { 'op': 'replace', 'path': '/xyz', 'value': 123 }, ]
def allow_deletion( *, body: bodies.Body, patch: patches.Patch, finalizer: str, ) -> None: if is_deletion_blocked(body=body, finalizer=finalizer): finalizers = body.get('metadata', {}).get('finalizers', []) patch.setdefault('metadata', {}).setdefault('finalizers', list(finalizers)) if finalizer in patch['metadata']['finalizers']: patch['metadata']['finalizers'].remove(finalizer)
def purge(self, patch: patches.Patch, body: bodies.Body) -> None: if 'progress' in body.get('status', {}).get('kopf', {}): patch_storage = patch.setdefault('status', {}).setdefault('kopf', {}) patch_storage['progress'] = None elif 'progress' in patch.get('status', {}).get('kopf', {}): del patch['status']['kopf']['progress'] # Avoid storing the empty status dicts (but do so if they have any content). if 'status' in patch and 'kopf' in patch['status'] and not patch['status']['kopf']: del patch['status']['kopf'] if 'status' in patch and not patch['status']: del patch['status']
def remove_finalizers( *, body: bodies.Body, patch: patches.Patch, ) -> None: if has_finalizers(body=body): finalizers = body.get('metadata', {}).get('finalizers', []) patch.setdefault('metadata', {}).setdefault('finalizers', list(finalizers)) if LEGACY_FINALIZER in patch['metadata']['finalizers']: patch['metadata']['finalizers'].remove(LEGACY_FINALIZER) if FINALIZER in patch['metadata']['finalizers']: patch['metadata']['finalizers'].remove(FINALIZER)
def allow_deletion( *, body: bodies.Body, patch: patches.Patch, ) -> None: if is_deletion_blocked(body=body): finalizers = body.get('metadata', {}).get('finalizers', []) patch.setdefault('metadata', {}).setdefault('finalizers', list(finalizers)) if LEGACY_FINALIZER in patch['metadata']['finalizers']: patch['metadata']['finalizers'].remove(LEGACY_FINALIZER) if FINALIZER in patch['metadata']['finalizers']: patch['metadata']['finalizers'].remove(FINALIZER)
def make_cause( cls=ResourceChangingCause, *, resource=resource, type=None, raw=None, body=None, diff=(), reason='some-reason', initial=False, activity=None, settings=None, ): if cls is ActivityCause or cls is ActivityRegistry: return ActivityCause( logger=logging.getLogger('kopf.test.fake.logger'), activity=activity, settings=settings, ) if cls is ResourceCause or cls is ResourceRegistry or cls is SimpleRegistry: return ResourceCause( logger=logging.getLogger('kopf.test.fake.logger'), resource=resource, patch=Patch(), memo=Memo(), body=Body(body if body is not None else {}), ) if cls is ResourceWatchingCause or cls is ResourceWatchingRegistry: return ResourceWatchingCause( logger=logging.getLogger('kopf.test.fake.logger'), resource=resource, patch=Patch(), memo=Memo(), body=Body(body if body is not None else {}), type=type, raw=raw, ) if cls is ResourceChangingCause or cls is ResourceChangingRegistry: return ResourceChangingCause( logger=logging.getLogger('kopf.test.fake.logger'), resource=resource, patch=Patch(), memo=Memo(), body=Body(body if body is not None else {}), diff=Diff(DiffItem(*d) for d in diff), initial=initial, reason=reason, ) raise TypeError( f"Cause/registry type {cls} is not supported by this fixture.")
def store_result( *, patch: patches.Patch, handler: registries.ResourceHandler, result: Any = None, ) -> None: if result is None: pass elif isinstance(result, collections.abc.Mapping): # TODO: merge recursively (patch-merge), do not overwrite the keys if they are present. patch.setdefault('status', {}).setdefault(handler.id, {}).update(result) else: # TODO? Fail if already present? patch.setdefault('status', {})[handler.id] = copy.deepcopy(result)
def test_touching_via_annotations_storage_with_none_when_absent(cls): storage = cls(prefix='my-operator.example.com', touch_key='my-dummy') patch = Patch() body = Body({}) storage.touch(body=body, patch=patch, value=None) assert not patch
def test_purge_progress_cascades_to_subrefs(storage, handler): body = { 'status': { 'kopf': { 'progress': { 'some-id': { 'subrefs': ['sub1', 'sub2', 'sub3'] }, 'sub1': {}, 'sub2': {}, # 'sub3' is intentionally absent -- should not be purged as already non-existent. 'sub-unrelated': {}, # should be ignored, as not related to the involved handlers. } } } } patch = Patch() state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) state.purge(patch=patch, body=Body(body), storage=storage) assert patch == { 'status': { 'kopf': { 'progress': { 'some-id': None, 'sub1': None, 'sub2': None, } } } }
async def test_special_kwargs_added(fn, resource): body = {'metadata': {'uid': 'uid', 'name': 'name', 'namespace': 'ns'}, 'spec': {'field': 'value'}, 'status': {'info': 'payload'}} # Values can be any. cause = ResourceChangingCause( logger=logging.getLogger('kopf.test.fake.logger'), resource=resource, patch=Patch(), initial=False, reason=Reason.NOOP, memo=object(), body=Body(body), diff=object(), old=object(), new=object(), ) fn = MagicMock(fn) await invoke(fn, cause=cause) assert fn.called assert fn.call_count == 1 # Only check that kwargs are passed at all. The exact kwargs per cause are tested separately. assert 'logger' in fn.call_args[1] assert 'resource' in fn.call_args[1]
async def test_patching_with_disappearance( resource, namespace, settings, caplog, assert_logs, version_api, aresponses, hostname, resp_mocker): caplog.set_level(logging.DEBUG) patch = {'spec': {'x': 'y'}, 'status': {'s': 't'}} # irrelevant url = resource.get_url(namespace=namespace, name='name1') patch_mock = resp_mocker(return_value=aresponses.Response(status=404)) aresponses.add(hostname, url, 'patch', patch_mock) body = Body({'metadata': {'namespace': namespace, 'name': 'name1'}}) logger = LocalObjectLogger(body=body, settings=settings) await patch_and_check( resource=resource, body=body, patch=Patch(patch), logger=logger, ) assert_logs([ "Patching with:", "Patching was skipped: the object does not exist anymore", ], prohibited=[ "inconsistencies" ])
def test_subrefs_added_to_preexisting_subrefs(storage, handler): body = { 'status': { 'kopf': { 'progress': { 'some-id': { 'subrefs': ['sub9/2', 'sub9/1'] } } } } } patch = Patch() outcome_subrefs = ['sub2/b', 'sub2/a', 'sub2', 'sub1', 'sub3'] expected_subrefs = [ 'sub1', 'sub2', 'sub2/a', 'sub2/b', 'sub3', 'sub9/1', 'sub9/2' ] outcome = HandlerOutcome(final=True, subrefs=outcome_subrefs) state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) state = state.with_handlers([handler]) state = state.with_outcomes(outcomes={handler.id: outcome}) state.store(patch=patch, body=Body(body), storage=storage) assert patch['status']['kopf']['progress']['some-id'][ 'subrefs'] == expected_subrefs
def test_always_started_when_created_from_body(storage, handler, body, expected): origbody = copy.deepcopy(body) patch = Patch() state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) state.store(body=Body({}), patch=patch, storage=storage) assert patch['status']['kopf']['progress']['some-id']['started'] == expected assert body == origbody # not modified
async def test_patching_without_inconsistencies(resource, settings, caplog, assert_logs, version_api, aresponses, hostname, resp_mocker, patch, response): caplog.set_level(logging.DEBUG) url = resource.get_url(namespace='ns1', name='name1') patch_mock = resp_mocker(return_value=aiohttp.web.json_response(response)) aresponses.add(hostname, url, 'patch', patch_mock) body = Body({'metadata': {'namespace': 'ns1', 'name': 'name1'}}) logger = LocalObjectLogger(body=body, settings=settings) await patch_and_check( resource=resource, body=body, patch=Patch(patch), logger=logger, ) assert_logs([ "Patching with:", ], prohibited=[ "Patching failed with inconsistencies:", ])
def test_touching_via_status_storage_with_none_when_absent(cls): storage = cls(touch_field='status.my-dummy') patch = Patch() body = Body({}) storage.touch(body=body, patch=patch, value=None) assert not patch
def store(self, patch: patches.Patch) -> None: for handler_id, handler_state in self.items(): # Nones are not stored by Kubernetes, so we filter them out for comparison. if handler_state.as_dict() != handler_state._origin: # Note: create the 'progress' key only if there are handlers to store, not always. storage = patch.setdefault('status', {}).setdefault('kopf', {}) storage.setdefault('progress', {})[handler_id] = handler_state.as_patch()
def test_resource_changing_kwargs(resource, indices): body = { 'metadata': { 'uid': 'uid1', 'name': 'name1', 'namespace': 'ns1', 'labels': { 'l1': 'v1' }, 'annotations': { 'a1': 'v1' } }, 'spec': { 'field': 'value' }, 'status': { 'info': 'payload' } } cause = ResourceChangingCause( logger=logging.getLogger('kopf.test.fake.logger'), indices=indices, resource=resource, patch=Patch(), initial=False, reason=Reason.NOOP, memo=Memo(), body=Body(body), diff=Diff([]), old=BodyEssence(), new=BodyEssence(), ) kwargs = build_kwargs(cause=cause, extrakwarg=123) assert set(kwargs) == { 'extrakwarg', 'logger', 'index1', 'index2', 'resource', 'patch', 'reason', 'memo', 'body', 'spec', 'status', 'meta', 'uid', 'name', 'namespace', 'labels', 'annotations', 'diff', 'old', 'new' } assert kwargs['extrakwarg'] == 123 assert kwargs['resource'] is cause.resource assert kwargs['index1'] is indices['index1'] assert kwargs['index2'] is indices['index2'] assert kwargs['reason'] is cause.reason assert kwargs['logger'] is cause.logger assert kwargs['patch'] is cause.patch assert kwargs['memo'] is cause.memo assert kwargs['diff'] is cause.diff assert kwargs['old'] is cause.old assert kwargs['new'] is cause.new assert kwargs['body'] is cause.body assert kwargs['spec'] is cause.body.spec assert kwargs['meta'] is cause.body.metadata assert kwargs['status'] is cause.body.status assert kwargs['labels'] is cause.body.metadata.labels assert kwargs['annotations'] is cause.body.metadata.annotations assert kwargs['uid'] == cause.body.metadata.uid assert kwargs['name'] == cause.body.metadata.name assert kwargs['namespace'] == cause.body.metadata.namespace
def test_purge_progress_when_already_empty_in_body_but_not_in__patch(storage, handler): body = {} patch = Patch({'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}}) origbody = copy.deepcopy(body) state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) state.purge(patch=patch, body=Body(body), storage=storage) assert not patch assert body == origbody # not modified
def test_purge_progress_when_known_at_restoration_only(storage, handler): body = {'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}} patch = Patch() state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) state.purge(patch=patch, body=Body(body), storage=storage, handlers=[]) assert patch == {'status': {'kopf': {'progress': {'some-id': None}}}}
def test_started_from_storage(storage, handler, body, expected): patch = Patch() state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) state.store(body=Body({}), patch=patch, storage=storage) assert patch['status']['kopf']['progress']['some-id'][ 'started'] == expected
def test_touching_via_status_storage_with_none_when_present(cls): storage = cls(touch_field='status.my-dummy') patch = Patch() body = Body({'status': {'my-dummy': 'something'}}) storage.touch(body=body, patch=patch, value=None) assert patch assert patch['status']['my-dummy'] is None
def test_purging_of_status_storage_nullifies_content(cls): storage = cls(field='status.my-operator') patch = Patch() body = Body({'status': {'my-operator': {'id1': CONTENT_DATA_1}}}) storage.purge(body=body, patch=patch, key=HandlerId('id1')) assert patch assert patch['status']['my-operator']['id1'] is None
def test_touching_via_status_storage_with_payload(cls, body_data): storage = cls(field='status.my-operator', touch_field='status.my-dummy') patch = Patch() body = Body(body_data) storage.touch(body=body, patch=patch, value='hello') assert patch assert patch['status']['my-dummy'] == 'hello'