def __init__(
     self,
     efs_id: str,
     cluster_name: str,
     elastic_search_access_role_arn: str,
     default_role_arn: str,
     alb_role_arn: str,
     external_dns_role_arn: str,
     autoscaling_role_arn: str,
     dag_sync_role_arn: str,
     domain: str,
     domain_filters: Optional[List[str]] = None,
     use_ssl: bool = False,
 ):
     self.__efs_id = efs_id
     self.__cluster_name = cluster_name
     self.__elastic_search_access_role = elastic_search_access_role_arn
     self.__default_role = default_role_arn
     self.__alb_role_arn = alb_role_arn
     self.__domain = domain
     self.__domain_filters = domain_filters
     self.__external_dns_role_arn = external_dns_role_arn
     self.__values = ValueOrchestrator()
     self.__use_ssl = use_ssl
     self.__autoscaling_role_arn = autoscaling_role_arn
     self.__dag_sync_role_arn = dag_sync_role_arn
     super().__init__(
         StorageClass(ObjectMeta(name="efs-sc"), "efs.csi.aws.com"),
         "Filesystem",
     )
def test_certificate_signing_request(chart_info):
    signing_request = CertificateSigningRequest(
        ObjectMeta(name="signing-request"),
        CertificateSigningRequestSpec(
            "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURSBSRVFVRVNULS0tLS0KTUlJQ1ZqQ0NBVDRDQV"
            "FBd0VURVBNQTBHQTFVRUF3d0dZVzVuWld4aE1JSUJJakFOQmdrcWhraUc5dzBCQVFF"
            "RgpBQU9DQVE4QU1JSUJDZ0tDQVFFQTByczhJTHRHdTYxakx2dHhWTTJSVlRWMDNHWl"
            "JTWWw0dWluVWo4RElaWjBOCnR2MUZtRVFSd3VoaUZsOFEzcWl0Qm0wMUFSMkNJVXBG"
            "d2ZzSjZ4MXF3ckJzVkhZbGlBNVhwRVpZM3ExcGswSDQKM3Z3aGJlK1o2MVNrVHF5SV"
            "BYUUwrTWM5T1Nsbm0xb0R2N0NtSkZNMUlMRVI3QTVGZnZKOEdFRjJ6dHBoaUlFMwpu"
            "b1dtdHNZb3JuT2wzc2lHQ2ZGZzR4Zmd4eW8ybmlneFNVekl1bXNnVm9PM2ttT0x1RV"
            "F6cXpkakJ3TFJXbWlECklmMXBMWnoyalVnald4UkhCM1gyWnVVV1d1T09PZnpXM01L"
            "aE8ybHEvZi9DdS8wYk83c0x0MCt3U2ZMSU91TFcKcW90blZtRmxMMytqTy82WDNDKz"
            "BERHk5aUtwbXJjVDBnWGZLemE1dHJRSURBUUFCb0FBd0RRWUpLb1pJaHZjTgpBUUVM"
            "QlFBRGdnRUJBR05WdmVIOGR4ZzNvK21VeVRkbmFjVmQ1N24zSkExdnZEU1JWREkyQT"
            "Z1eXN3ZFp1L1BVCkkwZXpZWFV0RVNnSk1IRmQycVVNMjNuNVJsSXJ3R0xuUXFISUh5"
            "VStWWHhsdnZsRnpNOVpEWllSTmU3QlJvYXgKQVlEdUI5STZXT3FYbkFvczFqRmxNUG"
            "5NbFpqdU5kSGxpT1BjTU1oNndLaTZzZFhpVStHYTJ2RUVLY01jSVUyRgpvU2djUWdM"
            "YTk0aEpacGk3ZnNMdm1OQUxoT045UHdNMGM1dVJVejV4T0dGMUtCbWRSeEgvbUNOS2"
            "JKYjFRQm1HCkkwYitEUEdaTktXTU0xMzhIQXdoV0tkNjVoVHdYOWl4V3ZHMkh4TG1W"
            "Qzg0L1BHT0tWQW9FNkpsYWFHdTlQVmkKdjlOSjVaZlZrcXdCd0hKbzZXdk9xVlA3SV"
            "FjZmg3d0drWm89Ci0tLS0tRU5EIENFUlRJRklDQVRFIFJFUVVFU1QtLS0tLQo="),
    )
    builder = ChartBuilder(
        chart_info,
        [signing_request],
    )
    with ChartInstallationContext(builder):
        certificate_signing_request_frame = DataFrame(
            kubectl_get("certificatesigningrequest"))
        certificate_signing_request_frame = certificate_signing_request_frame[
            certificate_signing_request_frame["NAME"] ==
            signing_request.metadata.name].reset_index()
        assert certificate_signing_request_frame["NAME"][
            0] == "signing-request"
