Test refactoring

Added mock based unit tests for maasservice module, baseopenstack
module and changed all other tests in compliance with latest
refactoring.
This commit is contained in:
trobert2 2014-02-19 15:16:35 +02:00
parent 63f22383aa
commit d61826a0c6
25 changed files with 594 additions and 363 deletions

View File

@ -47,7 +47,7 @@ def get_fake_metadata_json(version):
"IODpCTrT3vsPRG3xz7CppR+vGi/1gLXHtJCRj"
"frHwkY6cXyhypNmkU99K/wMqSv30vsDwdnsQ1"
"q3YhLarMHB Generated by Nova\n",
"name": "windows"},
0: "windows"},
"network_config": {"content_path": "network",
'debian_config': 'iface eth0 inet static'
'address 10.11.12.13'

View File

@ -0,0 +1,161 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Cloudbase Solutions Srl
#
# 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 importlib
import mock
import posixpath
import sys
import unittest
from cloudbaseinit.metadata.services import base
from oslo.config import cfg
CONF = cfg.CONF
_ctypes_mock = mock.MagicMock()
mock_dict = {'ctypes': _ctypes_mock}
class BaseOpenStackServiceTest(unittest.TestCase):
@mock.patch.dict(sys.modules, mock_dict)
def setUp(self):
self.baseopenstackservice = importlib.import_module(
"cloudbaseinit.metadata.services.baseopenstackservice")
CONF.set_override('retry_count_interval', 0)
self._service = self.baseopenstackservice.BaseOpenStackService()
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_cache_data")
def test_get_content(self, mock_get_cache_data):
response = self._service.get_content('fake name')
path = posixpath.join('openstack', 'content', 'fake name')
mock_get_cache_data.assert_called_once_with(path)
self.assertEqual(response, mock_get_cache_data())
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_cache_data")
def test_get_user_data(self, mock_get_cache_data):
response = self._service.get_user_data()
path = posixpath.join('openstack', 'latest', 'user_data')
mock_get_cache_data.assert_called_once_with(path)
self.assertEqual(response, mock_get_cache_data())
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_cache_data")
@mock.patch('json.loads')
def _test_get_meta_data(self, mock_loads, mock_get_cache_data, data):
mock_get_cache_data.return_value = data
response = self._service._get_meta_data(
version='fake version')
path = posixpath.join('openstack', 'fake version', 'meta_data.json')
mock_get_cache_data.assert_called_with(path)
if type(data) is str:
mock_loads.assert_called_once_with(mock_get_cache_data())
self.assertEqual(response, mock_loads())
else:
self.assertEqual(response, data)
def test_get_meta_data_string(self):
self._test_get_meta_data(data='fake data')
def test_get_meta_data_dict(self):
self._test_get_meta_data(data={'fake': 'data'})
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_meta_data")
def test_get_instance_id(self, mock_get_meta_data):
response = self._service.get_instance_id()
mock_get_meta_data.assert_called_once_with()
mock_get_meta_data().get.assert_called_once_with('uuid')
self.assertEqual(response, mock_get_meta_data().get())
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_meta_data")
def test_get_host_name(self, mock_get_meta_data):
response = self._service.get_host_name()
mock_get_meta_data.assert_called_once_with()
mock_get_meta_data().get.assert_called_once_with('hostname')
self.assertEqual(response, mock_get_meta_data().get())
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_meta_data")
def test_get_public_keys(self, mock_get_meta_data):
response = self._service.get_public_keys()
mock_get_meta_data.assert_called_once_with()
mock_get_meta_data().get.assert_called_once_with('public_keys')
self.assertEqual(response, mock_get_meta_data().get().values())
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_meta_data")
def test_get_network_config(self, mock_get_meta_data):
response = self._service.get_network_config()
mock_get_meta_data.assert_called_once_with()
mock_get_meta_data().get.assert_called_once_with('network_config')
self.assertEqual(response, mock_get_meta_data().get())
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_meta_data")
def _test_get_admin_password(self, mock_get_meta_data, meta_data):
mock_get_meta_data.return_value = meta_data
response = self._service.get_admin_password()
mock_get_meta_data.assert_called_once_with()
if meta_data and 'admin_pass' in meta_data:
self.assertEqual(response, meta_data['admin_pass'])
elif meta_data and 'admin_pass' in meta_data.get('meta'):
self.assertEqual(response, meta_data.get('meta')['admin_pass'])
else:
self.assertEqual(response, None)
def test_get_admin_pass(self):
self._test_get_admin_password(meta_data={'admin_pass': 'fake pass'})
def test_get_admin_pass_in_meta(self):
self._test_get_admin_password(
meta_data={'meta': {'admin_pass': 'fake pass'}})
def test_get_admin_pass_no_pass(self):
self._test_get_admin_password(meta_data={})
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService._get_meta_data")
@mock.patch("cloudbaseinit.metadata.services.baseopenstackservice"
".BaseOpenStackService.get_user_data")
def _test_get_client_auth_certs(self, mock_get_user_data,
mock_get_meta_data, meta_data,
ret_value=None):
mock_get_meta_data.return_value = meta_data
mock_get_user_data.side_effect = [ret_value]
response = self._service.get_client_auth_certs()
mock_get_meta_data.assert_called_once_with()
if 'meta' in meta_data:
self.assertEqual(response, ['fake cert'])
elif type(ret_value) is str and ret_value.startswith(
self.baseopenstackservice.x509.PEM_HEADER):
mock_get_user_data.assert_called_once_with()
self.assertEqual(response, [ret_value])
elif ret_value is base.NotExistingMetadataException:
self.assertEqual(response, None)
def test_get_client_auth_certs(self):
self._test_get_client_auth_certs(
meta_data={'meta': {'admin_cert0': 'fake cert'}})
def test_get_client_auth_certs_no_cert_data(self):
self._test_get_client_auth_certs(
meta_data={}, ret_value=self.baseopenstackservice.x509.PEM_HEADER)
def test_get_client_auth_certs_no_cert_data_exception(self):
self._test_get_client_auth_certs(
meta_data={}, ret_value=base.NotExistingMetadataException)

View File

@ -1,145 +0,0 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Cloudbase Solutions Srl
#
# 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 mock
import os
import unittest
from oslo.config import cfg
from cloudbaseinit.metadata.services import ec2service
CONF = cfg.CONF
class Ec2ServiceTest(unittest.TestCase):
def setUp(self):
self._ec2service = ec2service.EC2Service()
@mock.patch('cloudbaseinit.metadata.services.ec2service.EC2Service'
'.get_meta_data')
def _test_load(self, mock_get_meta_data, side_effect):
mock_get_meta_data.side_effect = [side_effect]
response = self._ec2service.load()
mock_get_meta_data.assert_called_once_with('openstack')
if side_effect is Exception:
self.assertFalse(response)
else:
self.assertTrue(response)
def test_load_exception(self):
self._test_load(side_effect=Exception)
def test_load(self):
self._test_load(side_effect='fake data')
@mock.patch('posixpath.join')
@mock.patch('urllib2.Request')
@mock.patch('urllib2.urlopen')
@mock.patch('cloudbaseinit.metadata.services.ec2service.EC2Service'
'._load_public_keys')
@mock.patch('cloudbaseinit.metadata.services.ec2service.EC2Service'
'._check_EC2')
@mock.patch('cloudbaseinit.metadata.services.ec2service.EC2Service'
'._get_EC2_value')
def _test_get_data(self, mock_get_EC2_value, mock_check_EC2,
mock_load_public_keys, mock_urlopen,
mock_Request, mock_join, check_ec2, data_type):
mock_path = mock.MagicMock()
mock_req = mock.MagicMock()
mock_response = mock.MagicMock()
fake_path = os.path.join('fake', 'path')
mock_join.return_value = fake_path
mock_check_EC2.return_value = check_ec2
mock_Request.return_value = mock_req
mock_urlopen.return_value = mock_response
mock_response.read.return_value = 'fake data'
mock_path.endswith.return_value = data_type
if check_ec2 is None:
self.assertRaises(Exception, self._ec2service._get_data,
mock_path)
elif data_type is 'meta_data.json':
response = self._ec2service._get_data(mock_path)
print response
for key in ec2service.ec2nodes:
mock_get_EC2_value.assert_called_with(key)
mock_load_public_keys.assert_called_with()
elif data_type is 'user_data':
response = self._ec2service._get_data(mock_path)
mock_join.assert_called_with(CONF.ec2_metadata_base_url,
'user-data')
mock_Request.assert_called_once_with(fake_path)
mock_urlopen.assert_called_once_with(mock_req)
mock_response.read.assert_called_once_with()
self.assertEqual(response, 'fake data')
def test_get_data_metadata_json(self):
self._test_get_data(check_ec2=True, data_type='meta_data.json')
def test_get_data_user_data(self):
self._test_get_data(check_ec2=True, data_type='user_data')
def test_get_data_no_EC2(self):
self._test_get_data(check_ec2=None, data_type=None)
@mock.patch('cloudbaseinit.metadata.services.ec2service.EC2Service'
'._get_EC2_value')
def _test_check_EC2(self, mock_get_EC2_value, side_effect):
mock_get_EC2_value.side_effect = [side_effect]
response = self._ec2service._check_EC2()
if side_effect is Exception:
self.assertFalse(response)
else:
self.assertTrue(response)
def test_check_EC2_Exception(self):
self._test_check_EC2(side_effect=Exception)
def test_check_EC2(self):
self._test_check_EC2(side_effect='fake value')
@mock.patch('posixpath.join')
@mock.patch('urllib2.Request')
@mock.patch('urllib2.urlopen')
def test_get_EC2_value(self, mock_urlopen, mock_Request, mock_join):
mock_key = mock.MagicMock()
mock_response = mock.MagicMock()
fake_path = os.path.join('fake', 'path')
mock_join.return_value = fake_path
mock_Request.return_value = 'fake req'
mock_urlopen.return_value = mock_response
mock_response.read.return_value = 'fake data'
response = self._ec2service._get_EC2_value(mock_key)
mock_join.assert_called_with(CONF.ec2_metadata_base_url,
'meta-data', mock_key)
mock_Request.assert_called_once_with(fake_path)
mock_urlopen.assert_called_once_with('fake req')
mock_response.read.assert_called_once_with()
self.assertEqual(response, 'fake data')
@mock.patch('cloudbaseinit.metadata.services.ec2service.EC2Service'
'._get_EC2_value')
def test_load_public_keys(self, mock_get_EC2_value):
data = {}
key_list = mock.MagicMock()
mock_get_EC2_value.return_value = key_list
self._ec2service._load_public_keys(data)
mock_get_EC2_value.assert_called_with('public-keys/')
self.assertEqual(data['public_keys'], {})

View File

@ -14,25 +14,31 @@
# License for the specific language governing permissions and limitations
# under the License.
import importlib
import mock
import os
import sys
import unittest
import urllib2
from oslo.config import cfg
from cloudbaseinit.metadata.services import base
from cloudbaseinit.metadata.services import httpservice
CONF = cfg.CONF
_ctypes_mock = mock.MagicMock()
mock_dict = {'ctypes': _ctypes_mock}
class HttpServiceTest(unittest.TestCase):
@mock.patch.dict(sys.modules, mock_dict)
def setUp(self):
httpservice = importlib.import_module("cloudbaseinit.metadata.services"
".httpservice")
CONF.set_override('retry_count_interval', 0)
self._httpservice = httpservice.HttpService()
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
@mock.patch('urlparse.urlparse')
def _test_check_metadata_ip_route(self, mock_urlparse, mock_get_os_utils,
side_effect):
@ -64,13 +70,13 @@ class HttpServiceTest(unittest.TestCase):
@mock.patch('cloudbaseinit.metadata.services.httpservice.HttpService'
'._check_metadata_ip_route')
@mock.patch('cloudbaseinit.metadata.services.httpservice.HttpService'
'.get_meta_data')
'._get_meta_data')
def _test_load(self, mock_get_meta_data, mock_check_metadata_ip_route,
side_effect):
mock_get_meta_data.side_effect = [side_effect]
response = self._httpservice.load()
mock_check_metadata_ip_route.assert_called_once_with()
mock_get_meta_data.assert_called_once_with('openstack')
mock_get_meta_data.assert_called_once_with()
if side_effect:
self.assertEqual(response, False)
else:
@ -101,7 +107,7 @@ class HttpServiceTest(unittest.TestCase):
def test_get_response_fail_HTTPError(self):
error = urllib2.HTTPError("http://169.254.169.254/", 404,
'test error 404', {}, None)
'test error 404', {}, None)
self._test_get_response(side_effect=error)
def test_get_response_fail_other_exception(self):
@ -155,3 +161,44 @@ class HttpServiceTest(unittest.TestCase):
mock_Request.assert_called_once_with(mock_norm_path, data=fake_data)
mock_get_response.assert_called_once_with(mock_req)
self.assertEqual(response, True)
def test_get_password_path(self):
response = self._httpservice._get_password_path()
self.assertEqual(
response, 'openstack/%s/password' %
self._httpservice._POST_PASSWORD_MD_VER)
@mock.patch('cloudbaseinit.metadata.services.httpservice.HttpService'
'._get_password_path')
@mock.patch('cloudbaseinit.metadata.services.httpservice.HttpService'
'._post_data')
@mock.patch('cloudbaseinit.metadata.services.httpservice.HttpService'
'._exec_with_retry')
def _test_post_password(self, mock_exec_with_retry, mock_post_data,
mock_get_password_path, ret_val):
mock_exec_with_retry.side_effect = [ret_val]
if isinstance(ret_val, urllib2.HTTPError) and ret_val.code == 409:
response = self._httpservice.post_password(
enc_password_b64='fake')
self.assertEqual(response, False)
elif isinstance(ret_val, urllib2.HTTPError) and ret_val.code != 409:
self.assertRaises(urllib2.HTTPError,
self._httpservice.post_password, 'fake')
else:
response = self._httpservice.post_password(
enc_password_b64='fake')
mock_get_password_path.assert_called_once_with()
self.assertEqual(response, ret_val)
def test_post_password(self):
self._test_post_password(ret_val='fake return')
def test_post_password_HTTPError_409(self):
err = urllib2.HTTPError("http://169.254.169.254/", 409,
'test error 409', {}, None)
self._test_post_password(ret_val=err)
def test_post_password_other_HTTPError(self):
err = urllib2.HTTPError("http://169.254.169.254/", 404,
'test error 404', {}, None)
self._test_post_password(ret_val=err)

