Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_ns_create_new(self, mock_ns_read, mock_api, mock_log):
# TODO: We should ideally replicate the correct API exception
mock_ns_read.side_effect = ApiException()
ns_create("a-namespace")
mock_ns_read.assert_called_once_with("a-namespace")
mock_api.create_namespace.assert_called_once()
mock_log.info.assert_called_once_with('Created namespace "a-namespace"')
def wait_to_deployment_to_be_deleted(deployment_name, name_space, time_out=None):
total_sleep_time = 0
while True:
try:
resp = client.AppsV1Api().read_namespaced_deployment(name=deployment_name, namespace=name_space)
except ApiException as e:
if e.status == 404:
print("Total time waiting for delete deployment {0}: {1} sec".format(deployment_name, total_sleep_time))
break
time.sleep(1)
total_sleep_time += 1
if time_out and total_sleep_time > time_out:
raise Exception("Timeout waiting to delete deployment")
def test_create_and_wait_replicaset_fail_create(self):
self.config_cls.reset_mock()
self.api_cls.reset_mock()
self.client_cls.reset_mock()
self.client.create_namespaced_replica_set.side_effect = [
rest.ApiException(status=500, reason="Test")
]
self.assertRaises(
rest.ApiException,
self.k8s_client.create_replicaset,
image="test/image",
namespace="ns",
replicas=2,
status_wait=True
)
(self.client.create_namespaced_replica_set
.assert_called_once())
self.assertEqual(
0,
self.client.read_namespaced_replica_set.call_count
def test_clusterinit_run_cmd_pods_init_failure(caplog):
fake_http_resp = FakeHTTPResponse(500, "fake reason", "fake body")
fake_api_exception = K8sApiException(http_resp=fake_http_resp)
with patch('intel.k8s.create_pod',
MagicMock(side_effect=fake_api_exception)):
with pytest.raises(SystemExit):
clusterinit.run_pods(None, ["init"], "fake_img",
"Never", "fake-conf-dir", "fake-install-dir",
"2", "2", ["fakenode"], "", "", "vertical",
"vertical", "default", "-1")
exp_err = "Exception when creating pod for ['init'] command(s)"
exp_log_err = get_expected_log_error(exp_err)
caplog_tuple = caplog.record_tuples
assert caplog_tuple[1][2] == exp_log_err
def test_raises_api_error(client_mock, resource, namespace, status):
error = kubernetes.client.rest.ApiException(status=status)
apicls_mock = client_mock.CustomObjectsApi
apicls_mock.return_value.list_cluster_custom_object.side_effect = error
apicls_mock.return_value.list_namespaced_custom_object.side_effect = error
fn = make_list_fn(resource=resource, namespace=namespace)
with pytest.raises(kubernetes.client.rest.ApiException) as e:
fn(opt1='val1', opt2=123)
assert e.value.status == status
def test_delete_pod_failed(self):
resp = mock.MagicMock()
resp.status.conditions = []
self.client.create_pod.return_value = "test"
self.client.get_pod.return_value = resp
self.client.delete_pod.side_effect = [
rest.ApiException(status=500, reason="Test")
]
self.assertRaises(rest.ApiException, self.scenario.run, "test/image")
self.client.create_pod.assert_called_once_with(
"test/image",
command=None,
namespace="ns",
status_wait=True
)
self.client.get_pod.assert_called_once_with(
"test",
namespace="ns"
)
self._apply_delta(api, current, target)
for (api_version, kind, name), action in six.iteritems(self.actions):
if action != 'delete':
continue
api = self.get_api(api_version)
underscored = _under_score(kind)
if self.dry_run:
log.info("{}: {}/{}".format(action.title(), underscored, name))
else:
try:
log.debug("{}: {}/{}".format(action.title(), underscored, name))
deleter = self.get_method(api, 'delete', 'namespaced', underscored)
deleter(name, self.namespace, client.V1DeleteOptions(orphan_dependents=False))
except client.rest.ApiException as e:
if e.status == 404:
pass
else:
six.reraise(*sys.exc_info())
def list(self, namespace):
pretty = 'pretty_example'
limit = 56
timeout_seconds = 56
try:
return self.batch_client.list_namespaced_job(
namespace, pretty=pretty, limit=limit, timeout_seconds=timeout_seconds)
except ApiException as e:
print("Exception when calling BatchV1Api->list_namespaced_job: %s\n" % e)
def _delete_k8s_job(self, pod_name, yaml_spec):
""" _delete_k8s_job deletes a pod """
try:
api_response = self._corev1.delete_namespaced_pod(pod_name, yaml_spec['metadata']['namespace'], body=k8s_client.V1DeleteOptions())
except k8s_client.rest.ApiException as e:
logging.exception('Exception when calling CoreV1Api->delete_namespaced_pod: {}\n'.format(str(e)))
msg = "{0}\n{1}".format(type(e).__name__, str(e))
raise ApiException(status=0, reason=msg)
if _preload_content:
r = RESTResponse(r)
# In the python 3, the response.data is bytes.
# we need to decode it to string.
if six.PY3:
r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s", r.data)
if not 200 <= r.status <= 299:
raise ApiException(http_resp=r)
return r