Exemple #3
0
def get_custom_resource_definition(
    external_documentation: Optional[ExternalDocumentation] = None,
    subresources: Optional[CustomResourceSubresources] = None,
    custom_resource_conversion: Optional[CustomResourceConversion] = None,
):
    return CustomResourceDefinition(
        ObjectMeta(name="tests.customs.com"),
        CustomResourceDefinitionSpec(
            "customs.com",
            CustomResourceDefinitionNames(["test"], "test-kind", "tests"),
            "Cluster",
            [
                CustomResourceDefinitionVersion(
                    "test-version",
                    [CustomResourceColumnDefinition("test-name", ".path", "integer")],
                    CustomResourceValidation(
                        JSONSchemaProps("object", external_docs=external_documentation)
                    ),
                    False,
                    True,
                    subresources=subresources,
                )
            ],
            conversion=custom_resource_conversion,
        ),
    )
Exemple #4
0
def test_network_policy(
    chart_info,
    name: str,
    selector: Optional[LabelSelector],
    egress: Optional[List[NetworkPolicyEgressRule]],
    ingress: Optional[List[NetworkPolicyIngressRule]],
    policy_types: Optional[List[str]],
):
    builder = ChartBuilder(
        chart_info,
        [
            NetworkPolicy(
                ObjectMeta(name=name),
                NetworkPolicySpec(egress, ingress, selector, policy_types),
            )
        ],
    )
    with ChartInstallationContext(builder):
        network_policy_info = kubectl_get("networkpolicy")
        assert network_policy_info["NAME"][0] == name
        expected_selector = "<none>"
        if isinstance(selector, LabelSelector):
            match_labels = selector.matchLabels
            if match_labels is None:
                raise Exception("Match labels cannot be none in this case")
            first_key = list(match_labels.keys())[0]
            expected_selector = f"{first_key}={match_labels[first_key]}"
        assert network_policy_info["POD-SELECTOR"][0] == expected_selector
Exemple #5
0
def test_deployment(
    chart_info,
    test_labels,
    pod_template_spec,
    selector,
    deployment_strategy: Optional[DeploymentStrategy],
):
    builder = ChartBuilder(
        chart_info,
        [
            Deployment(
                metadata=ObjectMeta(name="test-deployment",
                                    labels=test_labels),
                spec=DeploymentSpec(
                    replicas=1,
                    template=pod_template_spec,
                    selector=selector,
                    strategy=deployment_strategy,
                ),
            )
        ],
    )
    with ChartInstallationContext(builder):
        deployment_info = kubectl_get("deployments")
        assert deployment_info["NAME"][0] == "test-deployment"
        assert deployment_info["READY"][0] == "1/1"
Exemple #6
0
def get_base_pod_security_policy(
    name: str,
    allowed_csi_drivers: Optional[List[AllowedCSIDriver]] = None,
    allowed_flex_volumes: Optional[List[AllowedFlexVolume]] = None,
    allowed_host_paths: Optional[List[AllowedHostPath]] = None,
    host_ports: Optional[List[HostPortRange]] = None,
    run_as_group: Optional[RunAsGroupStrategyOptions] = None,
    runtime_class: Optional[RuntimeClassStrategyOptions] = None,
    se_linux_options: Optional[SELinuxOptions] = None,
):
    return PodSecurityPolicy(
        ObjectMeta(name=name),
        PodSecurityPolicySpec(
            FSGroupStrategyOptions("RunAsAny"),
            RunAsUserStrategyOptions("RunAsAny"),
            SELinuxStrategyOptions("RunAsAny", se_linux_options),
            SupplementalGroupsStrategyOptions("RunAsAny"),
            allowed_csidrivers=allowed_csi_drivers,
            allowed_flex_volumes=allowed_flex_volumes,
            allowed_host_paths=allowed_host_paths,
            host_ports=host_ports,
            run_as_group=run_as_group,
            runtime_class=runtime_class,
        ),
    )