View File

@ -0,0 +1,179 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Cloudbase Solutions Srl
#
# 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 importlib
import mock
import os
import posixpath
import sys
import unittest
import urllib2
from oslo.config import cfg
from cloudbaseinit.metadata.services import base
CONF = cfg.CONF
_ctypes_mock = mock.MagicMock()
mock_dict = {'ctypes': _ctypes_mock}
class MaaSHttpServiceTest(unittest.TestCase):
@mock.patch.dict(sys.modules, mock_dict)
def setUp(self):
maasservice = importlib.import_module("cloudbaseinit.metadata.services"
".maasservice")
self.mock_oauth = mock.MagicMock()
self.mock_x509 = mock.MagicMock()
maasservice.oauth = self.mock_oauth
maasservice.x509 = self.mock_x509
self._maasservice = maasservice.MaaSHttpService()
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_data")
def _test_load(self, mock_get_data, ip):
CONF.set_override('maas_metadata_url', ip)
response = self._maasservice.load()
if ip is not None:
mock_get_data.assert_called_once_with('latest/meta-data/')
self.assertTrue(response)
else:
self.assertFalse(response)
def test_load(self):
self._test_load(ip='196.254.196.254')
def test_load_no_ip(self):
self._test_load(ip=None)
@mock.patch('urllib2.urlopen')
def _test_get_response(self, mock_urlopen, ret_val):
mock_request = mock.MagicMock()
mock_urlopen.side_effect = [ret_val]
if isinstance(ret_val, urllib2.HTTPError) and ret_val.code == 404:
self.assertRaises(base.NotExistingMetadataException,
self._maasservice._get_response, mock_request)
elif isinstance(ret_val, urllib2.HTTPError) and ret_val.code != 404:
self.assertRaises(urllib2.HTTPError,
self._maasservice._get_response, mock_request)
else:
response = self._maasservice._get_response(req=mock_request)
mock_urlopen.assert_called_once_with(mock_request)
self.assertEqual(response, ret_val)
def test_get_response(self):
self._test_get_response(ret_val='fake response')
def test_get_response_error_404(self):
err = urllib2.HTTPError("http://169.254.169.254/", 404,
'test error 404', {}, None)
self._test_get_response(ret_val=err)
def test_get_response_error_not_404(self):
err = urllib2.HTTPError("http://169.254.169.254/", 409,
'test other error', {}, None)
self._test_get_response(ret_val=err)
@mock.patch('time.time')
def test_get_oauth_headers(self, mock_time):
mock_token = mock.MagicMock()
mock_consumer = mock.MagicMock()
mock_req = mock.MagicMock()
self.mock_oauth.OAuthConsumer.return_value = mock_consumer
self.mock_oauth.OAuthToken.return_value = mock_token
self.mock_oauth.OAuthRequest.return_value = mock_req
mock_time.return_value = 0
self.mock_oauth.generate_nonce.return_value = 'fake nounce'
response = self._maasservice._get_oauth_headers(url='196.254.196.254')
self.mock_oauth.OAuthConsumer.assert_called_once_with(
CONF.maas_oauth_consumer_key, CONF.maas_oauth_consumer_secret)
self.mock_oauth.OAuthToken.assert_called_once_with(
CONF.maas_oauth_token_key, CONF.maas_oauth_token_secret)
parameters = {'oauth_version': "1.0",
'oauth_nonce': 'fake nounce',
'oauth_timestamp': int(0),
'oauth_token': mock_token.key,
'oauth_consumer_key': mock_consumer.key}
self.mock_oauth.OAuthRequest.assert_called_once_with(
http_url='196.254.196.254', parameters=parameters)
mock_req.sign_request.assert_called_once_with(
self.mock_oauth.OAuthSignatureMethod_PLAINTEXT(), mock_consumer,
mock_token)
self.assertEqual(response, mock_req.to_header())
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_oauth_headers")
@mock.patch("urllib2.Request")
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_response")
def test_get_data(self, mock_get_response, mock_Request,
mock_get_oauth_headers):
CONF.set_override('maas_metadata_url', '196.254.196.254')
fake_path = os.path.join('fake', 'path')
mock_get_oauth_headers.return_value = 'fake headers'
response = self._maasservice._get_data(path=fake_path)
norm_path = posixpath.join(CONF.maas_metadata_url, fake_path)
mock_get_oauth_headers.assert_called_once_with(norm_path)
mock_Request.assert_called_once_with(norm_path,
headers='fake headers')
mock_get_response.assert_called_once_with(mock_Request())
self.assertEqual(response, mock_get_response().read())
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_cache_data")
def test_get_host_name(self, mock_get_cache_data):
response = self._maasservice.get_host_name()
mock_get_cache_data.assert_called_once_with(
'%s/meta-data/local-hostname' %
self._maasservice._metadata_version)
self.assertEqual(response, mock_get_cache_data())
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_cache_data")
def test_get_instance_id(self, mock_get_cache_data):
response = self._maasservice.get_instance_id()
mock_get_cache_data.assert_called_once_with(
'%s/meta-data/instance-id' % self._maasservice._metadata_version)
self.assertEqual(response, mock_get_cache_data())
def test_get_list_from_text(self):
response = self._maasservice._get_list_from_text('fake:text', ':')
self.assertEqual(response, ['fake:', 'text:'])
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_list_from_text")
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_cache_data")
def test_get_public_keys(self, mock_get_cache_data,
mock_get_list_from_text):
response = self._maasservice.get_public_keys()
mock_get_cache_data.assert_called_with(
'%s/meta-data/public-keys' % self._maasservice._metadata_version)
mock_get_list_from_text.assert_called_once_with(mock_get_cache_data(),
"\n")
self.assertEqual(response, mock_get_list_from_text())
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_list_from_text")
@mock.patch("cloudbaseinit.metadata.services.maasservice.MaaSHttpService"
"._get_cache_data")
def test_get_client_auth_certs(self, mock_get_cache_data,
mock_get_list_from_text):
response = self._maasservice.get_client_auth_certs()
mock_get_cache_data.assert_called_with(
'%s/meta-data/x509' % self._maasservice._metadata_version)
mock_get_list_from_text.assert_called_once_with(
mock_get_cache_data(), "%s\n" % self.mock_x509.PEM_FOOTER)
self.assertEqual(response, mock_get_list_from_text())

