Add unit test for collector/ceilometer.py

Also remove distil/common/odoo.py which is not used anywhere.

This change increase coverage from 55% to 57%

Change-Id: I95f673818bca570e8c0ffa91e45af5272e89c15a
This commit is contained in:
Lingxian Kong 2017-06-08 16:53:45 +12:00
parent 4f29bf7243
commit ccb1b5849e
2 changed files with 66 additions and 92 deletions

View File

@ -1,92 +0,0 @@
# Copyright (c) 2016 Catalyst IT Ltd.
#
# 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 odoorpc
from oslo_config import cfg
from oslo_log import log
from distil.common import openstack
CONF = cfg.CONF
PRODUCT_CATEGORY = ('Compute', 'Network', 'Block Storage', 'Object Storage')
class Odoo(object):
def __init__(self):
self.odoo = odoorpc.ODOO(CONF.odoo.hostname,
protocol=CONF.odoo.protocol,
port=CONF.odoo.port,
version=CONF.odoo.version)
self.odoo.login(CONF.odoo.database, CONF.odoo.user, CONF.odoo.password)
# NOTE(flwang): This is not necessary for most of cases, but just in
# case some cloud providers are using different region name formats in
# Keystone and Odoo.
if CONF.odoo.region_mapping:
regions = CONF.odoo.region_mapping.split(',')
self.region_mapping = dict([(r.split(":")[0],
r.split(":")[1]) for r in regions])
self.order = self.odoo.env['sale.order']
self.orderline = self.odoo.env['sale.order.line']
self.tenant = self.odoo.env['cloud.tenant']
self.partner = self.odoo.env['res.partner']
self.pricelist = self.odoo.env['product.pricelist']
self.product = self.odoo.env['product.product']
self.category = self.odoo.env['product.category']
def get_products(self, regions):
if not regions:
regions = [r.id for r in openstack.get_regions()]
if hasattr(self, 'region_mapping'):
regions = self.region_mapping.values()
else:
if hasattr(self, 'region_mapping'):
regions = [self.region_mapping.get(r) for r in regions]
prices = {}
for r in regions:
if not r:
continue
prices[r] = {}
for category in PRODUCT_CATEGORY:
prices[r][category.lower()] = []
c = self.category.search([('name', '=', category),
('display_name', 'ilike', r)])
product_ids = self.product.search([('categ_id', '=', c[0]),
('sale_ok', '=', True),
('active', '=', True)])
products = self.odoo.execute('product.product',
'read',
product_ids)
for p in products:
name = p['name_template'][len(r) + 1:]
if 'pre-prod' in name:
continue
price = round(p['lst_price'], 5)
# NOTE(flwang): default_code is Internal Reference on Odoo
# GUI
unit = p['default_code']
desc = p['description']
prices[r][category.lower()].append({'resource': name,
'price': price,
'unit': unit,
'description': desc})
return prices

View File

@ -0,0 +1,66 @@
# Copyright (C) 2017 Catalyst IT Ltd
#
# 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
from datetime import datetime
from datetime import timedelta
import mock
from distil.collector import ceilometer
from distil.tests.unit import base
FAKE_PROJECT = '123'
FAKE_METER = 'instance'
START = END = datetime.utcnow()
class CeilometerCollectorTest(base.DistilTestCase):
def setUp(self):
super(CeilometerCollectorTest, self).setUp()
meter_mapping_file = os.path.join(
os.environ["DISTIL_TESTS_CONFIGS_DIR"],
'meter_mappings.yaml'
)
self.conf.set_default(
'meter_mappings_file',
meter_mapping_file,
group='collector'
)
@mock.patch('distil.common.openstack.get_ceilometer_client')
def test_get_meter(self, mock_cclient):
class Sample(object):
def __init__(self, id, timestamp):
self.id = id
self.timestamp = timestamp
def to_dict(self):
return {'meter': 'instance', 'resource_id': self.id,
'timestamp': self.timestamp}
s1 = Sample('111', (datetime.utcnow() + timedelta(days=3)))
s2 = Sample('222', (datetime.utcnow() + timedelta(days=2)))
s3 = Sample('333', (datetime.utcnow() + timedelta(days=1)))
cclient = mock.Mock()
mock_cclient.return_value = cclient
cclient.new_samples.list.return_value = [s1, s2, s3]
collector = ceilometer.CeilometerCollector()
samples = collector.get_meter(FAKE_PROJECT, FAKE_METER, START, END)
expected = [s3.to_dict(), s2.to_dict(), s1.to_dict()]
self.assertEqual(expected, samples)