Exemple #7
0
def test_eviction(chart_info):
    builder = ChartBuilder(
        chart_info,
        [Eviction(ObjectMeta(name="test-eviction"), None)],  # type: ignore
    )
    with ChartInstallationContext(builder):
        kubectl_get("eviction")
Exemple #8
0
def test_secret(chart_info, secret_data: dict):
    builder = ChartBuilder(
        chart_info, [Secret(ObjectMeta(name="test-secret"), secret_data)])
    with ChartInstallationContext(builder):
        secret_info = get_secret_info()
        assert secret_info["NAME"][0] == "test-secret"
        assert secret_info["DATA"][0] == str(
            len(secret_data)) if secret_data else "0"
Exemple #9
0
def empty_persistent_volume_claim(access_modes):
    return PersistentVolumeClaim(
        ObjectMeta(name="test-persistent-volume-claim"),
        PersistentVolumeClaimSpec(
            access_modes,
            ResourceRequirements(requests={"storage": 1}),
        ),
    )
Exemple #10
0
def persistent_volume(persistent_volume_spec):
    """
    A generic persistent volume
    """
    return PersistentVolume(
        ObjectMeta(name="test-persistent-volume"),
        persistent_volume_spec,
    )
Exemple #11
0
def cron_job(pod_template_spec, job_spec):

    return CronJob(
        ObjectMeta(name="test-cron-job"),
        CronJobSpec(
            JobTemplateSpec(job_spec),
            "23 * * * 6",
        ),
    )
Exemple #12
0
def test_ingress_class(chart_info):
    ingress_class = IngressClass(ObjectMeta(name="test-ingress-class"),
                                 IngressClassSpec("acme.io/foo"))
    builder = ChartBuilder(
        chart_info,
        [ingress_class],
    )
    with ChartInstallationContext(builder):
        ingress_class_info = kubectl_get("ingressclass")
        assert ingress_class_info["NAME"][0] == ingress_class.metadata.name
        assert ingress_class_info["CONTROLLER"][
            0] == ingress_class.spec.controller
Exemple #13
0
def test_service(chart_info, service_spec: ServiceSpec):
    builder = ChartBuilder(
        chart_info, [Service(ObjectMeta(name="test-service"), service_spec)])
    with ChartInstallationContext(builder):
        service_info = get_service_info()
        assert service_info["NAME"][0] == "test-service"
        assert service_info["PORT(S)"][0] == ",".join([
            f"{port.port}/{port.protocol if port.protocol else 'TCP'}"
            for port in service_spec.ports
        ])
        assert service_info["EXTERNAL-IP"][0] == (service_spec.externalIPs[0]
                                                  if service_spec.externalIPs
                                                  else "<none>")
def test_token_request(chart_info):
    builder = ChartBuilder(
        chart_info,
        [
            TokenRequest(
                ObjectMeta(name="token-request"),
                TokenRequestSpec(["audience1", "audience2"], None, None),  # type: ignore
                "v1",
            )
        ],
    )
    with ChartInstallationContext(builder):
        print(kubectl_get("tokenrequest"))
Exemple #15
0
def persistent_volume_claim(persistent_volume):
    """
    A generic persistent volume claim
    """
    return PersistentVolumeClaim(
        ObjectMeta(name="test-pv-claim"),
        PersistentVolumeClaimSpec(
            persistent_volume.spec.accessModes,
            resources=ResourceRequirements(
                requests={
                    "storage": persistent_volume.spec.capacity["storage"]
                }),
        ),
    )
Exemple #16
0
def test_persistent_volume(chart_info, persistent_volume_spec):
    persistent_volume = PersistentVolume(
        ObjectMeta(name="test-persistent-volume"), persistent_volume_spec)
    builder = ChartBuilder(
        chart_info,
        [persistent_volume],
    )
    with ChartInstallationContext(builder):
        volume_info = kubectl_get("persistentvolumes")
        assert volume_info["NAME"][0] == persistent_volume.metadata.name
        assert persistent_volume.spec.capacity is not None
        assert volume_info["CAPACITY"][0] == str(
            persistent_volume.spec.capacity["storage"])
        assert volume_info["ACCESS MODES"][0] == modes_expected_value
