From fd2acd87a358a9669f2a6201cfcc389c6e2ee564 Mon Sep 17 00:00:00 2001 From: John Buluba Date: Sun, 8 Mar 2020 01:39:34 +0200 Subject: [PATCH] Fix check_sa_exists not checking all service accounts in python library (#718) * Fix check_sa_exists not checking all service accounts * Fixed lint errors --- python/kfserving/kfserving/api/creds_utils.py | 4 +--- python/kfserving/test/test_creds_utils.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 python/kfserving/test/test_creds_utils.py diff --git a/python/kfserving/kfserving/api/creds_utils.py b/python/kfserving/kfserving/api/creds_utils.py index 0f34c9988f8..35984dae061 100644 --- a/python/kfserving/kfserving/api/creds_utils.py +++ b/python/kfserving/kfserving/api/creds_utils.py @@ -179,9 +179,7 @@ def check_sa_exists(namespace, service_account): '''Check if the specified service account existing.''' sa_list = client.CoreV1Api().list_namespaced_service_account(namespace=namespace) - sa_name_list = [] - for item in range(0, len(sa_list.items)-1): - sa_name_list.append(sa_list.items[item].metadata.name) + sa_name_list = [sa.metadata.name for sa in sa_list.items] if service_account in sa_name_list: return True diff --git a/python/kfserving/test/test_creds_utils.py b/python/kfserving/test/test_creds_utils.py new file mode 100644 index 00000000000..fc858602a2c --- /dev/null +++ b/python/kfserving/test/test_creds_utils.py @@ -0,0 +1,19 @@ +from unittest import mock + +from kubernetes.client import V1ServiceAccountList, V1ServiceAccount, V1ObjectMeta + +from kfserving.api.creds_utils import check_sa_exists + + +@mock.patch('kubernetes.client.CoreV1Api.list_namespaced_service_account') +def test_check_sa_exists(mock_client): + # Mock kubernetes client to return 2 accounts + accounts = V1ServiceAccountList( + items=[V1ServiceAccount(metadata=V1ObjectMeta(name=n)) for n in ['a', 'b']] + ) + mock_client.return_value = accounts + + # then a, b should exist, c should not + assert check_sa_exists('kubeflow', 'a') is True + assert check_sa_exists('kubeflow', 'b') is True + assert check_sa_exists('kubeflow', 'c') is False