summaryrefslogtreecommitdiff
path: root/distil_ui
diff options
context:
space:
mode:
authorFeilong Wang <flwang@catalyst.net.nz>2017-05-29 10:46:33 +1200
committerFeilong Wang <flwang@catalyst.net.nz>2017-06-19 15:21:12 +1200
commit8fad6419b857d83fe1baac7e7230c69f9ab62768 (patch)
tree506a20681ff217f81c1a638e194aba9c4bfb1b83 /distil_ui
parentb1aad7dd19033af6aca3e6ae1d6ba567e0f090e5 (diff)
Improve test coverage
Notes
Notes (review): Code-Review+2: Feilong Wang <flwang@catalyst.net.nz> Workflow+1: Feilong Wang <flwang@catalyst.net.nz> Verified+2: Jenkins Submitted-by: Jenkins Submitted-at: Mon, 19 Jun 2017 22:17:36 +0000 Reviewed-on: https://review.openstack.org/471159 Project: openstack/distil-ui Branch: refs/heads/master
Diffstat (limited to 'distil_ui')
-rw-r--r--distil_ui/content/billing/tests.py389
-rw-r--r--distil_ui/test/api_tests/rest_api_tests.py287
-rw-r--r--distil_ui/test/helpers.py3
-rw-r--r--distil_ui/test/test_data.py18
4 files changed, 417 insertions, 280 deletions
diff --git a/distil_ui/content/billing/tests.py b/distil_ui/content/billing/tests.py
index 21c7e1c..e845501 100644
--- a/distil_ui/content/billing/tests.py
+++ b/distil_ui/content/billing/tests.py
@@ -1,4 +1,4 @@
1# Copyright (c) 2014 Catalyst IT Ltd. 1# Copyright (c) 2017 Catalyst IT Ltd.
2# 2#
3# Licensed under the Apache License, Version 2.0 (the "License"); 3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License. 4# you may not use this file except in compliance with the License.
@@ -12,34 +12,45 @@
12# See the License for the specific language governing permissions and 12# See the License for the specific language governing permissions and
13# limitations under the License. 13# limitations under the License.
14 14
15import collections
15import datetime 16import datetime
16import math 17import mock
17import time
18
19from mox3 import mox 18from mox3 import mox
20 19
21from distil_ui.api import distil 20from distil_ui.content.billing import base
21from distil_ui.content.billing import views
22from django.utils import timezone
23from horizon import forms
22from openstack_dashboard.test import helpers as test 24from openstack_dashboard.test import helpers as test
23 25
26BILLITEM = collections.namedtuple('BillItem',
27 ['id', 'resource', 'count', 'cost'])
28
24 29
25class FakeUser(object): 30class FakeUser(object):
26 roles = [{'name': 'admin'}] 31 roles = [{'name': 'admin'}]
32 authorized_tenants = ["tenant_name"]
27 33
34 def is_authenticated(self):
35 return True
28 36
29class FakeRequest(object):
30 user = FakeUser()
31 37
38class FakeRequest(object):
39 def _get(x, y):
40 if x == 'format' and y == 'html':
41 return 'csv'
42 return None
32 43
33class FakeDistilClient(object): 44 def is_ajax(self):
34 """A fake distil client for unit test.""" 45 return False
35 endpoint = 'http://localhost:8788'
36 request = FakeRequest()
37 46
38 def get_rated(self, tenant, start, end): 47 user = FakeUser()
39 raise NotImplemented() 48 session = mock.MagicMock()
49 GET = mock.MagicMock()
50 GET.get = _get
40 51
41 52
42class BillingTests(test.TestCase): 53class BaseBillingTests(test.TestCase):
43 """FIXME(flwang): Move this test to rest_api_tests.py 54 """FIXME(flwang): Move this test to rest_api_tests.py
44 55
45 Now we're putting the api test at here, since we don't want to hack 56 Now we're putting the api test at here, since we don't want to hack
@@ -48,240 +59,118 @@ class BillingTests(test.TestCase):
48 """ 59 """
49 60
50 def setUp(self): 61 def setUp(self):
51 super(BillingTests, self).setUp() 62 super(BaseBillingTests, self).setUp()
52 self.mocker = mox.Mox() 63 self.mocker = mox.Mox()
53 64 self.billing = base.BaseBilling(FakeRequest(), 'my_project_id')
54 def test_calculate_end_date(self): 65 self.year = 2017
55 start = datetime.date(2015, 1, 1) 66 self.month = 1
56 end = distil._calculate_end_date(start) 67 self.day = 30
57 self.assertEqual((end.year, end.month, end.day), (2015, 2, 1)) 68
58 69 def test_today(self):
59 start = datetime.date(2015, 6, 1) 70 delta = datetime.timedelta(seconds=1)
60 end = distil._calculate_end_date(start) 71 self.assertTrue(self.billing.today - timezone.now() < delta)
61 self.assertEqual((end.year, end.month, end.day), (2015, 7, 1)) 72
62 73 def test_get_start(self):
63 start = datetime.date(2015, 12, 1) 74 start = datetime.datetime(self.year, self.month, self.day, 0, 0, 0)
64 end = distil._calculate_end_date(start) 75 self.assertEqual(self.billing.get_start(self.year, self.month,
65 self.assertEqual((end.year, end.month, end.day), (2016, 1, 1)) 76 self.day),
66 77 timezone.make_aware(start, timezone.utc))
67 def test_get_month_cost(self): 78
68 distilclient = self.mocker.CreateMock(FakeDistilClient) 79 def test_get_end(self):
69 80 end = datetime.datetime(self.year, self.month, self.day, 23, 59, 59)
70 resources = {"fake_uuid_1": {"services": [{ 81 self.assertEqual(self.billing.get_end(self.year, self.month, self.day),
71 "volume": 2100, 82 timezone.make_aware(end, timezone.utc))
72 "rate": 0.0005, 83
73 "cost": 1.05, 84 def test_get_date_range(self):
74 "name": "b1.standard", 85 args_start = (self.billing.today.year, self.billing.today.month, 1)
75 "unit": "gigabyte"}], 86 args_end = (self.billing.today.year, self.billing.today.month,
76 "total_cost": 1.05, 87 self.billing.today.day)
77 "type": "Image", 88 start = self.billing.get_start(*args_start)
78 "name": "cirros"}, 89 end = self.billing.get_end(*args_end)
79 "fake_uuid_2": {"services": [{ 90 self.assertEqual(self.billing.get_date_range(),
80 "volume": 122, 91 (start, end))
81 "rate": 0.048, 92
82 "cost": 5.86, 93 @mock.patch('distil_ui.content.billing.base.BaseBilling.get_form')
83 "name": "m1.tiny", 94 def test_get_date_range_valid_form(self, mock_get_form):
84 "unit": "hour"}], 95 start = datetime.datetime(self.year, self.month, self.day, 0, 0, 0)
85 "total_cost": 5.86, 96 end = datetime.datetime(self.year, self.month, self.day, 23, 59, 59)
86 "type": "Virtual Machine", 97 myform = forms.DateForm({'start': start, 'end': end})
87 "name": "dfgh"}, 98 myform.data = {'start': start, 'end': end}
88 "fake_uuid_3": {"services": [{ 99 myform.cleaned_data = {'start': start, 'end': end}
89 "volume": 200, 100 mock_get_form.return_value = myform
90 "rate": 0.048, 101 self.assertEqual(self.billing.get_date_range(),
91 "cost": 9.60, 102 (timezone.make_aware(start, timezone.utc),
92 "name": "m1.tiny", 103 timezone.make_aware(end, timezone.utc)))
93 "unit": "hour"}], 104
94 "total_cost": 9.60, 105 def test_init_form(self):
95 "type": "Virtual Machine", 106 start = datetime.date(self.billing.today.year,
96 "name": "abcd"}, 107 self.billing.today.month, 1)
97 "fake_uuid_4": {"services": [{"volume": 20.00, 108 end = datetime.date.today()
98 "rate": 0.016, 109 self.assertEqual(self.billing.init_form(), (start, end))
99 "cost": 0.32, 110
100 "name": "n1.network", 111 def test_get_form(self):
101 "unit": "hour"}, 112 start = datetime.date(self.billing.today.year,
102 {"volume": 10.00, 113 self.billing.today.month, 1).strftime("%Y-%m-%d")
103 "rate": 0.016, 114 end = datetime.date.today().strftime("%Y-%m-%d")
104 "cost": 0.16, 115 self.assertEqual(self.billing.get_form().initial,
105 "name": "n1.network", 116 {"start": start, "end": end})
106 "unit": "hour"}], 117
107 "total_cost": 0.48, 118 def test_get_billing_list(self):
108 "type": "Network", 119 self.assertEqual(self.billing.get_billing_list(None, None), [])
109 "name": "public"} 120
110 } 121 def test_csv_link(self):
111 122 start = self.billing.today.strftime("%Y-%m-%d")
112 result = {'usage': {"end": "2011-03-01 00:00:00", "name": "openstack", 123 end = self.billing.today.strftime("%Y-%m-%d")
113 "total_cost": 7.23, 124 link = "?start={0}&end={1}&format=csv".format(start, end)
114 "tenant_id": "7c3c506ad4b943f5bb12b9fb69478084", 125 self.assertEqual(self.billing.csv_link(), link)
115 "start": "2011-02-01 00:00:00", 126
116 "resources": resources 127
117 } 128class IndexCsvRendererTest(test.TestCase):
118 } 129 def setUp(self):
119 130 super(IndexCsvRendererTest, self).setUp()
120 distilclient.get_rated([self.tenant.id], 131 request = FakeRequest()
121 '2011-02-01T00:00:00', 132 template = ""
122 '2011-03-01T00:00:00').AndReturn(result) 133 context = {"current_month": [BILLITEM(id=1, resource='N/A',
123 self.mocker.ReplayAll() 134 count=1, cost=2)]}
124 135 content_type = "text/csv"
125 cost = [()] 136 self.csvRenderer = views.IndexCsvRenderer(request=request,
126 distil._get_month_cost(distilclient, 137 template=template,
127 self.tenant.id, 138 context=context,
128 '2011-02-01T00:00:00', 139 content_type=content_type)
129 '2011-03-01T00:00:00', 140
130 cost, 0) 141 def test_get_row_data(self):
131 self.assertEqual(16.99, cost[0][0]) 142 data = list(self.csvRenderer.get_row_data())
132 self.assertEqual(3, len(cost[0][1])) 143 self.assertEqual(data, [('N/A', 1, u'2.00')])
133 bill_items = {} 144
134 for b in cost[0][1]: 145
135 # Convert cost to string make sure the floating number is right 146class ViewsTests(test.TestCase):
136 bill_items[b.resource] = (b.count, str(b.cost)) 147 def setUp(self):
137 148 super(ViewsTests, self).setUp()
138 self.assertEqual((2, '0.48'), bill_items['Network']) 149 project_id = "fake_project_id"
139 self.assertEqual((2, '15.46'), bill_items['Compute']) 150 self.view = views.IndexView()
140 self.assertEqual((1, '1.05'), bill_items['Image']) 151 self.view.request = FakeRequest()
141 152 self.view.billing = base.BaseBilling(self.request, project_id)
142 def test_calculate_history_date(self): 153
143 """Using the same algorithm to calculate the history date.""" 154 def test_get_template_names(self):
144 today = datetime.date(2015, 2, 17) 155 self.assertEqual(self.view.get_template_names(),
145 start = distil._calculate_start_date(datetime.date(2015, 2, 17)) 156 "management/billing/billing.csv")
146 end = distil._calculate_end_date(start) 157
147 final_end = datetime.datetime(today.year, today.month + 1, 1) 158 def test_get_content_type(self):
148 159 self.assertEqual(self.view.get_content_type(), "text/csv")
149 history_date = [None for i in range(12)] 160
150 for i in range(12): 161 def test_get_data(self):
151 start_str = start.strftime("%Y-%m-%dT00:00:00") 162 # TODO(flwang): Will add in next patch
152 end_str = end.strftime("%Y-%m-%dT00:00:00") 163 pass
153 history_date[i] = (start_str, end_str) 164
154 start = end 165 @mock.patch('horizon.tables.DataTableView.get_context_data')
155 end = distil._calculate_end_date(start) 166 def test_get_context_data(self, mock_get_context_data):
156 if end > final_end: 167 # TODO(flwang): Will add in next patch
157 break 168 pass
158 169
159 self.assertEqual(('2014-03-01T00:00:00', '2014-04-01T00:00:00'), 170 def test_render_to_response(self):
160 history_date[0]) 171 self.view.start = datetime.datetime.now()
161 self.assertEqual(('2014-04-01T00:00:00', '2014-05-01T00:00:00'), 172 self.view.end = datetime.datetime.now()
162 history_date[1]) 173 context = {"current_month": [BILLITEM(id=1, resource='N/A',
163 self.assertEqual(('2014-05-01T00:00:00', '2014-06-01T00:00:00'), 174 count=1, cost=2)]}
164 history_date[2]) 175 self.assertIsInstance(self.view.render_to_response(context),
165 self.assertEqual(('2014-06-01T00:00:00', '2014-07-01T00:00:00'), 176 views.IndexCsvRenderer)
166 history_date[3])
167 self.assertEqual(('2014-07-01T00:00:00', '2014-08-01T00:00:00'),
168 history_date[4])
169 self.assertEqual(('2014-08-01T00:00:00', '2014-09-01T00:00:00'),
170 history_date[5])
171 self.assertEqual(('2014-09-01T00:00:00', '2014-10-01T00:00:00'),
172 history_date[6])
173 self.assertEqual(('2014-10-01T00:00:00', '2014-11-01T00:00:00'),
174 history_date[7])
175 self.assertEqual(('2014-11-01T00:00:00', '2014-12-01T00:00:00'),
176 history_date[8])
177 self.assertEqual(('2014-12-01T00:00:00', '2015-01-01T00:00:00'),
178 history_date[9])
179 self.assertEqual(('2015-01-01T00:00:00', '2015-02-01T00:00:00'),
180 history_date[10])
181 self.assertEqual(('2015-02-01T00:00:00', '2015-03-01T00:00:00'),
182 history_date[11])
183
184 def test_get_cost(self):
185 distilclient = self.mocker.CreateMock(FakeDistilClient)
186
187 today = datetime.date.today()
188 start = distil._calculate_start_date(datetime.date.today())
189 end = distil._calculate_end_date(start)
190 final_end = datetime.datetime(today.year, today.month + 1, 1)
191
192 for i in range(12):
193 result = {'usage': {'total_cost': (i + 1) * 100,
194 'resources': {'uuid': {"services": [{
195 "volume": 2100,
196 "rate": 0.0005,
197 "cost": 1.05,
198 "name": "b1.standard",
199 "unit": "gigabyte"}],
200 "total_cost": 1.05,
201 "type": "Image",
202 "name": "cirros"}}}}
203 start_str = start.strftime("%Y-%m-%dT00:00:00")
204 end_str = end.strftime("%Y-%m-%dT00:00:00")
205 distilclient.get_rated([self.tenant.id],
206 start_str,
207 end_str).AndReturn(result)
208
209 start = end
210 end = distil._calculate_end_date(start)
211 if end > final_end:
212 break
213
214 self.mocker.ReplayAll()
215 setattr(self.request.user, 'tenant_id', self.tenant.id)
216 history_cost = distil.get_cost(self.request,
217 distil_client=distilclient,
218 enable_eventlet=False)
219 # 2 = math.ceil(1.05)
220 self.assertEqual([1.05 for i in range(12)],
221 [c[0] for c in history_cost])
222
223 def test_apply_discount(self):
224 # There are 3 scenarios for current month.
225 cost = (47.54,
226 [distil.BILLITEM(id=1, resource='Compute', count=9,
227 cost=31.76),
228 distil.BILLITEM(id=2, resource=u'Network', count=3, cost=1.5),
229 distil.BILLITEM(id=3, resource=u'Image', count=35, cost=3.82),
230 distil.BILLITEM(id=4, resource=u'Router', count=2, cost=0.96),
231 distil.BILLITEM(id=5, resource=u'Floating IP', count=21,
232 cost=3.57),
233 distil.BILLITEM(id=6, resource='Block Storage', count=22,
234 cost=6.08)
235 ], [])
236 prices = {u'Virtual Machine': 0.044, u'Network': 0.016,
237 u'Image': 0.0005, u'Volume': 0.0005,
238 u'Router': 0.017, u'Floating IP': 0.006}
239 start_str = '2015-07-01T00:00:00'
240 end_str = '2015-07-02T04:00:00'
241
242 cost_after_discount = distil._apply_discount(cost, start_str, end_str,
243 prices)
244 start = time.mktime(time.strptime(start_str, '%Y-%m-%dT%H:%M:%S'))
245 end = time.mktime(time.strptime(end_str, '%Y-%m-%dT%H:%M:%S'))
246 free_hours = math.floor((end - start) / 3600)
247
248 free_network_cost = round(0.016 * free_hours, 2)
249 free_router_cost = round(0.017 * free_hours, 2)
250
251 self.assertEqual(cost[0] - free_network_cost - free_router_cost,
252 cost_after_discount[0])
253
254 self.assertIn(distil.BILLITEM(id=2, resource=u'Network', count=3,
255 cost=1.05),
256 cost_after_discount[1])
257 self.assertIn(distil.BILLITEM(id=4, resource=u'Router', count=2,
258 cost=0.48),
259 cost_after_discount[1])
260
261 def test_get_month_cost_with_cache(self):
262 distil.CACHE.clear()
263 distilclient = self.mocker.CreateMock(FakeDistilClient)
264 result = {'usage': {'total_cost': 5.05,
265 'resources': {'uuid':
266 {"services": [{"volume": 2100,
267 "rate": 0.0005,
268 "cost": 5.05,
269 "name": "b1.standard",
270 "unit": "gigabyte"}],
271 "total_cost": 5.05,
272 "type": "Image",
273 "name": "cirros"}}}}
274 distilclient.get_rated([self.tenant.id],
275 '2011-02-01T00:00:00',
276 '2011-03-01T00:00:00').AndReturn(result)
277 self.mocker.ReplayAll()
278
279 cost = [()]
280 distil._get_month_cost(distilclient,
281 self.tenant.id,
282 '2011-02-01T00:00:00',
283 '2011-03-01T00:00:00',
284 cost, 0)
285 key = 'http://localhost:8788_1_2011-02-01T00:00:00_2011-03-01T00:00:00'
286 self.assertIn(key, distil.CACHE)
287 self.assertEqual(distil.CACHE[key][0], 5.05)
diff --git a/distil_ui/test/api_tests/rest_api_tests.py b/distil_ui/test/api_tests/rest_api_tests.py
index 5bda35e..1924385 100644
--- a/distil_ui/test/api_tests/rest_api_tests.py
+++ b/distil_ui/test/api_tests/rest_api_tests.py
@@ -1,8 +1,10 @@
1# Copyright (c) 2014 Catalyst IT Ltd.
2#
1# Licensed under the Apache License, Version 2.0 (the "License"); 3# Licensed under the Apache License, Version 2.0 (the "License");
2# you may not use this file except in compliance with the License. 4# you may not use this file except in compliance with the License.
3# You may obtain a copy of the License at 5# You may obtain a copy of the License at
4# 6#
5# http://www.apache.org/licenses/LICENSE-2.0 7# http://www.apache.org/licenses/LICENSE-2.0
6# 8#
7# Unless required by applicable law or agreed to in writing, software 9# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS, 10# distributed under the License is distributed on an "AS IS" BASIS,
@@ -10,19 +12,286 @@
10# See the License for the specific language governing permissions and 12# See the License for the specific language governing permissions and
11# limitations under the License. 13# limitations under the License.
12 14
15import datetime
16import math
13import mock 17import mock
18import time
19
20from mox3 import mox
21
22from distil_ui.api import distil
23from openstack_dashboard.test import helpers as test
24
25
26class FakeUser(object):
27 roles = [{'name': 'admin'}]
28 token = mock.MagicMock()
29 tenant_id = "fake"
30 services_region = "fake"
31
32
33class FakeRequest(object):
34 user = FakeUser()
35
36
37class FakeDistilClient(object):
38 """A fake distil client for unit test."""
39 endpoint = 'http://localhost:8788'
40 request = FakeRequest()
41
42 def get_rated(self, tenant, start, end):
43 raise NotImplemented()
44
45
46class BillingTests(test.TestCase):
47 """FIXME(flwang): Move this test to rest_api_tests.py
48
49 Now we're putting the api test at here, since we don't want to hack
50 horizon too much. That means we don't want to put the api.py under /api
51 folder, at least for now.
52 """
53
54 def setUp(self):
55 super(BillingTests, self).setUp()
56 self.mocker = mox.Mox()
57
58 @mock.patch("openstack_dashboard.api.base.url_for")
59 def test_init_distilclient(self, mock_url_for):
60 request = FakeRequest()
61 distilclient = distil.distilclient(request)
62 self.assertIsNotNone(distilclient)
63
64 def test_calculate_end_date(self):
65 start = datetime.date(2015, 1, 1)
66 end = distil._calculate_end_date(start)
67 self.assertEqual((end.year, end.month, end.day), (2015, 2, 1))
68
69 start = datetime.date(2015, 6, 1)
70 end = distil._calculate_end_date(start)
71 self.assertEqual((end.year, end.month, end.day), (2015, 7, 1))
72
73 start = datetime.date(2015, 12, 1)
74 end = distil._calculate_end_date(start)
75 self.assertEqual((end.year, end.month, end.day), (2016, 1, 1))
76
77 def test_get_month_cost(self):
78 distilclient = self.mocker.CreateMock(FakeDistilClient)
79
80 resources = {"fake_uuid_1": {"services": [{
81 "volume": 2100,
82 "rate": 0.0005,
83 "cost": 1.05,
84 "name": "b1.standard",
85 "unit": "gigabyte"}],
86 "total_cost": 1.05,
87 "type": "Image",
88 "name": "cirros"},
89 "fake_uuid_2": {"services": [{
90 "volume": 122,
91 "rate": 0.048,
92 "cost": 5.86,
93 "name": "m1.tiny",
94 "unit": "hour"}],
95 "total_cost": 5.86,
96 "type": "Virtual Machine",
97 "name": "dfgh"},
98 "fake_uuid_3": {"services": [{
99 "volume": 200,
100 "rate": 0.048,
101 "cost": 9.60,
102 "name": "m1.tiny",
103 "unit": "hour"}],
104 "total_cost": 9.60,
105 "type": "Virtual Machine",
106 "name": "abcd"},
107 "fake_uuid_4": {"services": [{"volume": 20.00,
108 "rate": 0.016,
109 "cost": 0.32,
110 "name": "n1.network",
111 "unit": "hour"},
112 {"volume": 10.00,
113 "rate": 0.016,
114 "cost": 0.16,
115 "name": "n1.network",
116 "unit": "hour"}],
117 "total_cost": 0.48,
118 "type": "Network",
119 "name": "public"}
120 }
121
122 result = {'usage': {"end": "2011-03-01 00:00:00", "name": "openstack",
123 "total_cost": 7.23,
124 "tenant_id": "7c3c506ad4b943f5bb12b9fb69478084",
125 "start": "2011-02-01 00:00:00",
126 "resources": resources
127 }
128 }
129
130 distilclient.get_rated([self.tenant.id],
131 '2011-02-01T00:00:00',
132 '2011-03-01T00:00:00').AndReturn(result)
133 self.mocker.ReplayAll()
134
135 cost = [()]
136 distil._get_month_cost(distilclient,
137 self.tenant.id,
138 '2011-02-01T00:00:00',
139 '2011-03-01T00:00:00',
140 cost, 0)
141 self.assertEqual(16.99, cost[0][0])
142 self.assertEqual(3, len(cost[0][1]))
143 bill_items = {}
144 for b in cost[0][1]:
145 # Convert cost to string make sure the floating number is right
146 bill_items[b.resource] = (b.count, str(b.cost))
147
148 self.assertEqual((2, '0.48'), bill_items['Network'])
149 self.assertEqual((2, '15.46'), bill_items['Compute'])
150 self.assertEqual((1, '1.05'), bill_items['Image'])
151
152 def test_calculate_history_date(self):
153 """Using the same algorithm to calculate the history date."""
154 today = datetime.date(2015, 2, 17)
155 start = distil._calculate_start_date(datetime.date(2015, 2, 17))
156 end = distil._calculate_end_date(start)
157 final_end = datetime.datetime(today.year, today.month + 1, 1)
158
159 history_date = [None for i in range(12)]
160 for i in range(12):
161 start_str = start.strftime("%Y-%m-%dT00:00:00")
162 end_str = end.strftime("%Y-%m-%dT00:00:00")
163 history_date[i] = (start_str, end_str)
164 start = end
165 end = distil._calculate_end_date(start)
166 if end > final_end:
167 break
168
169 self.assertEqual(('2014-03-01T00:00:00', '2014-04-01T00:00:00'),
170 history_date[0])
171 self.assertEqual(('2014-04-01T00:00:00', '2014-05-01T00:00:00'),
172 history_date[1])
173 self.assertEqual(('2014-05-01T00:00:00', '2014-06-01T00:00:00'),
174 history_date[2])
175 self.assertEqual(('2014-06-01T00:00:00', '2014-07-01T00:00:00'),
176 history_date[3])
177 self.assertEqual(('2014-07-01T00:00:00', '2014-08-01T00:00:00'),
178 history_date[4])
179 self.assertEqual(('2014-08-01T00:00:00', '2014-09-01T00:00:00'),
180 history_date[5])
181 self.assertEqual(('2014-09-01T00:00:00', '2014-10-01T00:00:00'),
182 history_date[6])
183 self.assertEqual(('2014-10-01T00:00:00', '2014-11-01T00:00:00'),
184 history_date[7])
185 self.assertEqual(('2014-11-01T00:00:00', '2014-12-01T00:00:00'),
186 history_date[8])
187 self.assertEqual(('2014-12-01T00:00:00', '2015-01-01T00:00:00'),
188 history_date[9])
189 self.assertEqual(('2015-01-01T00:00:00', '2015-02-01T00:00:00'),
190 history_date[10])
191 self.assertEqual(('2015-02-01T00:00:00', '2015-03-01T00:00:00'),
192 history_date[11])
193
194 def test_get_cost(self):
195 distilclient = self.mocker.CreateMock(FakeDistilClient)
196
197 today = datetime.date.today()
198 start = distil._calculate_start_date(datetime.date.today())
199 end = distil._calculate_end_date(start)
200 final_end = datetime.datetime(today.year, today.month + 1, 1)
201
202 for i in range(12):
203 result = {'usage': {'total_cost': (i + 1) * 100,
204 'resources': {'uuid': {"services": [{
205 "volume": 2100,
206 "rate": 0.0005,
207 "cost": 1.05,
208 "name": "b1.standard",
209 "unit": "gigabyte"}],
210 "total_cost": 1.05,
211 "type": "Image",
212 "name": "cirros"}}}}
213 start_str = start.strftime("%Y-%m-%dT00:00:00")
214 end_str = end.strftime("%Y-%m-%dT00:00:00")
215 distilclient.get_rated([self.tenant.id],
216 start_str,
217 end_str).AndReturn(result)
218
219 start = end
220 end = distil._calculate_end_date(start)
221 if end > final_end:
222 break
223
224 self.mocker.ReplayAll()
225 setattr(self.request.user, 'tenant_id', self.tenant.id)
226 history_cost = distil.get_cost(self.request,
227 distil_client=distilclient,
228 enable_eventlet=False)
229 # 2 = math.ceil(1.05)
230 self.assertEqual([1.05 for i in range(12)],
231 [c[0] for c in history_cost])
14 232
15from openstack_dashboard.test.test_data import utils 233 def test_apply_discount(self):
234 # There are 3 scenarios for current month.
235 cost = (47.54,
236 [distil.BILLITEM(id=1, resource='Compute', count=9,
237 cost=31.76),
238 distil.BILLITEM(id=2, resource=u'Network', count=3, cost=1.5),
239 distil.BILLITEM(id=3, resource=u'Image', count=35, cost=3.82),
240 distil.BILLITEM(id=4, resource=u'Router', count=2, cost=0.96),
241 distil.BILLITEM(id=5, resource=u'Floating IP', count=21,
242 cost=3.57),
243 distil.BILLITEM(id=6, resource='Block Storage', count=22,
244 cost=6.08)
245 ], [])
246 prices = {u'Virtual Machine': 0.044, u'Network': 0.016,
247 u'Image': 0.0005, u'Volume': 0.0005,
248 u'Router': 0.017, u'Floating IP': 0.006}
249 start_str = '2015-07-01T00:00:00'
250 end_str = '2015-07-02T04:00:00'
16 251
17from distil_ui.test import test_data 252 cost_after_discount = distil._apply_discount(cost, start_str, end_str,
253 prices)
254 start = time.mktime(time.strptime(start_str, '%Y-%m-%dT%H:%M:%S'))
255 end = time.mktime(time.strptime(end_str, '%Y-%m-%dT%H:%M:%S'))
256 free_hours = math.floor((end - start) / 3600)
18 257
19TEST = utils.TestData(test_data.data) 258 free_network_cost = round(0.016 * free_hours, 2)
259 free_router_cost = round(0.017 * free_hours, 2)
20 260
261 self.assertEqual(cost[0] - free_network_cost - free_router_cost,
262 cost_after_discount[0])
21 263
22def mock_resource(resource): 264 self.assertIn(distil.BILLITEM(id=2, resource=u'Network', count=3,
23 """Utility function to make mocking more DRY""" 265 cost=1.05),
266 cost_after_discount[1])
267 self.assertIn(distil.BILLITEM(id=4, resource=u'Router', count=2,
268 cost=0.48),
269 cost_after_discount[1])
24 270
25 mocked_data = \ 271 def test_get_month_cost_with_cache(self):
26 [mock.Mock(**{'to_dict.return_value': item}) for item in resource] 272 distil.CACHE.clear()
273 distilclient = self.mocker.CreateMock(FakeDistilClient)
274 result = {'usage': {'total_cost': 5.05,
275 'resources': {'uuid':
276 {"services": [{"volume": 2100,
277 "rate": 0.0005,
278 "cost": 5.05,
279 "name": "b1.standard",
280 "unit": "gigabyte"}],
281 "total_cost": 5.05,
282 "type": "Image",
283 "name": "cirros"}}}}
284 distilclient.get_rated([self.tenant.id],
285 '2011-02-01T00:00:00',
286 '2011-03-01T00:00:00').AndReturn(result)
287 self.mocker.ReplayAll()
27 288
28 return mocked_data 289 cost = [()]
290 distil._get_month_cost(distilclient,
291 self.tenant.id,
292 '2011-02-01T00:00:00',
293 '2011-03-01T00:00:00',
294 cost, 0)
295 key = 'http://localhost:8788_1_2011-02-01T00:00:00_2011-03-01T00:00:00'
296 self.assertIn(key, distil.CACHE)
297 self.assertEqual(distil.CACHE[key][0], 5.05)
diff --git a/distil_ui/test/helpers.py b/distil_ui/test/helpers.py
index 0e31976..e027adf 100644
--- a/distil_ui/test/helpers.py
+++ b/distil_ui/test/helpers.py
@@ -15,6 +15,3 @@ from openstack_dashboard.test import helpers
15 15
16class APITestCase(helpers.APITestCase): 16class APITestCase(helpers.APITestCase):
17 """Extends the base Horizon APITestCase for distilclient""" 17 """Extends the base Horizon APITestCase for distilclient"""
18
19 def setUp(self):
20 super(APITestCase, self).setUp()
diff --git a/distil_ui/test/test_data.py b/distil_ui/test/test_data.py
deleted file mode 100644
index c1c0e62..0000000
--- a/distil_ui/test/test_data.py
+++ /dev/null
@@ -1,18 +0,0 @@
1# Licensed under the Apache License, Version 2.0 (the "License");
2# you may not use this file except in compliance with the License.
3# You may obtain a copy of the License at
4#
5# http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS,
9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10# See the License for the specific language governing permissions and
11# limitations under the License.
12
13from openstack_dashboard.test.test_data import utils
14
15
16def data(TEST):
17 # Test Data Container in Horizon
18 TEST.queues = utils.TestDataContainer()