Exemple #17
0
def test_ingress(chart_info, ingress_spec: IngressSpec):
    ingress = Ingress(ObjectMeta(name="test-ingress"), ingress_spec)
    builder = ChartBuilder(chart_info, [ingress])
    with ChartInstallationContext(builder):
        ingress_info = kubectl_get("ingress")
        print(ingress_info)
        assert ingress_info["NAME"][0] == ingress.metadata.name
        assert (
            ingress_info["CLASS"][0] == ingress.spec.ingressClassName
            if ingress.spec.ingressClassName
            else "<none>"
        )
        assert ingress_info["HOSTS"][0] == "*"
        assert ingress_info["PORTS"][0] == "80" if not ingress.spec.tls else "80, 443"
Exemple #18
0
def test_lease(chart_info, holder_identity):
    builder = ChartBuilder(
        chart_info,
        [
            Lease(
                ObjectMeta(name="test-lease"),
                LeaseSpec(holder_identity=holder_identity),
            )
        ],
    )
    with ChartInstallationContext(builder):
        lease_info = kubectl_get("lease")
        assert lease_info["NAME"][0] == "test-lease"
        assert lease_info["HOLDER"][0] == (holder_identity
                                           if holder_identity else "")
def test_token_review(chart_info):
    builder = ChartBuilder(
        chart_info,
        [
            TokenReview(
                ObjectMeta(name="test-token"),
                TokenReviewSpec(["audience", "other_auditence"], "tokentoken"),
            )
        ],
    )
    with ChartInstallationContext(builder):
        token_review_info = kubectl_get("tokenreview")
        print(token_review_info)
        assert token_review_info["NAME"][0] == "test_name"
        assert token_review_info["DESIRED"][0] == "1"
        assert token_review_info["CURRENT"][0] == "1"
Exemple #20
0
def test_horizontal_pod_autoscaler(chart_info):
    autoscaler = HorizontalPodAutoscaler(
        ObjectMeta(name="test-autoscaler"),
        HorizontalPodAutoscalerSpec(1,
                                    CrossVersionObjectReference("test",
                                                                "Pod")),
    )
    builder = ChartBuilder(
        chart_info,
        kubernetes_objects=[autoscaler],
    )
    with ChartInstallationContext(builder):
        autoscaling_info = kubectl_get("horizontalpodautoscaler")
        assert autoscaling_info["NAME"][0] == "test-autoscaler"
        assert (autoscaling_info["REFERENCE"][0] ==
                f"{autoscaler.spec.scaleTargetRef.kind}/test")
        assert autoscaling_info["MAXPODS"][0] == "1"
Exemple #21
0
def test_daemon_set(
    chart_info,
    pod_template_spec,
    selector,
    update_strategy: Optional[DaemonSetUpdateStrategy],
):
    builder = ChartBuilder(
        chart_info,
        [
            DaemonSet(
                ObjectMeta(name="test-daemon-set"),
                DaemonSetSpec(pod_template_spec,
                              selector,
                              update_strategy=update_strategy),
            )
        ],
    )
    with ChartInstallationContext(builder):
        daemon_set_info = kubectl_get("daemonsets")
        assert daemon_set_info["NAME"][0] == "test-daemon-set"
        assert daemon_set_info["DESIRED"][0] == "1"
        assert daemon_set_info["CURRENT"][0] == "1"
Exemple #22
0
def test_stateful_set(
    chart_info,
    pod_template_spec,
    selector,
    update_strategy: Optional[StatefulSetUpdateStrategy],
):
    builder = ChartBuilder(
        chart_info,
        [
            StatefulSet(
                ObjectMeta(name="test-stateful-set"),
                StatefulSetSpec(
                    pod_template_spec,
                    selector,
                    "my-service",
                    update_strategy=update_strategy,
                ),
            )
        ],
    )
    with ChartInstallationContext(builder):
        stateful_set_info = kubectl_get("statefulsets")
        assert stateful_set_info["NAME"][0] == "test-stateful-set"
        assert stateful_set_info["READY"][0] == "1/1"
Exemple #23
0
def test_job(chart_info, job_spec):
    builder = ChartBuilder(chart_info,
                           [Job(ObjectMeta(name="test-job"), job_spec)])
    with ChartInstallationContext(builder):
        job_info = kubectl_get("job")
        assert job_info["NAME"][0] == "test-job"
Exemple #24
0
from pandas import DataFrame
import pytest

from avionix import ChartBuilder, ObjectMeta
from avionix.kube.scheduling import PriorityClass
from avionix.testing import kubectl_get
from avionix.testing.installation_context import ChartInstallationContext