View File

@ -21,16 +21,14 @@ from cloudbaseinit.metadata import factory
class MetadataServiceFactoryTests(unittest.TestCase):
def setUp(self):
self._factory = factory.MetadataServiceFactory()
@mock.patch('cloudbaseinit.utils.classloader.ClassLoader.load_class')
def _test_get_metadata_service(self, mock_load_class, ret_value):
mock_load_class.side_effect = ret_value
if ret_value is Exception:
self.assertRaises(Exception, self._factory.get_metadata_service)
self.assertRaises(Exception, factory.get_metadata_service)
else:
response = self._factory.get_metadata_service()
response = factory.get_metadata_service()
self.assertEqual(response, mock_load_class()())
def test_get_metadata_service(self):

View File

@ -22,13 +22,11 @@ from cloudbaseinit.osutils import factory
class OSUtilsFactory(unittest.TestCase):
def setUp(self):
self._factory = factory.OSUtilsFactory()
@mock.patch('cloudbaseinit.utils.classloader.ClassLoader.load_class')
def _test_get_os_utils(self, mock_load_class, fake_name):
os.name = fake_name
self._factory.get_os_utils()
factory.get_os_utils()
if fake_name == 'nt':
mock_load_class.assert_called_with(
'cloudbaseinit.osutils.windows.WindowsUtils')

View File

