import asyncio

import aiohttp.web
import pytest

import kopf
from kopf._cogs.structs.bodies import RawBody, RawEvent
from kopf._cogs.structs.references import NAMESPACES, Insights, Resource
from kopf._core.reactor.observation import process_discovered_resource_event

# Implementation awareness: the events only trigger the re-scan, so the fields can be reduced
# to only the group name which is being rescanned. Other fields are ignored in the events.
# The actual data is taken from the API. It is tested elsewhere, so we rely on its correctness here.
GROUP1_EVENT = RawBody(spec={'group': 'group1'})


@pytest.fixture()
def core_mock(resp_mocker, aresponses, hostname):
    mock = resp_mocker(
        return_value=aiohttp.web.json_response({'versions': ['v1']}))
    aresponses.add(hostname, '/api', 'get', mock)
    return mock


@pytest.fixture()
def apis_mock(resp_mocker, aresponses, hostname):
    mock = resp_mocker(return_value=aiohttp.web.json_response({
        'groups': [
            {
                'name': 'group1',
                'preferredVersion': {
def test_events_ignored_for_mismatching(registry):
    e1 = RawEvent(type=None, object=RawBody(metadata={'name': 'def1'}))
    insights = Insights()
    revise_namespaces(insights=insights, namespaces=['ns*'], raw_events=[e1])
    assert not insights.namespaces
def test_bodies_for_initial_population(registry):
    b1 = RawBody(metadata={'name': 'ns1'})
    insights = Insights()
    revise_namespaces(insights=insights, namespaces=['ns*'], raw_bodies=[b1])
    assert insights.namespaces == {'ns1'}
def test_events_for_initial_population(registry):
    e1 = RawEvent(type=None, object=RawBody(metadata={'name': 'ns1'}))
    insights = Insights()
    revise_namespaces(insights=insights, namespaces=['ns*'], raw_events=[e1])
    assert insights.namespaces == {'ns1'}
def test_bodies_ignored_for_mismatching(registry):
    b1 = RawBody(metadata={'name': 'def1'})
    insights = Insights()
    revise_namespaces(insights=insights, namespaces=['ns*'], raw_bodies=[b1])
    assert not insights.namespaces
import pytest

import kopf
from kopf._cogs.structs.bodies import Body, RawBody, RawMeta

OWNER_API_VERSION = 'owner-api-version'
OWNER_NAMESPACE = 'owner-namespace'
OWNER_KIND = 'OwnerKind'
OWNER_NAME = 'owner-name'
OWNER_UID = 'owner-uid'
OWNER_LABELS = {'label-1': 'value-1', 'label-2': 'value-2'}
OWNER = RawBody(
    apiVersion=OWNER_API_VERSION,
    kind=OWNER_KIND,
    metadata=RawMeta(
        namespace=OWNER_NAMESPACE,
        name=OWNER_NAME,
        uid=OWNER_UID,
        labels=OWNER_LABELS,
    ),
)


def test_appending_to_dict():
    obj = {}

    kopf.append_owner_reference(obj, owner=Body(OWNER))

    assert 'metadata' in obj
    assert 'ownerReferences' in obj['metadata']
    assert isinstance(obj['metadata']['ownerReferences'], list)
    assert len(obj['metadata']['ownerReferences']) == 1