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 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 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 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_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_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:", ])
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]
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_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
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_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
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_and_patch(storage, handler): body = {} patch = Patch() 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_exists_in_body(storage, handler): body = {'status': {'kopf': {'progress': {'some-id': {'retries': 5}}}}} patch = Patch() 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 patch == {'status': {'kopf': {'progress': {'some-id': None}}}} assert body == origbody # not modified
def test_set_awake_time(storage, handler, expected, body, delay): origbody = copy.deepcopy(body) patch = Patch() state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) state = state.with_outcomes(outcomes={handler.id: HandlerOutcome(final=False, delay=delay)}) state.store(patch=patch, body=Body(body), storage=storage) assert patch['status']['kopf']['progress']['some-id'].get('delayed') == expected assert body == origbody # not modified
def test_storing_to_status_storage_populates_keys(cls): storage = cls(field='status.my-operator.diff-base') patch = Patch() body = Body({}) storage.store(body=body, patch=patch, essence=ESSENCE_DATA_1) assert patch assert patch['status']['my-operator']['diff-base'] == ESSENCE_JSON_1
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_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_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_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'
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_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}}}}
async def test_status_as_subresource_with_object_fields_only( resp_mocker, aresponses, hostname, resource, version_api_with_substatus): # Simulate Kopf's initial state and intention. patch = Patch({'spec': {'x': 'y'}}) # Simulate K8s API's behaviour. Assume something extra is added remotely. object_response = { 'metadata': { 'namespace': 'ns1', 'name': 'name1', 'extra': '123' }, 'spec': { 'x': 'y', 'extra': '456' }, 'status': '...' } status_response = {'status': {'s': 't', 'extra': '789'}} object_url = resource.get_url(namespace='ns1', name='name1') status_url = resource.get_url(namespace='ns1', name='name1', subresource='status') object_patch_mock = resp_mocker( return_value=aiohttp.web.json_response(object_response)) status_patch_mock = resp_mocker( return_value=aiohttp.web.json_response(status_response)) aresponses.add(hostname, object_url, 'patch', object_patch_mock) aresponses.add(hostname, status_url, 'patch', status_patch_mock) reconstructed = await patch_obj(resource=resource, namespace='ns1', name='name1', patch=patch) assert object_patch_mock.called assert object_patch_mock.call_count == 1 assert not status_patch_mock.called data = object_patch_mock.call_args_list[0][0][ 0].data # [callidx][args/kwargs][argidx] assert data == {'spec': {'x': 'y'}} assert reconstructed == { 'metadata': { 'namespace': 'ns1', 'name': 'name1', 'extra': '123' }, 'spec': { 'x': 'y', 'extra': '456' }, 'status': '...' }
def test_keys_normalized_on_storing(cls, prefix, provided_key, expected_key): storage = cls(prefix=prefix) patch = Patch() body = Body({'metadata': {'annotations': {expected_key: 'null'}}}) storage.store(body=body, patch=patch, key=HandlerId(provided_key), record=CONTENT_DATA) assert expected_key in patch.metadata.annotations
def test_touching_via_annotations_storage_with_payload(cls, body_data): storage = cls(prefix='my-operator.example.com', touch_key='my-dummy') patch = Patch() body = Body(body_data) storage.touch(body=body, patch=patch, value='hello') assert patch assert patch['metadata']['annotations'][ 'my-operator.example.com/my-dummy'] == 'hello'
def test_resource_watching_kwargs(resource, indices): body = { 'metadata': { 'uid': 'uid1', 'name': 'name1', 'namespace': 'ns1', 'labels': { 'l1': 'v1' }, 'annotations': { 'a1': 'v1' } }, 'spec': { 'field': 'value' }, 'status': { 'info': 'payload' } } cause = ResourceWatchingCause( logger=logging.getLogger('kopf.test.fake.logger'), indices=indices, resource=resource, patch=Patch(), memo=Memo(), body=Body(body), type='ADDED', raw={ 'type': 'ADDED', 'object': {} }, ) kwargs = build_kwargs(cause=cause, extrakwarg=123) assert set(kwargs) == { 'extrakwarg', 'logger', 'index1', 'index2', 'resource', 'patch', 'event', 'type', 'memo', 'body', 'spec', 'status', 'meta', 'uid', 'name', 'namespace', 'labels', 'annotations' } assert kwargs['extrakwarg'] == 123 assert kwargs['resource'] is cause.resource assert kwargs['index1'] is indices['index1'] assert kwargs['index2'] is indices['index2'] assert kwargs['logger'] is cause.logger assert kwargs['patch'] is cause.patch assert kwargs['event'] is cause.raw assert kwargs['memo'] is cause.memo assert kwargs['type'] is cause.type 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_storing_to_annotations_storage_populates_keys(cls): storage = cls(name='my-operator.example.com/diff-base') patch = Patch() body = Body({}) storage.store(body=body, patch=patch, essence=ESSENCE_DATA_1) assert patch assert patch['metadata']['annotations'][ 'my-operator.example.com/diff-base'] == ESSENCE_JSON_1
def test_removal_of_the_key(): patch = Patch() patch['xyz'] = None jsonpatch = patch.as_json_patch() assert jsonpatch == [ { 'op': 'remove', 'path': '/xyz' }, ]
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_subrefs_ignored_when_not_specified(storage, handler): body = {} patch = Patch() outcome = HandlerOutcome(final=True, subrefs=[]) state = State.from_storage(body=Body(body), handlers=[handler], storage=storage) 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'] is None