@ -25,14 +25,12 @@ CONF = cfg.CONF
class PluginFactoryTests(unittest.TestCase):
def setUp(self):
self._factory = factory.PluginFactory()
@mock.patch('cloudbaseinit.utils.classloader.ClassLoader.load_class')
def test_load_plugins(self, mock_load_class):
expected = []
for path in CONF.plugins:
expected.append(mock.call(path))
response = self._factory.load_plugins()
response = factory.load_plugins()
self.assertEqual(mock_load_class.call_args_list, expected)
self.assertTrue(response is not None)

View File

@ -37,7 +37,7 @@ class CreateUserPluginTests(unittest.TestCase):
mock_osutils.generate_random_password.assert_called_once_with(14)
self.assertEqual(response, 'fake password')
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
@mock.patch('cloudbaseinit.plugins.windows.createuser.CreateUserPlugin'
'._get_password')
def _test_execute(self, mock_get_password, mock_get_os_utils,

View File

@ -43,7 +43,7 @@ class ExtendVolumesPluginTests(unittest.TestCase):
'.ExtendVolumesPlugin._get_volume_index')
@mock.patch('cloudbaseinit.plugins.windows.extendvolumes'
'.ExtendVolumesPlugin._extend_volume')
@mock.patch('cloudbaseinit.plugins.windows.vds.IVdsVolume')
@mock.patch('cloudbaseinit.utils.windows.vds.IVdsVolume')
def test_extend_volumes(self, _vds_mock, mock_extend_volume,
mock_get_volume_index):
mock_pack = mock.MagicMock()
@ -81,7 +81,7 @@ class ExtendVolumesPluginTests(unittest.TestCase):
@mock.patch('cloudbaseinit.plugins.windows.extendvolumes'
'.ExtendVolumesPlugin._get_volume_extents_to_resize')
@mock.patch('cloudbaseinit.plugins.windows.vds.VDS_INPUT_DISK')
@mock.patch('cloudbaseinit.utils.windows.vds.VDS_INPUT_DISK')
def test_extend_volume(self, mock_VDS_INPUT_DISK,
mock_get_volume_extents_to_resize):
mock_disk = mock.MagicMock()
@ -105,8 +105,8 @@ class ExtendVolumesPluginTests(unittest.TestCase):
mock_VDS_INPUT_DISK.__mul__()(), 1)
mock_async.Wait.assert_called_once_with()
@mock.patch('cloudbaseinit.plugins.windows.vds.IVdsDisk')
@mock.patch('cloudbaseinit.plugins.windows.vds.VDS_DISK_EXTENT')
@mock.patch('cloudbaseinit.utils.windows.vds.IVdsDisk')
@mock.patch('cloudbaseinit.utils.windows.vds.VDS_DISK_EXTENT')
def test_get_volume_extents_to_resize(self, mock_VDS_DISK_EXTENT,
mock_IVdsDisk):
mock_pack = mock.MagicMock()
@ -142,9 +142,9 @@ class ExtendVolumesPluginTests(unittest.TestCase):
_ctypes_mock.windll.ole32.CoTaskMemFree.assert_called_with(
mock_extents_p)
@mock.patch('cloudbaseinit.plugins.windows.vds.'
@mock.patch('cloudbaseinit.utils.windows.vds.'
'VDS_QUERY_SOFTWARE_PROVIDERS')
@mock.patch('cloudbaseinit.plugins.windows.vds.IVdsSwProvider')
@mock.patch('cloudbaseinit.utils.windows.vds.IVdsSwProvider')
def test_query_providers(self, mock_IVdsSwProvider,
mock_VDS_QUERY_SOFTWARE_PROVIDERS):
mock_svc = mock.MagicMock()
@ -162,7 +162,7 @@ class ExtendVolumesPluginTests(unittest.TestCase):
mock_unk.QueryInterface.assert_called_once_with(mock_IVdsSwProvider)
self.assertEqual(response, ['fake providers'])
@mock.patch('cloudbaseinit.plugins.windows.vds.IVdsPack')
@mock.patch('cloudbaseinit.utils.windows.vds.IVdsPack')
def test_query_packs(self, mock_IVdsPack):
mock_provider = mock.MagicMock()
mock_enum = mock.MagicMock()
@ -184,7 +184,7 @@ class ExtendVolumesPluginTests(unittest.TestCase):
response = self._extend_volumes._get_volumes_to_extend()
self.assertEqual(response, [1])
@mock.patch('cloudbaseinit.plugins.windows.vds.load_vds_service')
@mock.patch('cloudbaseinit.utils.windows.vds.load_vds_service')
@mock.patch('cloudbaseinit.plugins.windows.extendvolumes.'
'ExtendVolumesPlugin._query_providers')
@mock.patch('cloudbaseinit.plugins.windows.extendvolumes.'

View File

@ -33,14 +33,15 @@ class NetworkConfigPluginPluginTests(unittest.TestCase):
self.fake_data = fake_json_response.get_fake_metadata_json(
'2013-04-04')
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
def _test_execute(self, mock_get_os_utils, search_result, no_adapters):
CONF.set_override('network_adapter', 'fake adapter')
mock_service = mock.MagicMock()
mock_osutils = mock.MagicMock()
re.search = mock.MagicMock(return_value=search_result)
fake_shared_data = 'fake shared data'
mock_service.get_meta_data.return_value = self.fake_data
network_config = self.fake_data['network_config']
mock_service.get_network_config.return_value = network_config
mock_service.get_content.return_value = search_result
mock_get_os_utils.return_value = mock_osutils
mock_osutils.set_static_network_config.return_value = False
@ -57,9 +58,9 @@ class NetworkConfigPluginPluginTests(unittest.TestCase):
response = self._network_plugin.execute(mock_service,
fake_shared_data)
mock_service.get_meta_data.assert_called_once_with('openstack')
mock_service.get_network_config.assert_called_once_with()
mock_service.get_content.assert_called_once_with(
'openstack', self.fake_data['network_config']['content_path'])
network_config['content_path'])
mock_osutils.set_static_network_config.assert_called_once_with(
'fake adapter', search_result.group('address'),
search_result.group('netmask'),

View File

@ -15,8 +15,6 @@
# under the License.
import mock
import random
import string
import unittest
from oslo.config import cfg
@ -34,28 +32,28 @@ class SetHostNamePluginPluginTests(unittest.TestCase):
self.fake_data = fake_json_response.get_fake_metadata_json(
'2013-04-04')
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
def _test_execute(self, mock_get_os_utils, hostname_exists,
new_hostname_length=1):
mock_service = mock.MagicMock()
mock_osutils = mock.MagicMock()
fake_shared_data = 'fake data'
new_hostname = 'x' * new_hostname_length
self.fake_data['hostname'] = new_hostname
mock_service.get_meta_data.return_value = self.fake_data
if hostname_exists:
mock_service.get_host_name.return_value = new_hostname
else:
mock_service.get_host_name.return_value = None
CONF.set_override('netbios_host_name_compatibility', True)
if hostname_exists is False:
del self.fake_data['hostname']
mock_get_os_utils.return_value = mock_osutils
mock_osutils.set_host_name.return_value = False
response = self._sethostname_plugin.execute(mock_service,
fake_shared_data)
mock_service.get_meta_data.assert_called_once_with('openstack')
mock_service.get_host_name.assert_caled_once_with()
if hostname_exists is True:
length = sethostname.NETBIOS_HOST_NAME_MAX_LEN
mock_get_os_utils.assert_called_once_with()
hostname = self.fake_data['hostname'].split('.', 1)[0]
if len(self.fake_data['hostname']) > length:
hostname = new_hostname.split('.', 1)[0]
if len(new_hostname) > length:
hostname = hostname[:length]
mock_osutils.set_host_name.assert_called_once_with(hostname)

View File

@ -55,18 +55,11 @@ class SetUserPasswordPluginTests(unittest.TestCase):
def _test_get_ssh_public_key(self, data_exists):
mock_service = mock.MagicMock()
mock_service.get_meta_data.return_value = self.fake_data
if data_exists is False:
del self.fake_data['public_keys']
response = self._setpassword_plugin._get_ssh_public_key(
mock_service)
self.assertEqual(response, False)
else:
response = self._setpassword_plugin._get_ssh_public_key(
mock_service)
mock_service.get_meta_data.assert_called_with(
'openstack', self._setpassword_plugin._post_password_md_ver)
self.assertEqual(response, self.fake_data['public_keys']['name'])
public_keys = self.fake_data['public_keys']
mock_service.get_public_keys.return_value = public_keys
response = self._setpassword_plugin._get_ssh_public_key(mock_service)
mock_service.get_public_keys.assert_called_with()
self.assertEqual(response, public_keys[0])
def test_get_ssh_plublic_key(self):
self._test_get_ssh_public_key(data_exists=True)
@ -74,18 +67,26 @@ class SetUserPasswordPluginTests(unittest.TestCase):
def test_get_ssh_plublic_key_no_pub_keys(self):
self._test_get_ssh_public_key(data_exists=False)
def test_get_password(self):
def _test_get_password(self, inject_password):
mock_service = mock.MagicMock()
mock_osutils = mock.MagicMock()
mock_service.get_meta_data.return_value = self.fake_data
CONF.set_override('inject_user_password', False)
mock_service.get_admin_password.return_value = 'Passw0rd'
CONF.set_override('inject_user_password', inject_password)
mock_osutils.generate_random_password.return_value = 'Passw0rd'
response = self._setpassword_plugin._get_password(mock_service,
mock_osutils)
mock_service.get_meta_data.assert_called_with('openstack')
mock_osutils.generate_random_password.assert_called_once_with(14)
if inject_password:
mock_service.get_admin_password.assert_called_with()
else:
mock_osutils.generate_random_password.assert_called_once_with(14)
self.assertEqual(response, 'Passw0rd')
def test_get_password_inject_true(self):
self._test_get_password(inject_password=True)
def test_get_password_inject_false(self):
self._test_get_password(inject_password=False)
@mock.patch('cloudbaseinit.plugins.windows.setuserpassword.'
'SetUserPasswordPlugin._get_ssh_public_key')
@mock.patch('cloudbaseinit.plugins.windows.setuserpassword.'
@ -97,10 +98,8 @@ class SetUserPasswordPluginTests(unittest.TestCase):
mock_get_key.return_value = ssh_pub_key
mock_encrypt_password.return_value = 'encrypted password'
mock_service.post_password.return_value = 'value'
response = self._setpassword_plugin._set_metadata_password(
fake_passw0rd, mock_service)
if ssh_pub_key is None:
self.assertEqual(response, True)
else:
@ -108,8 +107,7 @@ class SetUserPasswordPluginTests(unittest.TestCase):
mock_encrypt_password.assert_called_once_with(ssh_pub_key,
fake_passw0rd)
mock_service.post_password.assert_called_with(
'encrypted password',
self._setpassword_plugin._post_password_md_ver)
'encrypted password')
self.assertEqual(response, 'value')
def test_set_metadata_password_with_ssh_key(self):
@ -125,11 +123,9 @@ class SetUserPasswordPluginTests(unittest.TestCase):
mock_service = mock.MagicMock()
mock_osutils = mock.MagicMock()
mock_get_password.return_value = 'fake password'
response = self._setpassword_plugin._set_password(mock_service,
mock_osutils,
'fake user')
mock_get_password.assert_called_once_with(mock_service, mock_osutils)
mock_osutils.set_user_password.assert_called_once_with('fake user',
'fake password')
@ -139,26 +135,24 @@ class SetUserPasswordPluginTests(unittest.TestCase):
'SetUserPasswordPlugin._set_password')
@mock.patch('cloudbaseinit.plugins.windows.setuserpassword.'
'SetUserPasswordPlugin._set_metadata_password')
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
def test_execute(self, mock_get_os_utils, mock_set_metadata_password,
mock_set_password):
mock_service = mock.MagicMock()
mock_osutils = mock.MagicMock()
fake_shared_data = mock.MagicMock()
fake_shared_data.get.return_value = 'fake username'
mock_service.is_password_set.return_value = False
mock_service.is_password_set = False
mock_service.can_post_password = True
mock_get_os_utils.return_value = mock_osutils
mock_osutils.user_exists.return_value = True
mock_set_password.return_value = 'fake password'
response = self._setpassword_plugin.execute(mock_service,
fake_shared_data)
print mock_service.mock_calls
mock_get_os_utils.assert_called_once_with()
fake_shared_data.get.assert_called_with(
constants.SHARED_DATA_USERNAME, CONF.username)
mock_service.is_password_set.assert_called_once_with(
self._setpassword_plugin._post_password_md_ver)
mock_get_os_utils.assert_called_once_with()
mock_osutils.user_exists.assert_called_once_with('fake username')
mock_set_password.assert_called_once_with(mock_service, mock_osutils,
'fake username')

View File

@ -33,7 +33,7 @@ class SetUserSSHPublicKeysPluginTests(unittest.TestCase):
self.fake_data = fake_json_response.get_fake_metadata_json(
'2013-04-04')
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
@mock.patch('os.path')
@mock.patch('os.makedirs')
def _test_execute(self, mock_os_makedirs, mock_os_path,
@ -41,7 +41,7 @@ class SetUserSSHPublicKeysPluginTests(unittest.TestCase):
mock_service = mock.MagicMock()
mock_osutils = mock.MagicMock()
fake_shared_data = 'fake data'
mock_service.get_meta_data.return_value = self.fake_data
mock_service.get_public_keys.return_value = self.fake_data
CONF.set_override('username', 'fake user')
mock_get_os_utils.return_value = mock_osutils
mock_osutils.get_user_home.return_value = user_home
@ -56,7 +56,7 @@ class SetUserSSHPublicKeysPluginTests(unittest.TestCase):
mock.mock_open(), create=True):
response = self._set_ssh_keys_plugin.execute(mock_service,
fake_shared_data)
mock_service.get_meta_data.assert_called_with('openstack')
mock_service.get_public_keys.assert_called_with()
mock_osutils.get_user_home.assert_called_with('fake user')
self.assertEqual(mock_os_path.join.call_count, 2)
mock_os_makedirs.assert_called_once_with(mock_os_path.join())

View File

@ -41,7 +41,7 @@ class UserDataPluginTest(unittest.TestCase):
mock_service.get_user_data.side_effect = [ret_val]
response = self._userdata.execute(service=mock_service,
shared_data=None)
mock_service.get_user_data.assert_called_once_with('openstack')
mock_service.get_user_data.assert_called_once_with()
if ret_val is metadata_services_base.NotExistingMetadataException:
self.assertEqual(response, (base.PLUGIN_EXECUTION_DONE, False))
elif ret_val is None:
@ -68,7 +68,7 @@ class UserDataPluginTest(unittest.TestCase):
self.assertEqual(response, mock_message_from_string().walk())
@mock.patch('cloudbaseinit.plugins.windows.userdataplugins.factory.'
'UserDataPluginsFactory.load_plugins')
'load_plugins')
@mock.patch('cloudbaseinit.plugins.windows.userdata.UserDataPlugin'
'._parse_mime')
@mock.patch('cloudbaseinit.plugins.windows.userdata.UserDataPlugin'

View File

@ -37,7 +37,7 @@ class UserDataUtilsTest(unittest.TestCase):
@mock.patch('os.path.isdir')
@mock.patch('os.path.exists')
@mock.patch('os.path.expandvars')
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
def _test_execute_user_data_script(self, mock_get_os_utils,
mock_path_expandvars,
mock_path_exists, mock_path_isdir,

View File

@ -19,62 +19,28 @@ import mock
import sys
import unittest
from oslo.config import cfg
from cloudbaseinit.plugins import constants
CONF = cfg.CONF
_ctypes_mock = mock.MagicMock()
_win32com_mock = mock.MagicMock()
_pywintypes_mock = mock.MagicMock()
mock_dict = {'ctypes': _ctypes_mock,
'win32com': _win32com_mock,
'pywintypes': _pywintypes_mock}
from oslo.config import cfg
from cloudbaseinit.plugins import constants
CONF = cfg.CONF
class ConfigWinRMCertificateAuthPluginTests(unittest.TestCase):
@mock.patch.dict(sys.modules, mock_dict)
def setUp(self):
winrmcert = importlib.import_module('cloudbaseinit.plugins.windows.'
'winrmcertificateauth')
self.x509 = importlib.import_module('cloudbaseinit.plugins.windows'
'.x509')
self._certif_auth = winrmcert.ConfigWinRMCertificateAuthPlugin()
self.winrmcert = importlib.import_module(
'cloudbaseinit.plugins.windows.winrmcertificateauth')
self._certif_auth = self.winrmcert.ConfigWinRMCertificateAuthPlugin()
def tearDown(self):
reload(sys)
def _test_get_client_auth_cert(self, chunk):
mock_service = mock.MagicMock()
mock_meta_data = mock.MagicMock()
mock_meta = mock.MagicMock()
mock_service.get_meta_data.return_value = mock_meta_data
mock_meta_data.get.return_value = mock_meta
mock_meta.get.side_effect = chunk
mock_service.get_user_data.return_value = self.x509.PEM_HEADER
response = self._certif_auth._get_client_auth_cert(mock_service)
mock_service.get_meta_data.assert_called_once_with('openstack')
mock_meta_data.get.assert_called_once_with('meta')
if chunk == [None]:
mock_service.get_user_data.assert_called_once_with('openstack')
mock_meta.get.assert_called_once_with('admin_cert0')
self.assertEqual(response, self.x509.PEM_HEADER)
else:
expected = [mock.call('admin_cert0'), mock.call('admin_cert1')]
self.assertEqual(mock_meta.get.call_args_list, expected)
self.assertEqual(response, 'fake data')
def test_get_client_auth_cert(self):
chunk = ['fake data', None]
self._test_get_client_auth_cert(chunk=chunk)
def test_get_client_auth_cert_no_cert_data(self):
self._test_get_client_auth_cert(chunk=[None])
def _test_get_credentials(self, fake_user, fake_password):
mock_shared_data = mock.MagicMock()
mock_shared_data.get.side_effect = [fake_user, fake_password]
@ -105,32 +71,28 @@ class ConfigWinRMCertificateAuthPluginTests(unittest.TestCase):
@mock.patch('cloudbaseinit.plugins.windows.winrmcertificateauth'
'.ConfigWinRMCertificateAuthPlugin._get_credentials')
@mock.patch('cloudbaseinit.plugins.windows.winrmcertificateauth'
'.ConfigWinRMCertificateAuthPlugin._get_client_auth_cert')
@mock.patch('cloudbaseinit.plugins.windows.x509.CryptoAPICertManager'
'.import_cert')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig')
def _test_execute(self, mock_WinRMConfig, mock_import_cert,
mock_get_client_auth_cert, mock_get_credentials,
cert_data, cert_upn):
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig')
@mock.patch('cloudbaseinit.utils.windows.x509.CryptoAPICertManager.'
'import_cert')
def _test_execute(self, mock_import_cert, mock_WinRMConfig,
mock_get_credentials, cert_data, cert_upn):
mock_service = mock.MagicMock()
mock_cert_thumprint = mock.MagicMock()
fake_credentials = ('fake user', 'fake password')
mock_shared_data = mock.MagicMock()
mock_get_client_auth_cert.return_value = cert_data
mock_get_credentials.return_value = fake_credentials
mock_import_cert.return_value = (mock_cert_thumprint, cert_upn)
mock_WinRMConfig.get_cert_mapping.return_value = True
mock_service.get_client_auth_certs.return_value = [cert_data]
response = self._certif_auth.execute(mock_service,
mock_shared_data)
if not cert_data or not cert_upn:
shared_data='fake data')
mock_service.get_client_auth_certs.assert_called_once_with()
if not cert_data:
self.assertEqual(response, (1, False))
else:
mock_get_client_auth_cert.assert_called_once_with(mock_service)
mock_get_credentials.assert_called_once_with(mock_shared_data)
mock_get_credentials.assert_called_once_with('fake data')
mock_import_cert.assert_called_once_with(
cert_data, store_name=self.x509.STORE_NAME_ROOT)
cert_data, store_name=self.winrmcert.x509.STORE_NAME_ROOT)
mock_WinRMConfig().set_auth_config.assert_called_once_with(
certificate=True)
@ -151,7 +113,3 @@ class ConfigWinRMCertificateAuthPluginTests(unittest.TestCase):
def test_execute_no_cert_data(self):
cert_upn = mock.MagicMock()
self._test_execute(cert_data=None, cert_upn=cert_upn)
def test_execute_no_cert_upn(self):
cert_data = 'fake cert data'
self._test_execute(cert_data=cert_data, cert_upn=None)