@pytest.mark.parametrize(
    "priority_class",
    [
        PriorityClass(ObjectMeta(name="test-priority-class"), 1),
        PriorityClass(ObjectMeta(name="priority-class-global-default"), 1, True),
    ],
)
def test_priority_class(chart_info, priority_class):
    builder = ChartBuilder(chart_info, [priority_class])
    with ChartInstallationContext(builder):
        class_info = kubectl_get("priorityclass")
        class_info_frame = DataFrame(class_info)
        filter_frame = class_info_frame[
            class_info_frame["NAME"] == priority_class.metadata.name
        ].reset_index()
        assert filter_frame["NAME"][0] == priority_class.metadata.name
        assert filter_frame["VALUE"][0] == str(priority_class.value)
        assert (
            filter_frame["GLOBAL-DEFAULT"][0]
            == str(bool(priority_class.globalDefault)).lower()
        )
Exemple #25
0
    GroupVersionForDiscovery,
    ManagedFieldsEntry,
    OwnerReference,
    StatusDetails,
)
from avionix.testing import kubectl_get
from avionix.testing.installation_context import ChartInstallationContext


@pytest.mark.parametrize(
    "object_meta",
    [
        ObjectMeta(
            name="test-managed-fields",
            managed_fields=[
                ManagedFieldsEntry("test"),
                ManagedFieldsEntry(fields_v1={"my": "data"}),
                ManagedFieldsEntry(time=datetime.now()),
            ],
        ),
        ObjectMeta(
            name="test-owner-reference",
            owner_references=[OwnerReference("test", "10")],
        ),
    ],
)
def test_object_meta(chart_info: ChartInfo, object_meta: ObjectMeta):
    config_map = ConfigMap(object_meta, {"test": "1"},)
    builder = ChartBuilder(chart_info, [config_map])
    with ChartInstallationContext(builder):
        config_maps = kubectl_get("configmaps")
        assert config_maps["NAME"][0] == config_map.metadata.name
Exemple #26
0
def config_map_value_yaml():
    return ConfigMap(
        ObjectMeta(name="test-values"),
        {"my_value": Value("my_value"), "my_nested_value": Value("my.nested.value")},
    )
Exemple #27
0
        endpoint_ips += endpoint.addresses
    return ",".join(endpoint_ips)


def get_all_endpoint_ports(endpoint_slice: EndpointSlice) -> str:
    if endpoint_slice.ports is None:
        raise Exception("Endpoint port cannot be none!")
    return ",".join(
        [str(port_object.port) for port_object in endpoint_slice.ports])


@pytest.mark.parametrize(
    "endpoint_slice",
    [
        EndpointSlice(
            ObjectMeta(name="endpoint-slice"),
            "IPv4",
            [Endpoint(["10.0.0.0", "10.0.0.1"])],
        ),
        EndpointSlice(
            ObjectMeta(name="endpoint-slice-w-conditions"),
            "IPv4",
            [Endpoint(["10.0.0.0", "10.0.0.1"], EndpointConditions(False))],
        ),
        EndpointSlice(
            ObjectMeta(name="endpoint-slice-w-conditions"),
            "IPv4",
            [Endpoint(["10.0.0.0", "10.0.0.1"])],
            [EndpointPort("http", "TCP", 80),
             EndpointPort("ssh", "TCP", 22)],
        ),
 def __init__(self):
     super().__init__(
         storage_class=StorageClass(ObjectMeta(name="standard"),
                                    "efs.csi.aws.com"),
         volume_mode="Filesystem",
     )
Exemple #29
0
from avionix import ChartBuilder, ChartInfo, ObjectMeta, Value, Values
from avionix.kube.core import ConfigMap

config_map = ConfigMap(
    ObjectMeta(name="test-values"),
    {
        "my_value": Value("my_value"),
        "my_nested_value": Value("my.nested.value")
    },
)
values = Values({"my_value": "some_value", "my": {"nested": {"value": 0}}})
chart = ChartBuilder(
    ChartInfo(
        api_version="3.2.4",
        name="values_yaml_example",
        version="0.1.0",
        app_version="v1",
    ),
    [],
    values=values,
)
Exemple #30
0
def controller_revision():
    return ControllerRevision(ObjectMeta(name="test-controller-revision"),
                              {"test": "yes"}, 1)