Add test for ovs collector module and modify collector

This change includes:

* New test class to test ovs/collector module. Added one test
  in the meantime to test get_env function.

* loading configuration moved to a function, since it affects
  testing.

* Added paramiko to test-requirements since it used by ovs/common

* Minor improvement to get_env function.

Change-Id: I606f1af74a7148057673df1e95c1c80e82777ec3
This commit is contained in:
Arie
2016-10-08 16:14:26 +03:00
parent f75e67c73d
commit 927da6205e
6 changed files with 80 additions and 20 deletions

View File

@@ -1,3 +1,14 @@
# 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.
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
import horizon import horizon

View File

@@ -18,20 +18,20 @@ import re
import openstack_dashboard.don.ovs.common as common import openstack_dashboard.don.ovs.common as common
don_config = ConfigParser.ConfigParser()
try:
don_config.read('/etc/don/don.conf')
except Exception as e:
print(e.value)
deployment_type = don_config.get('DEFAULT', 'deployment_type')
def get_env(filename): def get_env(filename):
"""Returns environment dictionary created from the environment file.
:param filename: the name of the environment file.
"""
# Try read enviornment file
try: try:
lines = open(os.getcwd() + os.sep + filename, 'r').read().splitlines() with open(os.getcwd() + os.sep + filename, 'r') as f:
lines = f.read().splitlines()
except IOError as e: except IOError as e:
print("%s :%s" % (e.args[1], filename)) raise(e)
raise
# Create env dictionary based on lines that starts with 'export ...'
env = {} env = {}
for line in lines: for line in lines:
if line.startswith('export'): if line.startswith('export'):
@@ -42,8 +42,6 @@ def get_env(filename):
env.update({key: val}) env.update({key: val})
return env return env
myenv = os.environ.copy()
myenv.update(get_env('admin-openrc.sh'))
# Contains all info gathered by parsing the output of commands # Contains all info gathered by parsing the output of commands
info = { info = {
@@ -497,7 +495,6 @@ def neutron_router_list_parser(parse_this):
'parser': ip_namespace_qrouter_parser, 'parser': ip_namespace_qrouter_parser,
} }
add_new_command(commands, cmd_key, cmd) add_new_command(commands, cmd_key, cmd)
pass
def ip_namespace_qrouter_parser(parse_this): def ip_namespace_qrouter_parser(parse_this):
@@ -640,7 +637,6 @@ def neutron_net_list_parser(parse_this):
'parser': ip_namespace_qdhcp_parser, 'parser': ip_namespace_qdhcp_parser,
} }
add_new_command(commands, cmd_key, cmd) add_new_command(commands, cmd_key, cmd)
pass
''' '''
@@ -875,9 +871,9 @@ def all_commands_executed(commands):
return True return True
def get_vm_info_from_compute(cmd): def get_vm_info_from_compute(cmd, my_env):
output = common.execute_cmd(['nova', 'hypervisor-list'], output = common.execute_cmd(['nova', 'hypervisor-list'],
sudo=False, shell=False, env=myenv).split('\n') sudo=False, shell=False, env=my_env).split('\n')
compute_list = get_hypervisor(output) compute_list = get_hypervisor(output)
vm_info = [] vm_info = []
compute_creds = common.get_vm_credentials() compute_creds = common.get_vm_credentials()
@@ -915,7 +911,22 @@ def get_hypervisor(parse_this):
return hypervisor return hypervisor
def load_config():
"""Loads configuration."""
don_config = ConfigParser.ConfigParser()
try:
don_config.read('/etc/don/don.conf')
except Exception as e:
raise(e.value)
return don_config.get('DEFAULT', 'deployment_type')
def main(): def main():
deployment_type = load_config()
my_env = os.environ.copy()
my_env.update(get_env('admin-openrc.sh'))
check_args() check_args()
iteration = 0 iteration = 0
@@ -938,7 +949,7 @@ def main():
shell = commands[cmd].get('shell', False) shell = commands[cmd].get('shell', False)
env = None env = None
if commands[cmd].get('env', False): if commands[cmd].get('env', False):
env = myenv env = my_env
sudo = commands[cmd].get('sudo', False) sudo = commands[cmd].get('sudo', False)
if deployment_type == 'multinode': if deployment_type == 'multinode':
# handling for network node # handling for network node
@@ -948,7 +959,7 @@ def main():
if cmd == 'cat_instance': if cmd == 'cat_instance':
commands[cmd][ commands[cmd][
'output'] = get_vm_info_from_compute( 'output'] = get_vm_info_from_compute(
commands[cmd]['cmd']) commands[cmd]['cmd'], my_env)
print(commands[cmd]['output']) print(commands[cmd]['output'])
else: else:
commands[cmd]['output'] = common.execute_cmd( commands[cmd]['output'] = common.execute_cmd(
@@ -966,5 +977,6 @@ def main():
'Writing collected info into ' + common.settings['info_file']) 'Writing collected info into ' + common.settings['info_file'])
common.dump_json(info, common.settings['info_file']) common.dump_json(info, common.settings['info_file'])
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@@ -205,7 +205,6 @@ def collect(request):
status = 1 status = 1
macro['collect_status'] = \ macro['collect_status'] = \
"Collecton successful. Click visualize to display" "Collecton successful. Click visualize to display"
# res = collector.main()
os.chdir(BASE_DIR) os.chdir(BASE_DIR)
if status: if status:
messages.success(request, macro['collect_status']) messages.success(request, macro['collect_status'])

View File

@@ -19,5 +19,4 @@ from oslotest import base
class TestCase(base.BaseTestCase): class TestCase(base.BaseTestCase):
"""Test case base class for all unit tests.""" """Test case base class for all unit tests."""

View File

@@ -0,0 +1,38 @@
# 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 tempfile
import openstack_dashboard.don.ovs.collector as collector
from openstack_dashboard.tests import base
class TestOvsCollector(base.TestCase):
"""Tests openvswitch collector module."""
def setUp(self):
super(TestOvsCollector, self).setUp()
# Create a temporary file
self.tmp_fd, self.tmp_fp = tempfile.mkstemp(dir=os.getcwd())
def tearDown(self):
super(TestOvsCollector, self).tearDown()
# Remove the file
os.remove(self.tmp_fp)
def test_get_env(self):
lines = ["export x=2", "export y=3", "z=4"]
with open(self.tmp_fp, 'w') as f:
f.write("\n".join(lines))
env = collector.get_env(os.path.basename(self.tmp_fp))
self.assertEqual(env, dict(x='2', y='3'))

View File

@@ -10,6 +10,7 @@ python-subunit>=0.0.18
sphinx!=1.2.0,!=1.3b1,<1.3,>=1.1.2 sphinx!=1.2.0,!=1.3b1,<1.3,>=1.1.2
oslosphinx>=2.5.0 # Apache-2.0 oslosphinx>=2.5.0 # Apache-2.0
oslotest>=1.10.0 # Apache-2.0 oslotest>=1.10.0 # Apache-2.0
paramiko
testrepository>=0.0.18 testrepository>=0.0.18
testscenarios>=0.4 testscenarios>=0.4
testtools>=1.4.0 testtools>=1.4.0