|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from unittest.mock import patch, MagicMock, ANY, call |
| 3 | + |
| 4 | +import pytest |
| 5 | +from chaoslib.exceptions import ActivityFailed |
| 6 | +from kubernetes.client.models import V1DeploymentList, V1Deployment, V1ObjectMeta |
| 7 | + |
| 8 | +from chaosk8s.deployment.actions import create_deployment, delete_deployment, scale_deployment |
| 9 | + |
| 10 | + |
| 11 | +@patch('chaosk8s.has_local_config_file', autospec=True) |
| 12 | +def test_cannot_process_other_than_yaml_and_json(has_conf): |
| 13 | + has_conf.return_value = False |
| 14 | + path = "./tests/fixtures/invalid-k8s.txt" |
| 15 | + with pytest.raises(ActivityFailed) as excinfo: |
| 16 | + create_deployment(spec_path=path) |
| 17 | + assert "cannot process {path}".format(path=path) in str(excinfo) |
| 18 | + |
| 19 | + |
| 20 | +@patch('builtins.open', autospec=True) |
| 21 | +@patch('chaosk8s.deployment.actions.json', autospec=True) |
| 22 | +@patch('chaosk8s.deployment.actions.create_k8s_api_client', autospec=True) |
| 23 | +@patch('chaosk8s.deployment.actions.client', autospec=True) |
| 24 | +def test_create_deployment(client, api, json, open): |
| 25 | + v1 = MagicMock() |
| 26 | + client.AppsV1beta1Api.return_value = v1 |
| 27 | + json.loads.return_value = {"Kind": "Deployment"} |
| 28 | + |
| 29 | + create_deployment(spec_path="depl.json") |
| 30 | + |
| 31 | + v1.create_namespaced_deployment.assert_called_with(ANY, body=json.loads.return_value) |
| 32 | + |
| 33 | + |
| 34 | +@patch('chaosk8s.deployment.actions.create_k8s_api_client', autospec=True) |
| 35 | +@patch('chaosk8s.deployment.actions.client', autospec=True) |
| 36 | +def test_delete_deployment(client, api): |
| 37 | + depl1 = V1Deployment(metadata=V1ObjectMeta(name="depl1")) |
| 38 | + depl2 = V1Deployment(metadata=V1ObjectMeta(name="depl2")) |
| 39 | + v1 = MagicMock() |
| 40 | + client.AppsV1beta1Api.return_value = v1 |
| 41 | + v1.list_namespaced_deployment.return_value = V1DeploymentList(items=(depl1, depl2)) |
| 42 | + |
| 43 | + delete_deployment("fake_name", "fake_ns") |
| 44 | + |
| 45 | + v1.list_namespaced_deployment.assert_called_with("fake_ns", label_selector=ANY) |
| 46 | + v1.delete_namespaced_deployment.assert_has_calls( |
| 47 | + calls=[ |
| 48 | + call(depl1.metadata.name, "fake_ns", ANY), |
| 49 | + call(depl2.metadata.name, "fake_ns", ANY) |
| 50 | + ], |
| 51 | + any_order=True |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +@patch('chaosk8s.deployment.actions.create_k8s_api_client', autospec=True) |
| 56 | +@patch('chaosk8s.deployment.actions.client', autospec=True) |
| 57 | +def test_scale_deployment(client, api): |
| 58 | + v1 = MagicMock() |
| 59 | + client.ExtensionsV1beta1Api.return_value = v1 |
| 60 | + |
| 61 | + scale_deployment("fake", 3, "fake_ns") |
| 62 | + |
| 63 | + body = {"spec": {"replicas": 3}} |
| 64 | + v1.patch_namespaced_deployment_scale.assert_called_with("fake", namespace="fake_ns", body=body) |
0 commit comments