View File

@ -23,7 +23,12 @@ from oslo.config import cfg
CONF = cfg.CONF
_mock_wintypes = mock.MagicMock()
mock_dict = {'ctypes.wintypes': _mock_wintypes}
_mock_pywintypes = mock.MagicMock()
_mock_win32 = mock.MagicMock()
mock_dict = {'ctypes': _mock_wintypes,
'ctypes.wintypes': _mock_wintypes,
'pywintypes': _mock_pywintypes,
'win32com': _mock_win32}
class ConfigWinRMListenerPluginTests(unittest.TestCase):
@ -66,11 +71,11 @@ class ConfigWinRMListenerPluginTests(unittest.TestCase):
def test_check_winrm_service_no_service(self):
self._test_check_winrm_service(service_exists=False)
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
@mock.patch('cloudbaseinit.plugins.windows.winrmlistener.'
'ConfigWinRMListenerPlugin._check_winrm_service')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig')
@mock.patch('cloudbaseinit.plugins.windows.x509.CryptoAPICertManager'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig')
@mock.patch('cloudbaseinit.utils.windows.x509.CryptoAPICertManager'
'.create_self_signed_cert')
def _test_execute(self, mock_create_cert, mock_WinRMConfig,
mock_check_winrm_service, mock_get_os_utils,

View File

@ -26,10 +26,7 @@ CONF = cfg.CONF
class UserDataPluginsFactoryTests(unittest.TestCase):
def setUp(self):
self._factory = factory.UserDataPluginsFactory()
@mock.patch('cloudbaseinit.utils.classloader.ClassLoader.load_class')
def test_process(self, mock_load_class):
response = self._factory.load_plugins()
response = factory.load_plugins()
self.assertTrue(response is not None)

View File

@ -30,7 +30,7 @@ class ShellScriptPluginTests(unittest.TestCase):
def setUp(self):
self._shellscript = shellscript.ShellScriptPlugin()
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
@mock.patch('tempfile.gettempdir')
def _test_process(self, mock_gettempdir, mock_get_os_utils, filename,
exception=False):

View File

@ -47,18 +47,32 @@ class InitManagerTest(unittest.TestCase):
reload(sys)
reload(init)
def test_get_plugin_status(self):
def _test_get_plugin_section(self, instance_id):
response = self._init._get_plugins_section(instance_id=instance_id)
if not instance_id:
self.assertEqual(response, self._init._PLUGINS_CONFIG_SECTION)
else:
self.assertEqual(
response,
instance_id + "/" + self._init._PLUGINS_CONFIG_SECTION)
@mock.patch('cloudbaseinit.init.InitManager._get_plugins_section')
def test_get_plugin_status(self, mock_get_plugins_section):
self.osutils.get_config_value.return_value = 1
response = self._init._get_plugin_status(self.osutils, 'fake plugin')
response = self._init._get_plugin_status(self.osutils, 'fake id',
'fake plugin')
mock_get_plugins_section.assert_called_once_with('fake id')
self.osutils.get_config_value.assert_called_once_with(
'fake plugin', self._init._PLUGINS_CONFIG_SECTION)
'fake plugin', mock_get_plugins_section())
self.assertTrue(response == 1)
def test_set_plugin_status(self):
self._init._set_plugin_status(self.osutils, 'fake plugin', 'status')
@mock.patch('cloudbaseinit.init.InitManager._get_plugins_section')
def test_set_plugin_status(self, mock_get_plugins_section):
self._init._set_plugin_status(self.osutils, 'fake id',
'fake plugin', 'status')
mock_get_plugins_section.assert_called_once_with('fake id')
self.osutils.set_config_value.assert_called_once_with(
'fake plugin', 'status', self._init._PLUGINS_CONFIG_SECTION)
'fake plugin', 'status', mock_get_plugins_section())
@mock.patch('cloudbaseinit.init.InitManager._get_plugin_status')
@mock.patch('cloudbaseinit.init.InitManager._set_plugin_status')
@ -72,14 +86,17 @@ class InitManagerTest(unittest.TestCase):
response = self._init._exec_plugin(osutils=self.osutils,
service='fake service',
plugin=self.plugin,
instance_id='fake id',
shared_data='shared data')
mock_get_plugin_status.assert_called_once_with(self.osutils,
'fake id',
fake_name)
if status is base.PLUGIN_EXECUTE_ON_NEXT_BOOT:
self.plugin.execute.assert_called_once_with('fake service',
'shared data')
mock_set_plugin_status.assert_called_once_with(self.osutils,
'fake id',
fake_name, status)
self.assertTrue(response)
@ -114,10 +131,9 @@ class InitManagerTest(unittest.TestCase):
@mock.patch('cloudbaseinit.init.InitManager'
'._check_plugin_os_requirements')
@mock.patch('cloudbaseinit.init.InitManager._exec_plugin')
@mock.patch('cloudbaseinit.plugins.factory.PluginFactory.load_plugins')
@mock.patch('cloudbaseinit.osutils.factory.OSUtilsFactory.get_os_utils')
@mock.patch('cloudbaseinit.metadata.factory.MetadataServiceFactory.'
'get_metadata_service')
@mock.patch('cloudbaseinit.plugins.factory.load_plugins')
@mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
@mock.patch('cloudbaseinit.metadata.factory.get_metadata_service')
def test_configure_host(self, mock_get_metadata_service,
mock_get_os_utils, mock_load_plugins,
mock_exec_plugin,
@ -128,6 +144,7 @@ class InitManagerTest(unittest.TestCase):
mock_get_os_utils.return_value = self.osutils
mock_get_metadata_service.return_value = fake_service
fake_service.get_name.return_value = 'fake name'
fake_service.get_instance_id.return_value = 'fake id'
self._init.configure_host()
@ -137,6 +154,6 @@ class InitManagerTest(unittest.TestCase):
mock_check_os_requirements.assert_called_once_with(self.osutils,
fake_plugin)
mock_exec_plugin.assert_called_once_with(self.osutils, fake_service,
fake_plugin, {})
fake_plugin, 'fake id', {})
fake_service.cleanup.assert_called_once_with()
self.osutils.reboot.assert_called_once_with()

