CORD-3048 Unit Tests for Kubernetes Synchronizer

Change-Id: I0ff9146d544a2e0a212264b7d366500d6a51ff1c
diff --git a/xos/synchronizer/tests/test_config.yaml b/xos/synchronizer/tests/test_config.yaml
new file mode 100644
index 0000000..acd2ba7
--- /dev/null
+++ b/xos/synchronizer/tests/test_config.yaml
@@ -0,0 +1,29 @@
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+name: test-model-policies
+accessor:
+  username: xosadmin@opencord.org
+  password: "sample"
+  kind: "testframework"
+logging:
+  version: 1
+  handlers:
+    console:
+      class: logging.StreamHandler
+  loggers:
+    'multistructlog':
+      handlers:
+          - console
diff --git a/xos/synchronizer/tests/test_pull_pods.py b/xos/synchronizer/tests/test_pull_pods.py
new file mode 100644
index 0000000..672687f
--- /dev/null
+++ b/xos/synchronizer/tests/test_pull_pods.py
@@ -0,0 +1,283 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os, sys
+import unittest
+from mock import patch, PropertyMock, ANY, MagicMock
+from unit_test_common import setup_sync_unit_test
+
+def fake_init_kubernetes_client(self):
+    self.v1core = MagicMock()
+    self.v1apps = MagicMock()
+    self.v1batch = MagicMock()
+
+class TestPullPods(unittest.TestCase):
+
+    def setUp(self):
+        self.unittest_setup = setup_sync_unit_test(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
+                                                   globals(),
+                                                   [("kubernetes-service", "kubernetes.proto")] )
+
+        sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), "../pull_steps"))
+
+        from pull_pods import KubernetesServiceInstancePullStep
+        self.pull_step_class = KubernetesServiceInstancePullStep
+
+        self.service = KubernetesService()
+        self.trust_domain = TrustDomain(name="test-trust", owner=self.service)
+        self.principal = Principal(name="test-principal", trust_domain = self.trust_domain)
+        self.image = Image(name="test-image", tag="1.1", kind="container")
+
+    def tearDown(self):
+        sys.path = self.unittest_setup["sys_path_save"]
+
+    def test_read_obj_kind(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            pull_step = self.pull_step_class()
+            pull_step.v1apps.read_namespaced_replica_set.return_value = ["my_replica_set"]
+            pull_step.v1apps.read_namespaced_stateful_set.return_value = ["my_stateful_set"]
+            pull_step.v1apps.read_namespaced_daemon_set.return_value = ["my_daemon_set"]
+            pull_step.v1apps.read_namespaced_deployment.return_value = ["my_deployment"]
+            pull_step.v1batch.read_namespaced_job.return_value = ["my_job"]
+
+            obj = pull_step.read_obj_kind("ReplicaSet", "foo", self.trust_domain)
+            self.assertEqual(obj, ["my_replica_set"])
+
+            obj = pull_step.read_obj_kind("StatefulSet", "foo", self.trust_domain)
+            self.assertEqual(obj, ["my_stateful_set"])
+
+            obj = pull_step.read_obj_kind("DaemonSet", "foo", self.trust_domain)
+            self.assertEqual(obj, ["my_daemon_set"])
+
+            obj = pull_step.read_obj_kind("Deployment", "foo", self.trust_domain)
+            self.assertEqual(obj, ["my_deployment"])
+
+            obj = pull_step.read_obj_kind("Job", "foo", self.trust_domain)
+            self.assertEqual(obj, ["my_job"])
+
+    def test_get_controller_from_obj(self):
+        """ Setup an owner_reference chain: leaf --> StatefulSet --> Deployment. Calling get_controller_from_obj()
+            on the leaf should return the deployment.
+        """
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            leaf_obj = MagicMock()
+            leaf_obj.metadata.owner_references= [MagicMock(controller=True, name="my_stateful_set", kind="StatefulSet")]
+
+            ss_obj = MagicMock()
+            ss_obj.metadata.owner_references= [MagicMock(controller=True, name="my_deployment", kind="Deployment")]
+
+            dep_obj = MagicMock()
+            dep_obj.metadata.owner_references = []
+
+            pull_step = self.pull_step_class()
+            pull_step.v1apps.read_namespaced_stateful_set.return_value = ss_obj
+            pull_step.v1apps.read_namespaced_deployment.return_value = dep_obj
+
+            controller = pull_step.get_controller_from_obj(leaf_obj, self.trust_domain)
+            self.assertEqual(controller, dep_obj)
+
+    def test_get_slice_from_pod_exists(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client),\
+                patch.object(self.pull_step_class, "get_controller_from_obj") as get_controller_from_obj, \
+                patch.object(Slice.objects, "get_items") as slice_objects:
+            pull_step = self.pull_step_class()
+
+            myslice = Slice(name="myslice")
+
+            dep_obj = MagicMock()
+            dep_obj.metadata.name = myslice.name
+            get_controller_from_obj.return_value = dep_obj
+
+            slice_objects.return_value = [myslice]
+
+            pod = MagicMock()
+
+            slice = pull_step.get_slice_from_pod(pod, self.trust_domain, self.principal)
+            self.assertEqual(slice, myslice)
+
+    def test_get_slice_from_pod_noexist(self):
+        """ Call get_slice_from_pod() where not pre-existing slice is present. A new slice will be created, named
+            after the pod's controller.
+        """
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client),\
+                patch.object(self.pull_step_class, "get_controller_from_obj") as get_controller_from_obj, \
+                patch.object(Site.objects, "get_items") as site_objects:
+            pull_step = self.pull_step_class()
+
+            site_objects.return_value=[Site(name="mysite")]
+
+            dep_obj = MagicMock()
+            dep_obj.metadata.name = "my_other_slice"
+            get_controller_from_obj.return_value = dep_obj
+
+            pod = MagicMock()
+
+            slice = pull_step.get_slice_from_pod(pod, self.trust_domain, self.principal)
+            self.assertEqual(slice.name, "my_other_slice")
+            self.assertEqual(slice.trust_domain, self.trust_domain)
+            self.assertEqual(slice.principal, self.principal)
+            self.assertEqual(slice.xos_managed, False)
+
+    def test_get_trustdomain_from_pod_exists(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client), \
+             patch.object(TrustDomain.objects, "get_items") as trustdomain_objects:
+            pull_step = self.pull_step_class()
+
+            pod = MagicMock()
+            pod.metadata.namespace = self.trust_domain.name
+
+            trustdomain_objects.return_value = [self.trust_domain]
+
+            trustdomain = pull_step.get_trustdomain_from_pod(pod, owner_service=self.service)
+            self.assertEqual(trustdomain, self.trust_domain)
+
+    def test_get_trustdomain_from_pod_noexist(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            pull_step = self.pull_step_class()
+
+            pod = MagicMock()
+            pod.metadata.namespace = "new-trust"
+
+            trustdomain = pull_step.get_trustdomain_from_pod(pod, owner_service=self.service)
+            self.assertEqual(trustdomain.name, "new-trust")
+            self.assertEqual(trustdomain.owner, self.service)
+
+    def test_get_principal_from_pod_exists(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client), \
+             patch.object(Principal.objects, "get_items") as principal_objects:
+            pull_step = self.pull_step_class()
+
+            pod = MagicMock()
+            pod.spec.service_account = self.principal.name
+
+            principal_objects.return_value = [self.principal]
+
+            principal = pull_step.get_principal_from_pod(pod, trust_domain=self.trust_domain)
+            self.assertEqual(principal, self.principal)
+
+    def test_get_principal_from_pod_noexist(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            pull_step = self.pull_step_class()
+
+            pod = MagicMock()
+            pod.spec.service_account = "new-principal"
+
+            principal = pull_step.get_principal_from_pod(pod, trust_domain=self.trust_domain)
+            self.assertEqual(principal.name, "new-principal")
+            self.assertEqual(principal.trust_domain, self.trust_domain)
+
+    def test_get_image_from_pod_exists(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client), \
+             patch.object(Image.objects, "get_items") as image_objects:
+            pull_step = self.pull_step_class()
+
+            container = MagicMock()
+            container.image = "%s:%s" % (self.image.name, self.image.tag)
+
+            pod = MagicMock()
+            pod.spec.containers = [container]
+
+            image_objects.return_value = [self.image]
+
+            image = pull_step.get_image_from_pod(pod)
+            self.assertEqual(image, self.image)
+
+    def test_get_image_from_pod_noexist(self):
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            pull_step = self.pull_step_class()
+
+            container = MagicMock()
+            container.image = "new-image:2.3" \
+
+            pod = MagicMock()
+            pod.spec.containers = [container]
+
+            image = pull_step.get_image_from_pod(pod)
+            self.assertEqual(image.name, "new-image")
+            self.assertEqual(image.tag, "2.3")
+            self.assertEqual(image.kind, "container")
+
+    def make_pod(self, name, trust_domain, principal, image):
+        container = MagicMock()
+        container.image = "%s:%s" % (image.name, image.tag)
+
+        pod = MagicMock()
+        pod.metadata.name = name
+        pod.metadata.namespace = trust_domain.name
+        pod.spec.service_account = principal.name
+
+        return pod
+
+    def test_pull_records_new_pod(self):
+        """ A pod is found in k8s that does not exist in XOS. A new KubernetesServiceInstance sohuld be created
+        """
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client), \
+             patch.object(self.pull_step_class, "get_trustdomain_from_pod") as get_trustdomain, \
+             patch.object(self.pull_step_class, "get_principal_from_pod") as get_principal, \
+             patch.object(self.pull_step_class, "get_slice_from_pod") as get_slice, \
+             patch.object(self.pull_step_class, "get_image_from_pod") as get_image, \
+             patch.object(KubernetesService.objects, "get_items") as service_objects, \
+             patch.object(KubernetesServiceInstance.objects, "get_items") as si_objects, \
+             patch.object(KubernetesServiceInstance, "save", autospec=True) as ksi_save:
+
+            service_objects.return_value = [self.service]
+
+            slice = Slice(name="myslice")
+
+            get_trustdomain.return_value = self.trust_domain
+            get_principal.return_value = self.principal
+            get_slice.return_value = slice
+            get_image.return_value = self.image
+
+            pod = self.make_pod("my-pod", self.trust_domain, self.principal, self.image)
+            pod.status.pod_ip = "1.2.3.4"
+
+            pull_step = self.pull_step_class()
+            pull_step.v1core.list_pod_for_all_namespaces.return_value = MagicMock(items=[pod])
+
+            pull_step.pull_records()
+
+            self.assertEqual(ksi_save.call_count, 1)
+            saved_ksi = ksi_save.call_args[0][0]
+
+            self.assertEqual(saved_ksi.name, "my-pod")
+            self.assertEqual(saved_ksi.pod_ip, "1.2.3.4")
+            self.assertEqual(saved_ksi.owner, self.service)
+            self.assertEqual(saved_ksi.slice, slice)
+            self.assertEqual(saved_ksi.image, self.image)
+            self.assertEqual(saved_ksi.xos_managed, False)
+
+    def test_pull_records_missing_pod(self):
+        """ A pod is found in k8s that does not exist in XOS. A new KubernetesServiceInstance sohuld be created
+        """
+        with patch.object(self.pull_step_class, "init_kubernetes_client", new=fake_init_kubernetes_client), \
+                patch.object(KubernetesService.objects, "get_items") as service_objects, \
+                patch.object(KubernetesServiceInstance.objects, "get_items") as si_objects, \
+                patch.object(KubernetesServiceInstance, "delete", autospec=True) as ksi_delete:
+            service_objects.return_value = [self.service]
+
+            si = KubernetesServiceInstance(name="my-pod", owner=self.service, xos_managed=False)
+            si_objects.return_value = [si]
+
+            pull_step = self.pull_step_class()
+            pull_step.v1core.list_pod_for_all_namespaces.return_value = MagicMock(items=[])
+
+            pull_step.pull_records()
+
+            self.assertEqual(ksi_delete.call_count, 1)
+            deleted_ksi = ksi_delete.call_args[0][0]
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/xos/synchronizer/tests/test_sync_configmap.py b/xos/synchronizer/tests/test_sync_configmap.py
new file mode 100644
index 0000000..1ebd9e8
--- /dev/null
+++ b/xos/synchronizer/tests/test_sync_configmap.py
@@ -0,0 +1,123 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import sys
+import unittest
+from mock import patch, PropertyMock, ANY, MagicMock
+from unit_test_common import setup_sync_unit_test
+
+class ApiException(Exception):
+    def __init__(self, status, *args, **kwargs):
+        super(ApiException, self).__init__(*args, **kwargs)
+        self.status = status
+
+def fake_init_kubernetes_client(self):
+    self.kubernetes_client = MagicMock()
+    self.v1core = MagicMock()
+    self.ApiException = ApiException
+
+class TestSyncConfigmap(unittest.TestCase):
+
+    def setUp(self):
+        self.unittest_setup = setup_sync_unit_test(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
+                                                   globals(),
+                                                   [("kubernetes-service", "kubernetes.proto")] )
+
+        sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), "../steps"))
+
+        from sync_configmap import SyncKubernetesConfigMap
+        self.step_class = SyncKubernetesConfigMap
+
+        self.service = KubernetesService()
+        self.trust_domain = TrustDomain(name="test-trust", owner=self.service)
+
+    def tearDown(self):
+        sys.path = self.unittest_setup["sys_path_save"]
+
+    def test_get_config_map_exists(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            configmap = KubernetesConfigMap(trust_domain=self.trust_domain, name="test-configmap")
+
+            step = self.step_class()
+            map = MagicMock()
+            step.v1core.read_namespaced_config_map.return_value = map
+
+            result = step.get_config_map(configmap)
+
+            self.assertEqual(result, map)
+            step.v1core.read_namespaced_config_map.assert_called_with("test-configmap", "test-trust")
+
+    def test_get_config_map_noexist(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            configmap = KubernetesConfigMap(trust_domain=self.trust_domain, name="test-configmap")
+
+            step = self.step_class()
+            map = MagicMock()
+            step.v1core.read_namespaced_config_map.side_effect = step.ApiException(status=404)
+
+            result = step.get_config_map(configmap)
+
+            self.assertEqual(result, None)
+
+    def test_sync_record_create(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            data = {"foo": "bar"}
+            configmap = KubernetesConfigMap(trust_domain=self.trust_domain, name="test-configmap", data=json.dumps(data))
+
+            step = self.step_class()
+            step.v1core.read_namespaced_config_map.side_effect = step.ApiException(status=404)
+
+            map = MagicMock()
+            map.metadata.self_link="1234"
+            step.v1core.create_namespaced_config_map.return_value = map
+
+            step.sync_record(configmap)
+
+            step.v1core.create_namespaced_config_map.assert_called()
+            self.assertEqual(configmap.backend_handle, "1234")
+
+    def test_sync_record_update(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            data = {"foo": "bar"}
+            configmap = KubernetesConfigMap(trust_domain=self.trust_domain, name="test-configmap", data=json.dumps(data))
+
+            orig_map = MagicMock()
+            orig_map.data = {"foo": "not_bar"}
+            orig_map.metadata.self_link = "1234"
+
+            step = self.step_class()
+            step.v1core.read_namespaced_config_map.return_value = orig_map
+
+            new_map = MagicMock()
+            new_map.data = {"foo": "bar"}
+            new_map.metadata.self_link = "1234"
+
+            step.v1core.patch_namespaced_config_map.return_value = new_map
+
+            step.sync_record(configmap)
+
+            self.assertEqual(step.v1core.patch_namespaced_config_map.call_count, 1)
+            call_args = step.v1core.patch_namespaced_config_map.call_args[0]
+            self.assertEqual(call_args[0], "test-configmap")
+            self.assertEqual(call_args[1], "test-trust")
+            self.assertEqual(call_args[2].data, {"foo": "bar"})
+
+            self.assertEqual(configmap.backend_handle, "1234")
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/xos/synchronizer/tests/test_sync_kubernetesserviceinstance.py b/xos/synchronizer/tests/test_sync_kubernetesserviceinstance.py
new file mode 100644
index 0000000..9bf285a
--- /dev/null
+++ b/xos/synchronizer/tests/test_sync_kubernetesserviceinstance.py
@@ -0,0 +1,99 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import sys
+import unittest
+from mock import patch, PropertyMock, ANY, MagicMock
+from unit_test_common import setup_sync_unit_test
+
+class ApiException(Exception):
+    def __init__(self, status, *args, **kwargs):
+        super(ApiException, self).__init__(*args, **kwargs)
+        self.status = status
+
+def fake_init_kubernetes_client(self):
+    self.kubernetes_client = MagicMock()
+    self.v1core = MagicMock()
+    self.ApiException = ApiException
+
+class TestSyncKubernetesServiceInstance(unittest.TestCase):
+
+    def setUp(self):
+        self.unittest_setup = setup_sync_unit_test(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
+                                                   globals(),
+                                                   [("kubernetes-service", "kubernetes.proto")] )
+
+        self.MockObjectList = self.unittest_setup["MockObjectList"]
+
+        sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), "../steps"))
+
+        from sync_kubernetesserviceinstance import SyncKubernetesServiceInstance
+        self.step_class = SyncKubernetesServiceInstance
+
+        self.service = KubernetesService()
+        self.trust_domain = TrustDomain(owner=self.service, name="test-trust")
+        self.principal = Principal(name="test-principal", trust_domain=self.trust_domain)
+        self.slice = Slice(name="test-slice", trust_domain=self.trust_domain, principal=self.principal)
+        self.image = Image(name="test-image", tag="1.2", kind="container")
+
+    def tearDown(self):
+        sys.path = self.unittest_setup["sys_path_save"]
+
+    def test_get_pod_exists(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_si = KubernetesServiceInstance(name="test-instance", slice=self.slice)
+
+            step = self.step_class()
+            pod = MagicMock()
+            step.v1core.read_namespaced_pod.return_value = pod
+
+            result = step.get_pod(xos_si)
+
+            self.assertEqual(result, pod)
+            step.v1core.read_namespaced_pod.assert_called_with("test-instance", "test-trust")
+
+    def test_get_pod_noexist(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_si = KubernetesServiceInstance(name="test-instance", slice=self.slice)
+
+            step = self.step_class()
+            step.v1core.read_namespaced_pod.side_effect = step.ApiException(status=404)
+
+            result = step.get_pod(xos_si)
+
+            self.assertEqual(result, None)
+
+    def test_sync_record_create(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_si = KubernetesServiceInstance(name="test-instance", slice=self.slice, image=self.image)
+            xos_si.kubernetes_config_volume_mounts = self.MockObjectList([])
+            xos_si.kubernetes_secret_volume_mounts = self.MockObjectList([])
+
+            step = self.step_class()
+            step.v1core.read_namespaced_pod.side_effect = step.ApiException(status=404)
+
+            pod = MagicMock()
+            pod.metadata.self_link="1234"
+            step.v1core.create_namespaced_pod.return_value = pod
+
+            step.sync_record(xos_si)
+
+            step.v1core.create_namespaced_pod.assert_called()
+            self.assertEqual(xos_si.backend_handle, "1234")
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/xos/synchronizer/tests/test_sync_principal.py b/xos/synchronizer/tests/test_sync_principal.py
new file mode 100644
index 0000000..81f9b30
--- /dev/null
+++ b/xos/synchronizer/tests/test_sync_principal.py
@@ -0,0 +1,92 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import sys
+import unittest
+from mock import patch, PropertyMock, ANY, MagicMock
+from unit_test_common import setup_sync_unit_test
+
+class ApiException(Exception):
+    def __init__(self, status, *args, **kwargs):
+        super(ApiException, self).__init__(*args, **kwargs)
+        self.status = status
+
+def fake_init_kubernetes_client(self):
+    self.kubernetes_client = MagicMock()
+    self.v1core = MagicMock()
+    self.ApiException = ApiException
+
+class TestSyncPrincipal(unittest.TestCase):
+
+    def setUp(self):
+        self.unittest_setup = setup_sync_unit_test(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
+                                                   globals(),
+                                                   [("kubernetes-service", "kubernetes.proto")] )
+
+        sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), "../steps"))
+
+        from sync_principal import SyncPrincipal
+        self.step_class = SyncPrincipal
+
+        self.service = KubernetesService()
+        self.trust_domain = TrustDomain(owner=self.service, name="test-trust")
+
+    def tearDown(self):
+        sys.path = self.unittest_setup["sys_path_save"]
+
+    def test_get_service_account_exists(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_principal = Principal(name="test-principal", trust_domain=self.trust_domain)
+
+            step = self.step_class()
+            sa = MagicMock()
+            step.v1core.read_namespaced_service_account.return_value = sa
+
+            result = step.get_service_account(xos_principal)
+
+            self.assertEqual(result, sa)
+            step.v1core.read_namespaced_service_account.assert_called_with("test-principal", "test-trust")
+
+    def test_get_service_account_noexist(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_principal = Principal(name="test-principal", trust_domain=self.trust_domain)
+
+            step = self.step_class()
+            step.v1core.read_namespaced_service_account.side_effect = step.ApiException(status=404)
+
+            result = step.get_service_account(xos_principal)
+
+            self.assertEqual(result, None)
+
+    def test_sync_record_create(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_principal = Principal(name="test-principal", trust_domain=self.trust_domain)
+
+            step = self.step_class()
+            step.v1core.read_namespaced_service_account.side_effect = step.ApiException(status=404)
+
+            sa = MagicMock()
+            sa.metadata.self_link="1234"
+            step.v1core.create_namespaced_service_account.return_value = sa
+
+            step.sync_record(xos_principal)
+
+            step.v1core.create_namespaced_service_account.assert_called()
+            self.assertEqual(xos_principal.backend_handle, "1234")
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/xos/synchronizer/tests/test_sync_secret.py b/xos/synchronizer/tests/test_sync_secret.py
new file mode 100644
index 0000000..ba7b39e
--- /dev/null
+++ b/xos/synchronizer/tests/test_sync_secret.py
@@ -0,0 +1,123 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import sys
+import unittest
+from mock import patch, PropertyMock, ANY, MagicMock
+from unit_test_common import setup_sync_unit_test
+
+class ApiException(Exception):
+    def __init__(self, status, *args, **kwargs):
+        super(ApiException, self).__init__(*args, **kwargs)
+        self.status = status
+
+def fake_init_kubernetes_client(self):
+    self.kubernetes_client = MagicMock()
+    self.v1core = MagicMock()
+    self.ApiException = ApiException
+
+class TestSyncSecret(unittest.TestCase):
+
+    def setUp(self):
+        self.unittest_setup = setup_sync_unit_test(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
+                                                   globals(),
+                                                   [("kubernetes-service", "kubernetes.proto")] )
+
+        sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), "../steps"))
+
+        from sync_secret import SyncKubernetesSecret
+        self.step_class = SyncKubernetesSecret
+
+        self.service = KubernetesService()
+        self.trust_domain = TrustDomain(name="test-trust", owner=self.service)
+
+    def tearDown(self):
+        sys.path = self.unittest_setup["sys_path_save"]
+
+    def test_get_secret_exists(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_secret = KubernetesSecret(trust_domain=self.trust_domain, name="test-secret")
+
+            step = self.step_class()
+            secret = MagicMock()
+            step.v1core.read_namespaced_secret.return_value = secret
+
+            result = step.get_secret(xos_secret)
+
+            self.assertEqual(result, secret)
+            step.v1core.read_namespaced_secret.assert_called_with("test-secret", "test-trust")
+
+    def test_get_secret_noexist(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_secret = KubernetesSecret(trust_domain=self.trust_domain, name="test-secret")
+
+            step = self.step_class()
+            secret = MagicMock()
+            step.v1core.read_namespaced_secret.side_effect = step.ApiException(status=404)
+
+            result = step.get_secret(xos_secret)
+
+            self.assertEqual(result, None)
+
+    def test_sync_record_create(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            data = {"foo": "bar"}
+            xos_secret = KubernetesSecret(trust_domain=self.trust_domain, name="test-secret", data=json.dumps(data))
+
+            step = self.step_class()
+            step.v1core.read_namespaced_secret.side_effect = step.ApiException(status=404)
+
+            secret = MagicMock()
+            secret.metadata.self_link="1234"
+            step.v1core.create_namespaced_secret.return_value = secret
+
+            step.sync_record(xos_secret)
+
+            step.v1core.create_namespaced_secret.assert_called()
+            self.assertEqual(xos_secret.backend_handle, "1234")
+
+    def test_sync_record_update(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            data = {"foo": "bar"}
+            xos_secret = KubernetesSecret(trust_domain=self.trust_domain, name="test-secret", data=json.dumps(data))
+
+            orig_secret = MagicMock()
+            orig_secret.data = {"foo": "not_bar"}
+            orig_secret.metadata.self_link = "1234"
+
+            step = self.step_class()
+            step.v1core.read_namespaced_secret.return_value = orig_secret
+
+            new_secret = MagicMock()
+            new_secret.data = {"foo": "bar"}
+            new_secret.metadata.self_link = "1234"
+
+            step.v1core.patch_namespaced_secret.return_value = new_secret
+
+            step.sync_record(xos_secret)
+
+            self.assertEqual(step.v1core.patch_namespaced_secret.call_count, 1)
+            call_args = step.v1core.patch_namespaced_secret.call_args[0]
+            self.assertEqual(call_args[0], "test-secret")
+            self.assertEqual(call_args[1], "test-trust")
+            self.assertEqual(call_args[2].data, {"foo": "bar"})
+
+            self.assertEqual(xos_secret.backend_handle, "1234")
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/xos/synchronizer/tests/test_sync_service.py b/xos/synchronizer/tests/test_sync_service.py
new file mode 100644
index 0000000..550d0c2
--- /dev/null
+++ b/xos/synchronizer/tests/test_sync_service.py
@@ -0,0 +1,104 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import sys
+import unittest
+from mock import patch, PropertyMock, ANY, MagicMock
+from unit_test_common import setup_sync_unit_test
+
+class ApiException(Exception):
+    def __init__(self, status, *args, **kwargs):
+        super(ApiException, self).__init__(*args, **kwargs)
+        self.status = status
+
+def fake_init_kubernetes_client(self):
+    self.kubernetes_client = MagicMock()
+    self.v1core = MagicMock()
+    self.ApiException = ApiException
+
+class TestSyncService(unittest.TestCase):
+
+    def setUp(self):
+        self.unittest_setup = setup_sync_unit_test(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
+                                                   globals(),
+                                                   [("kubernetes-service", "kubernetes.proto")] )
+
+        sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), "../steps"))
+
+        self.MockObjectList = self.unittest_setup["MockObjectList"]
+
+        from sync_service import SyncService
+        self.step_class = SyncService
+
+        self.trust_domain = TrustDomain(name="test-trust")
+        self.service = KubernetesService()
+
+    def tearDown(self):
+        sys.path = self.unittest_setup["sys_path_save"]
+
+    def test_get_service_exists(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_service = Service(name="test-service")
+            xos_slice = Slice(service=xos_service, trust_domain=self.trust_domain)
+            xos_service.slices = self.MockObjectList([xos_slice])
+
+            step = self.step_class()
+            service = MagicMock()
+            step.v1core.read_namespaced_service.return_value = service
+
+            result = step.get_service(xos_service, self.trust_domain)
+
+            self.assertEqual(result, service)
+            step.v1core.read_namespaced_service.assert_called_with("test-service", "test-trust")
+
+    def test_get_service_noexist(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_service = Service(name="test-service")
+            xos_slice = Slice(service=xos_service, trust_domain=self.trust_domain)
+            xos_service.slices = self.MockObjectList([xos_slice])
+
+            step = self.step_class()
+            step.v1core.read_namespaced_service.side_effect = step.ApiException(status=404)
+
+            result = step.get_service(xos_service, self.trust_domain)
+
+            self.assertEqual(result, None)
+
+    def test_sync_record_create(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_service = Service(name="test-service")
+            xos_slice = Slice(service=xos_service, trust_domain=self.trust_domain)
+            xos_service.slices = self.MockObjectList([xos_slice])
+
+            xos_serviceport = ServicePort(service=xos_service, name="web", external_port=123, internal_port=345,
+                                          protocol="TCP")
+            xos_service.serviceports=self.MockObjectList([xos_serviceport])
+
+            step = self.step_class()
+            step.v1core.read_namespaced_service.side_effect = step.ApiException(status=404)
+
+            service = MagicMock()
+            service.metadata.self_link="1234"
+            step.v1core.create_namespaced_service.return_value = service
+
+            step.sync_record(xos_service)
+
+            step.v1core.create_namespaced_service.assert_called()
+            self.assertEqual(xos_service.backend_handle, "1234")
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/xos/synchronizer/tests/test_sync_trustdomain.py b/xos/synchronizer/tests/test_sync_trustdomain.py
new file mode 100644
index 0000000..1695b26
--- /dev/null
+++ b/xos/synchronizer/tests/test_sync_trustdomain.py
@@ -0,0 +1,91 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import sys
+import unittest
+from mock import patch, PropertyMock, ANY, MagicMock
+from unit_test_common import setup_sync_unit_test
+
+class ApiException(Exception):
+    def __init__(self, status, *args, **kwargs):
+        super(ApiException, self).__init__(*args, **kwargs)
+        self.status = status
+
+def fake_init_kubernetes_client(self):
+    self.kubernetes_client = MagicMock()
+    self.v1core = MagicMock()
+    self.ApiException = ApiException
+
+class TestSyncTrustDomain(unittest.TestCase):
+
+    def setUp(self):
+        self.unittest_setup = setup_sync_unit_test(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
+                                                   globals(),
+                                                   [("kubernetes-service", "kubernetes.proto")] )
+
+        sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), "../steps"))
+
+        from sync_trustdomain import SyncTrustDomain
+        self.step_class = SyncTrustDomain
+
+        self.service = KubernetesService()
+
+    def tearDown(self):
+        sys.path = self.unittest_setup["sys_path_save"]
+
+    def test_get_namespace_exists(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_trustdomain = TrustDomain(name="test-trust")
+
+            step = self.step_class()
+            td = MagicMock()
+            step.v1core.read_namespace.return_value = td
+
+            result = step.get_namespace(xos_trustdomain)
+
+            self.assertEqual(result, td)
+            step.v1core.read_namespace.assert_called_with("test-trust")
+
+    def test_get_config_namespace_noexist(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_trustdomain = TrustDomain(name="test-trust")
+
+            step = self.step_class()
+            step.v1core.read_namespace.side_effect = step.ApiException(status=404)
+
+            result = step.get_namespace(xos_trustdomain)
+
+            self.assertEqual(result, None)
+
+    def test_sync_record_create(self):
+        with patch.object(self.step_class, "init_kubernetes_client", new=fake_init_kubernetes_client):
+            xos_trustdomain = TrustDomain(name="test-trust")
+
+            step = self.step_class()
+            step.v1core.read_namespace.side_effect = step.ApiException(status=404)
+
+            td = MagicMock()
+            td.metadata.self_link="1234"
+            step.v1core.create_namespace.return_value = td
+
+            step.sync_record(xos_trustdomain)
+
+            step.v1core.create_namespace.assert_called()
+            self.assertEqual(xos_trustdomain.backend_handle, "1234")
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/xos/synchronizer/tests/unit_test_common.py b/xos/synchronizer/tests/unit_test_common.py
new file mode 100644
index 0000000..7ba2287
--- /dev/null
+++ b/xos/synchronizer/tests/unit_test_common.py
@@ -0,0 +1,84 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import sys
+
+def setup_sync_unit_test(test_path, globals_dict, models, config_fn="test_config.yaml"):
+    """ Perform the common steps associated with setting up a synchronizer unit test.
+           1) Add synchronizers/new_base to sys.path
+           2) Import xosconfig.Config and set it up to test_config.yaml in the current dir
+           3) Build the mock modelaccessor and import it
+           4) Import all model accessor classes into global space
+
+        Arguments:
+            test_path - path to the test case that is being run
+            globals_dict - a dictionary to add global models to
+            models - a list of pairs (service_name, xproto_name,
+            config_fn - filename of config file)
+
+        Returns:
+            Dictionary containing the following:
+                sys_path_save: the original sys.path
+                model_accessor: model accessor class
+                Config: the Config object
+                xos_dir: xos directory
+                services_dir: services directory
+    """
+    def get_models_fn(services_dir, service_name, xproto_name):
+        name = os.path.join(service_name, "xos", xproto_name)
+        if os.path.exists(os.path.join(services_dir, name)):
+            return name
+        else:
+            name = os.path.join(service_name, "xos", "synchronizer", "models", xproto_name)
+            if os.path.exists(os.path.join(services_dir, name)):
+                return name
+        raise Exception("Unable to find service=%s xproto=%s" % (service_name, xproto_name))
+
+    sys_path_save = sys.path
+
+    xos_dir = os.path.join(test_path, "../../..")
+    if not os.path.exists(os.path.join(test_path, "new_base")):
+        xos_dir = os.path.join(test_path, "../../../../../../orchestration/xos/xos")
+        services_dir = os.path.join(xos_dir, "../../xos_services")
+    sys.path.append(xos_dir)
+    sys.path.append(os.path.join(xos_dir, 'synchronizers', 'new_base'))
+
+    # Setting up the config module
+    from xosconfig import Config
+    config = os.path.join(test_path, config_fn)
+    Config.clear()
+    Config.init(config, "synchronizer-config-schema.yaml")
+
+    xprotos = []
+    for (service_name, xproto_name) in models:
+        xprotos.append(get_models_fn(services_dir, "kubernetes-service", "kubernetes.xproto"))
+
+    from synchronizers.new_base.mock_modelaccessor_build import build_mock_modelaccessor
+    build_mock_modelaccessor(xos_dir, services_dir, xprotos)
+    import synchronizers.new_base.modelaccessor
+    from synchronizers.new_base.modelaccessor import model_accessor
+    from mock_modelaccessor import MockObjectList
+
+    # import all class names to globals
+    for (k, v) in model_accessor.all_model_classes.items():
+        globals_dict[k] = v
+
+    return {"sys_path_save": sys_path_save,
+            "model_accessor": model_accessor,
+            "Config": Config,
+            "xos_dir": xos_dir,
+            "services_dir": services_dir,
+            "MockObjectList": MockObjectList}