summaryrefslogtreecommitdiffstats
path: root/pgaas
diff options
context:
space:
mode:
authorTony Hansen <tony@att.com>2017-09-27 19:25:05 +0000
committerTony Hansen <tony@att.com>2017-09-27 20:25:42 +0000
commitd86ed03e595f16bdff1e802870f51ad26fe37359 (patch)
treea6355f14ebbdbbe0f4300c0e5395aa0042445af6 /pgaas
parent4eff192847e2db2195080182baf2e6d318c6d4ae (diff)
add unit tests to pgaas_plugin
plus various small fixes to get unit tests to pass Change-Id: I9ec786c5a40cb82d14ec72504d6ad4703a442a1a Signed-off-by: Tony Hansen <tony@att.com> Issue-Id: CCSDK-18 Signed-off-by: Tony Hansen <tony@att.com>
Diffstat (limited to 'pgaas')
-rw-r--r--pgaas/pgaas/pgaas_plugin.py19
-rw-r--r--pgaas/pom.xml4
-rw-r--r--pgaas/tests/psycopg2.py53
-rw-r--r--pgaas/tests/test_plugin.py145
-rw-r--r--pgaas/tox.ini28
5 files changed, 243 insertions, 6 deletions
diff --git a/pgaas/pgaas/pgaas_plugin.py b/pgaas/pgaas/pgaas_plugin.py
index dd1928b..bfeeba0 100644
--- a/pgaas/pgaas/pgaas_plugin.py
+++ b/pgaas/pgaas/pgaas_plugin.py
@@ -94,6 +94,11 @@ sys.path = opath
"""
+OPT_MANAGER_RESOURCES = "/opt/manager/resources"
+
+def setOptManagerResources(o):
+ global OPT_MANAGER_RESOURCES
+ OPT_MANAGER_RESOURCES = o
def safestr(s):
return urllib.quote(str(s), '')
@@ -178,7 +183,8 @@ def rootconn(data, dbname='postgres'):
connecting to the specified database
"""
debug("rootconn(..data..,{0})".format(safestr(dbname)))
- return doconn(rootdesc(data, dbname))
+ ret = doconn(rootdesc(data, dbname))
+ return ret
def onedesc(data, dbname, role, access):
"""
@@ -253,7 +259,8 @@ def getclusterinfo(wfqdn, reuse, rfqdn, related):
if len(related) != 0:
raiseNonRecoverableError('Cluster SSH keypair must not be specified when using an existing cluster')
try:
- with open('/opt/manager/resources/pgaas/{0}'.format(wfqdn).lower(), 'r') as f:
+ fn = '{0}/pgaas/{1}'.format(OPT_MANAGER_RESOURCES, wfqdn).lower()
+ with open('{0}/pgaas/{1}'.format(OPT_MANAGER_RESOURCES, wfqdn).lower(), 'r') as f:
data = json.load(f)
data['rw'] = wfqdn
return data
@@ -270,16 +277,16 @@ def getclusterinfo(wfqdn, reuse, rfqdn, related):
data = { 'ro': rfqdn, 'pubkey': related[0].instance.runtime_properties['public'], 'data': related[0].instance.runtime_properties['base64private'] }
os.umask(077)
try:
- os.makedirs('/opt/manager/resources/pgaas')
+ os.makedirs('{0}/pgaas'.format(OPT_MANAGER_RESOURCES))
except:
pass
try:
- with open('/opt/manager/resources/pgaas/{0}'.format(wfqdn).lower(), 'w') as f:
+ with open('{0}/pgaas/{1}'.format(OPT_MANAGER_RESOURCES, wfqdn).lower(), 'w') as f:
f.write(json.dumps(data))
except Exception as e:
warn("Error: {0}".format(e))
warn("Stack: {0}".format(traceback.format_exc()))
- raiseNonRecoverableError('Cannot write cluster information to /opt/manager/resources/pgaas: fqdn={0}, err={1}'.format(safestr(wfqdn),e))
+ raiseNonRecoverableError('Cannot write cluster information to {0}/pgaas: fqdn={1}, err={2}'.format(OPT_MANAGER_RESOURCES, safestr(wfqdn),e))
data['rw'] = wfqdn
return(data)
@@ -311,7 +318,7 @@ def rm_pgaas_cluster(**kwargs):
warn("rm_pgaas_cluster()")
wfqdn = ctx.node.properties['writerfqdn']
if chkfqdn(wfqdn) and not ctx.node.properties['use_existing']:
- os.remove('/opt/manager/resources/pgaas/{0}'.format(wfqdn))
+ os.remove('{0}/pgaas/{1}'.format(OPT_MANAGER_RESOURCES, wfqdn))
warn('All done')
except Exception as e:
ctx.logger.warn("Error: {0}".format(e))
diff --git a/pgaas/pom.xml b/pgaas/pom.xml
index 8a934ac..bbe6f70 100644
--- a/pgaas/pom.xml
+++ b/pgaas/pom.xml
@@ -43,9 +43,13 @@ limitations under the License.
<!-- path, in repo, to store type file -->
<typefile.dest>type_files/pgaas/pgaas_types.yaml</typefile.dest>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <sonar.skip>true</sonar.skip>
<sonar.sources>.</sonar.sources>
<!-- customize the SONARQUBE URL -->
<sonar.host.url>http://localhost:9000</sonar.host.url>
+ <sonar.junit.reportsPath>**/xunit-results.xml</sonar.junit.reportsPath>
+ <sonar.python.coverage.reportPath>**/coverage.xml</sonar.python.coverage.reportPath>
+ <sonar.exclusions>tests/*</sonar.exclusions>
<!-- below are language dependent -->
<!-- for Python -->
<sonar.language>py</sonar.language>
diff --git a/pgaas/tests/psycopg2.py b/pgaas/tests/psycopg2.py
new file mode 100644
index 0000000..fab5333
--- /dev/null
+++ b/pgaas/tests/psycopg2.py
@@ -0,0 +1,53 @@
+# ============LICENSE_START====================================================
+# org.onap.ccsdk
+# =============================================================================
+# Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
+# =============================================================================
+# 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.
+# ============LICENSE_END======================================================
+
+"""
+
+This is a mock psycopg2 module.
+
+"""
+
+class csr(object):
+ def __init__(self, **kwargs):
+ pass
+
+ def execute(self, cmd, exc = None):
+ pass
+
+ def close(self):
+ pass
+
+ def __iter__(self):
+ return iter([])
+
+class conn(object):
+ def __init__(self, **kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ pass
+
+ def cursor(self):
+ return csr()
+
+def connect(**kwargs):
+ return conn()
+
diff --git a/pgaas/tests/test_plugin.py b/pgaas/tests/test_plugin.py
new file mode 100644
index 0000000..5561f16
--- /dev/null
+++ b/pgaas/tests/test_plugin.py
@@ -0,0 +1,145 @@
+# ============LICENSE_START====================================================
+# org.onap.ccsdk
+# =============================================================================
+# Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
+# =============================================================================
+# 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.
+# ============LICENSE_END======================================================
+
+import pytest
+import socket
+import psycopg2
+import pgaas.pgaas_plugin
+from cloudify.mocks import MockCloudifyContext
+from cloudify.mocks import MockNodeContext
+from cloudify.mocks import MockNodeInstanceContext
+from cloudify.mocks import MockRelationshipSubjectContext
+from cloudify.state import current_ctx
+from cloudify.exceptions import NonRecoverableError
+from cloudify import ctx
+
+import sys, os
+sys.path.append(os.path.realpath(os.path.dirname(__file__)))
+
+class MockKeyPair(object):
+ def __init__(self, type_hierarchy=None, target=None):
+ self._type_hierarchy = type_hierarchy
+ self._target = target
+
+ @property
+ def type_hierarchy(self):
+ return self._type_hierarchy
+
+ @property
+ def target(self):
+ return self._target
+
+class MockInstance(object):
+ def __init__(self, instance=None):
+ self._instance = instance
+
+ @property
+ def instance(self):
+ return self._instance
+
+class MockRuntimeProperties(object):
+ def __init__(self, runtime_properties=None):
+ self._runtime_properties = runtime_properties
+
+ @property
+ def runtime_properties(self):
+ return self._runtime_properties
+
+def _connect(h,p):
+ return { }
+
+def set_mock_context(msg, monkeypatch):
+ print("================ %s ================" % msg)
+ os.system("echo Before test; ls -l /tmp/pgaas") #### DELETE
+ props = {
+ 'writerfqdn': 'test.bar.example.com',
+ 'use_existing': False,
+ 'readerfqdn': 'test-ro.bar.example.com',
+ 'name': 'testdb'
+ }
+
+ sshkeyprops = {
+ 'public': "testpub",
+ 'base64private': "testpriv"
+ }
+
+ mock_ctx = MockCloudifyContext(node_id='test_node_id', node_name='test_node_name',
+ properties=props,
+ relationships = [
+ MockKeyPair(type_hierarchy =
+ [ "dcae.relationships.pgaas_cluster_uses_sshkeypair" ],
+ target= MockInstance(
+ MockRuntimeProperties(sshkeyprops)) )
+ ],
+ runtime_properties = {
+ "admin": { "user": "admin_user" },
+ "user": { "user": "user_user" },
+ "viewer": { "user": "viewer_user" }
+ }
+ )
+ current_ctx.set(mock_ctx)
+ monkeypatch.setattr(socket.socket, 'connect', _connect)
+ # monkeypatch.setattr(psycopg2, 'connect', _connect)
+ pgaas.pgaas_plugin.setOptManagerResources("/tmp")
+
+
+
+@pytest.mark.dependency()
+def test_add_pgaas_cluster(monkeypatch):
+ try:
+ set_mock_context('test_add_pgaas_cluster', monkeypatch)
+ pgaas.pgaas_plugin.add_pgaas_cluster(args={})
+ finally:
+ current_ctx.clear()
+ os.system("echo After test; ls -l /tmp/pgaas") #### DELETE
+
+class MockSocket(object):
+ def __init__(self):
+ pass
+ def connect(self,host=None,port=None):
+ pass
+ def close(self):
+ pass
+
+@pytest.mark.dependency(depends=['test_add_pgaas_cluster'])
+def test_add_database(monkeypatch):
+ try:
+ set_mock_context('test_add_database', monkeypatch)
+ pgaas.pgaas_plugin.create_database(args={})
+ finally:
+ current_ctx.clear()
+ os.system("echo After test; ls -l /tmp/pgaas") #### DELETE
+
+@pytest.mark.dependency(depends=['test_add_database'])
+def test_delete_database(monkeypatch):
+ try:
+ set_mock_context('test_delete_database', monkeypatch)
+ pgaas.pgaas_plugin.delete_database(args={})
+ finally:
+ current_ctx.clear()
+ os.system("echo After test; ls -l /tmp/pgaas") #### DELETE
+
+@pytest.mark.dependency(depends=['test_delete_database'])
+def test_rm_pgaas_cluster(monkeypatch):
+ try:
+ set_mock_context('test_rm_pgaas_cluster', monkeypatch)
+ pgaas.pgaas_plugin.rm_pgaas_cluster(args={})
+ finally:
+ current_ctx.clear()
+ os.system("echo After test; ls -l /tmp/pgaas") #### DELETE
+
diff --git a/pgaas/tox.ini b/pgaas/tox.ini
new file mode 100644
index 0000000..884c079
--- /dev/null
+++ b/pgaas/tox.ini
@@ -0,0 +1,28 @@
+# ============LICENSE_START====================================================
+# org.onap.ccsdk
+# =============================================================================
+# Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
+# =============================================================================
+# 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.
+# ============LICENSE_END======================================================
+
+[tox]
+envlist = py27
+[testenv]
+deps=
+ pytest
+ cloudify==3.4
+ requests
+ coverage
+ pytest-cov
+commands=pytest --junitxml xunit-results.xml --cov {envsitepackagesdir}/pgaas --cov-report=xml