View File

@ -0,0 +1,15 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
#
# 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.

View File

@ -0,0 +1,15 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
#
# 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.

View File

@ -21,7 +21,7 @@ import unittest
from oslo.config import cfg
if sys.platform == 'win32':
from cloudbaseinit.plugins.windows import winrmconfig
from cloudbaseinit.utils.windows import winrmconfig
CONF = cfg.CONF
@ -49,7 +49,7 @@ class WinRMConfigTests(unittest.TestCase):
self.assertEqual(response, mock_match().groups().__getitem__())
@mock.patch('xml.etree.ElementTree.fromstring')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_node_tag')
def _test_parse_listener_xml(self, mock_get_node_tag, mock_fromstring,
data_xml, tag=None, text='Fake'):
@ -104,8 +104,8 @@ class WinRMConfigTests(unittest.TestCase):
text='fake text')
@mock.patch('xml.etree.ElementTree.fromstring')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
'_get_node_tag')
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig'
'._get_node_tag')
def _test_parse_cert_mapping_xml(self, mock_get_node_tag,
mock_fromstring, data_xml, tag=None,
text='Fake'):
@ -157,7 +157,7 @@ class WinRMConfigTests(unittest.TestCase):
def test_get_xml_bool_false(self):
self._test_get_xml_bool(value=None)
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_wsman_session')
def _test_get_resource(self, mock_get_wsman_session, resource):
fake_session = mock.MagicMock()
@ -179,7 +179,7 @@ class WinRMConfigTests(unittest.TestCase):
def test_get_resource_exception(self):
self._test_get_resource(resource=Exception)
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_wsman_session')
def test_delete_resource(self, mock_get_wsman_session):
fake_session = mock.MagicMock()
@ -188,7 +188,7 @@ class WinRMConfigTests(unittest.TestCase):
self._winrmconfig._delete_resource(fake_uri)
fake_session.Delete.assert_called_once_with(fake_uri)
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_wsman_session')
def test_create_resource(self, mock_get_wsman_session):
fake_session = mock.MagicMock()
@ -197,9 +197,9 @@ class WinRMConfigTests(unittest.TestCase):
self._winrmconfig._create_resource(fake_uri, 'fake data')
fake_session.Create.assert_called_once_with(fake_uri, 'fake data')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_parse_cert_mapping_xml')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_resource')
def test_get_cert_mapping(self, mock_get_resource,
mock_parse_cert_mapping_xml):
@ -215,7 +215,7 @@ class WinRMConfigTests(unittest.TestCase):
self._winrmconfig._SERVICE_CERTMAPPING_URI % fake_dict)
self.assertEqual(response, 'fake response')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_delete_resource')
def test_delete_cert_mapping(self, mock_delete_resource):
fake_dict = {'issuer': 'issuer',
@ -226,9 +226,9 @@ class WinRMConfigTests(unittest.TestCase):
mock_delete_resource.assert_called_with(
self._winrmconfig._SERVICE_CERTMAPPING_URI % fake_dict)
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_xml_bool')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_create_resource')
def test_create_cert_mapping(self, mock_create_resource,
mock_get_xml_bool):
@ -251,9 +251,9 @@ class WinRMConfigTests(unittest.TestCase):
'username': 'fake user',
'password': 'fake password'})
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_resource')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_parse_listener_xml')
def test_get_listener(self, mock_parse_listener_xml, mock_get_resource):
dict = {'protocol': 'HTTPS',
@ -267,7 +267,7 @@ class WinRMConfigTests(unittest.TestCase):
mock_parse_listener_xml.assert_called_once_with('fake resource')
self.assertEqual(response, 'fake response')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_delete_resource')
def test_delete_listener(self, mock_delete_resource):
dict = {'protocol': 'HTTPS',
@ -277,9 +277,9 @@ class WinRMConfigTests(unittest.TestCase):
mock_delete_resource.assert_called_with(
self._winrmconfig._SERVICE_LISTENER_URI % dict)
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_create_resource')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_xml_bool')
def test_create_listener(self, mock_get_xml_bool, mock_create_resource):
dict = {'protocol': 'HTTPS',
@ -301,9 +301,9 @@ class WinRMConfigTests(unittest.TestCase):
"cert_thumbprint": None})
@mock.patch('xml.etree.ElementTree.fromstring')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_node_tag')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_resource')
def test_get_auth_config(self, mock_get_resource, mock_get_node_tag,
mock_fromstring):
@ -325,9 +325,9 @@ class WinRMConfigTests(unittest.TestCase):
@mock.patch('xml.etree.ElementTree.fromstring')
@mock.patch('xml.etree.ElementTree.tostring')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_wsman_session')
@mock.patch('cloudbaseinit.plugins.windows.winrmconfig.WinRMConfig.'
@mock.patch('cloudbaseinit.utils.windows.winrmconfig.WinRMConfig.'
'_get_xml_bool')
def test_set_auth_config(self, mock_get_xml_bool, mock_get_wsman_session,
mock_tostring, mock_fromstring):

View File

@ -21,8 +21,8 @@ import unittest
from oslo.config import cfg
if sys.platform == 'win32':
from cloudbaseinit.plugins.windows import cryptoapi
from cloudbaseinit.plugins.windows import x509
from cloudbaseinit.utils.windows import cryptoapi
from cloudbaseinit.utils.windows import x509
CONF = cfg.CONF
@ -33,17 +33,16 @@ class CryptoAPICertManagerTests(unittest.TestCase):
def setUp(self):
self._x509 = x509.CryptoAPICertManager()
@mock.patch('cloudbaseinit.plugins.windows.x509.free')
@mock.patch('cloudbaseinit.utils.windows.x509.free')
@mock.patch('ctypes.c_ubyte')
@mock.patch('ctypes.POINTER')
@mock.patch('ctypes.cast')
@mock.patch('cloudbaseinit.plugins.windows.x509.malloc')
@mock.patch('cloudbaseinit.utils.windows.x509.malloc')
@mock.patch('ctypes.byref')
@mock.patch('ctypes.wintypes.DWORD')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertGetCertificateContextProperty')
def _test_get_cert_thumprint(self,
mock_CertGetCertificateContextProperty,
def _test_get_cert_thumprint(self, mock_CertGetCertificateContextProperty,
mock_DWORD, mock_byref, mock_malloc,
mock_cast, mock_POINTER, mock_c_ubyte,
mock_free, ret_val):
@ -80,14 +79,10 @@ class CryptoAPICertManagerTests(unittest.TestCase):
def test_get_cert_thumprint_GetCertificateContextProperty_exception(self):
self._test_get_cert_thumprint(ret_val=False)
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
'CryptDestroyKey')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
'CryptReleaseContext')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
'CryptGenKey')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
'CryptAcquireContext')
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.CryptDestroyKey')
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.CryptReleaseContext')
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.CryptGenKey')
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.CryptAcquireContext')
@mock.patch('ctypes.byref')
@mock.patch('ctypes.wintypes.HANDLE')
def _test_generate_key(self, mock_HANDLE, mock_byref,
@ -131,41 +126,41 @@ class CryptoAPICertManagerTests(unittest.TestCase):
self._test_generate_key(acquired_context=True,
generate_key_ret_val=None)
@mock.patch('cloudbaseinit.plugins.windows.x509.free')
@mock.patch('cloudbaseinit.utils.windows.x509.free')
@mock.patch('copy.copy')
@mock.patch('ctypes.byref')
@mock.patch('cloudbaseinit.plugins.windows.x509.malloc')
@mock.patch('cloudbaseinit.utils.windows.x509.malloc')
@mock.patch('ctypes.POINTER')
@mock.patch('ctypes.cast')
@mock.patch('cloudbaseinit.plugins.windows.x509.CryptoAPICertManager'
@mock.patch('cloudbaseinit.utils.windows.x509.CryptoAPICertManager'
'._generate_key')
@mock.patch('cloudbaseinit.plugins.windows.x509.CryptoAPICertManager'
@mock.patch('cloudbaseinit.utils.windows.x509.CryptoAPICertManager'
'._get_cert_thumprint')
@mock.patch('uuid.uuid4')
@mock.patch('ctypes.wintypes.DWORD')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertStrToName')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CRYPTOAPI_BLOB')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CRYPT_KEY_PROV_INFO')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CRYPT_ALGORITHM_IDENTIFIER')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'SYSTEMTIME')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'GetSystemTime')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertCreateSelfSignCertificate')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertAddEnhancedKeyUsageIdentifier')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertOpenStore')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertAddCertificateContextToStore')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertCloseStore')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertFreeCertificateContext')
def _test_create_self_signed_cert(self, mock_CertFreeCertificateContext,
mock_CertCloseStore,
@ -278,25 +273,25 @@ class CryptoAPICertManagerTests(unittest.TestCase):
response = self._x509._get_cert_base64(fake_cert_data)
self.assertEqual(response, 'fake cert')
@mock.patch('cloudbaseinit.plugins.windows.x509.free')
@mock.patch('cloudbaseinit.plugins.windows.x509.CryptoAPICertManager'
@mock.patch('cloudbaseinit.utils.windows.x509.free')
@mock.patch('cloudbaseinit.utils.windows.x509.CryptoAPICertManager'
'._get_cert_thumprint')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertCloseStore')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertFreeCertificateContext')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertGetNameString')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertAddEncodedCertificateToStore')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CertOpenStore')
@mock.patch('cloudbaseinit.plugins.windows.cryptoapi.'
@mock.patch('cloudbaseinit.utils.windows.cryptoapi.'
'CryptStringToBinaryA')
@mock.patch('cloudbaseinit.plugins.windows.x509.CryptoAPICertManager'
@mock.patch('cloudbaseinit.utils.windows.x509.CryptoAPICertManager'
'._get_cert_base64')
@mock.patch('ctypes.POINTER')
@mock.patch('cloudbaseinit.plugins.windows.x509.malloc')
@mock.patch('cloudbaseinit.utils.windows.x509.malloc')
@mock.patch('ctypes.cast')
@mock.patch('ctypes.byref')
@mock.patch('ctypes.wintypes.DWORD')