Browse Source

Improve test coverage

Change-Id: Iad45bf241db7a38efbb4c38b00f8f955f9810be7
Feilong Wang 1 year ago
parent
commit
8fad6419b8

+ 139
- 250
distil_ui/content/billing/tests.py View File

@@ -1,4 +1,4 @@
1
-# Copyright (c) 2014 Catalyst IT Ltd.
1
+# Copyright (c) 2017 Catalyst IT Ltd.
2 2
 #
3 3
 # Licensed under the Apache License, Version 2.0 (the "License");
4 4
 # you may not use this file except in compliance with the License.
@@ -12,34 +12,45 @@
12 12
 # See the License for the specific language governing permissions and
13 13
 # limitations under the License.
14 14
 
15
+import collections
15 16
 import datetime
16
-import math
17
-import time
18
-
17
+import mock
19 18
 from mox3 import mox
20 19
 
21
-from distil_ui.api import distil
20
+from distil_ui.content.billing import base
21
+from distil_ui.content.billing import views
22
+from django.utils import timezone
23
+from horizon import forms
22 24
 from openstack_dashboard.test import helpers as test
23 25
 
26
+BILLITEM = collections.namedtuple('BillItem',
27
+                                  ['id', 'resource', 'count', 'cost'])
28
+
24 29
 
25 30
 class FakeUser(object):
26 31
     roles = [{'name': 'admin'}]
32
+    authorized_tenants = ["tenant_name"]
27 33
 
34
+    def is_authenticated(self):
35
+        return True
28 36
 
29
-class FakeRequest(object):
30
-    user = FakeUser()
31 37
 
38
+class FakeRequest(object):
39
+    def _get(x, y):
40
+        if x == 'format' and y == 'html':
41
+            return 'csv'
42
+        return None
32 43
 
33
-class FakeDistilClient(object):
34
-    """A fake distil client for unit test."""
35
-    endpoint = 'http://localhost:8788'
36
-    request = FakeRequest()
44
+    def is_ajax(self):
45
+        return False
37 46
 
38
-    def get_rated(self, tenant, start, end):
39
-        raise NotImplemented()
47
+    user = FakeUser()
48
+    session = mock.MagicMock()
49
+    GET = mock.MagicMock()
50
+    GET.get = _get
40 51
 
41 52
 
42
-class BillingTests(test.TestCase):
53
+class BaseBillingTests(test.TestCase):
43 54
     """FIXME(flwang): Move this test to rest_api_tests.py
44 55
 
45 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 61
     def setUp(self):
51
-        super(BillingTests, self).setUp()
62
+        super(BaseBillingTests, self).setUp()
52 63
         self.mocker = mox.Mox()
53
-
54
-    def test_calculate_end_date(self):
55
-        start = datetime.date(2015, 1, 1)
56
-        end = distil._calculate_end_date(start)
57
-        self.assertEqual((end.year, end.month, end.day), (2015, 2, 1))
58
-
59
-        start = datetime.date(2015, 6, 1)
60
-        end = distil._calculate_end_date(start)
61
-        self.assertEqual((end.year, end.month, end.day), (2015, 7, 1))
62
-
63
-        start = datetime.date(2015, 12, 1)
64
-        end = distil._calculate_end_date(start)
65
-        self.assertEqual((end.year, end.month, end.day), (2016, 1, 1))
66
-
67
-    def test_get_month_cost(self):
68
-        distilclient = self.mocker.CreateMock(FakeDistilClient)
69
-
70
-        resources = {"fake_uuid_1": {"services": [{
71
-                                     "volume": 2100,
72
-                                     "rate": 0.0005,
73
-                                     "cost": 1.05,
74
-                                     "name": "b1.standard",
75
-                                     "unit": "gigabyte"}],
76
-                                     "total_cost": 1.05,
77
-                                     "type": "Image",
78
-                                     "name": "cirros"},
79
-                     "fake_uuid_2": {"services": [{
80
-                                     "volume": 122,
81
-                                     "rate": 0.048,
82
-                                     "cost": 5.86,
83
-                                     "name": "m1.tiny",
84
-                                     "unit": "hour"}],
85
-                                     "total_cost": 5.86,
86
-                                     "type": "Virtual Machine",
87
-                                     "name": "dfgh"},
88
-                     "fake_uuid_3": {"services": [{
89
-                                     "volume": 200,
90
-                                     "rate": 0.048,
91
-                                     "cost": 9.60,
92
-                                     "name": "m1.tiny",
93
-                                     "unit": "hour"}],
94
-                                     "total_cost": 9.60,
95
-                                     "type": "Virtual Machine",
96
-                                     "name": "abcd"},
97
-                     "fake_uuid_4": {"services": [{"volume": 20.00,
98
-                                                   "rate": 0.016,
99
-                                                   "cost": 0.32,
100
-                                                   "name": "n1.network",
101
-                                                   "unit": "hour"},
102
-                                                  {"volume": 10.00,
103
-                                                   "rate": 0.016,
104
-                                                   "cost": 0.16,
105
-                                                   "name": "n1.network",
106
-                                                   "unit": "hour"}],
107
-                                     "total_cost": 0.48,
108
-                                     "type": "Network",
109
-                                     "name": "public"}
110
-                     }
111
-
112
-        result = {'usage': {"end": "2011-03-01 00:00:00", "name": "openstack",
113
-                            "total_cost": 7.23,
114
-                            "tenant_id": "7c3c506ad4b943f5bb12b9fb69478084",
115
-                            "start": "2011-02-01 00:00:00",
116
-                            "resources": resources
117
-                            }
118
-                  }
119
-
120
-        distilclient.get_rated([self.tenant.id],
121
-                               '2011-02-01T00:00:00',
122
-                               '2011-03-01T00:00:00').AndReturn(result)
123
-        self.mocker.ReplayAll()
124
-
125
-        cost = [()]
126
-        distil._get_month_cost(distilclient,
127
-                               self.tenant.id,
128
-                               '2011-02-01T00:00:00',
129
-                               '2011-03-01T00:00:00',
130
-                               cost, 0)
131
-        self.assertEqual(16.99, cost[0][0])
132
-        self.assertEqual(3, len(cost[0][1]))
133
-        bill_items = {}
134
-        for b in cost[0][1]:
135
-            # Convert cost to string make sure the floating number is right
136
-            bill_items[b.resource] = (b.count, str(b.cost))
137
-
138
-        self.assertEqual((2, '0.48'), bill_items['Network'])
139
-        self.assertEqual((2, '15.46'), bill_items['Compute'])
140
-        self.assertEqual((1, '1.05'), bill_items['Image'])
141
-
142
-    def test_calculate_history_date(self):
143
-        """Using the same algorithm to calculate the history date."""
144
-        today = datetime.date(2015, 2, 17)
145
-        start = distil._calculate_start_date(datetime.date(2015, 2, 17))
146
-        end = distil._calculate_end_date(start)
147
-        final_end = datetime.datetime(today.year, today.month + 1, 1)
148
-
149
-        history_date = [None for i in range(12)]
150
-        for i in range(12):
151
-            start_str = start.strftime("%Y-%m-%dT00:00:00")
152
-            end_str = end.strftime("%Y-%m-%dT00:00:00")
153
-            history_date[i] = (start_str, end_str)
154
-            start = end
155
-            end = distil._calculate_end_date(start)
156
-            if end > final_end:
157
-                break
158
-
159
-        self.assertEqual(('2014-03-01T00:00:00', '2014-04-01T00:00:00'),
160
-                         history_date[0])
161
-        self.assertEqual(('2014-04-01T00:00:00', '2014-05-01T00:00:00'),
162
-                         history_date[1])
163
-        self.assertEqual(('2014-05-01T00:00:00', '2014-06-01T00:00:00'),
164
-                         history_date[2])
165
-        self.assertEqual(('2014-06-01T00:00:00', '2014-07-01T00:00:00'),
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)
64
+        self.billing = base.BaseBilling(FakeRequest(), 'my_project_id')
65
+        self.year = 2017
66
+        self.month = 1
67
+        self.day = 30
68
+
69
+    def test_today(self):
70
+        delta = datetime.timedelta(seconds=1)
71
+        self.assertTrue(self.billing.today - timezone.now() < delta)
72
+
73
+    def test_get_start(self):
74
+        start = datetime.datetime(self.year, self.month, self.day, 0, 0, 0)
75
+        self.assertEqual(self.billing.get_start(self.year, self.month,
76
+                                                self.day),
77
+                         timezone.make_aware(start, timezone.utc))
78
+
79
+    def test_get_end(self):
80
+        end = datetime.datetime(self.year, self.month, self.day, 23, 59, 59)
81
+        self.assertEqual(self.billing.get_end(self.year, self.month, self.day),
82
+                         timezone.make_aware(end, timezone.utc))
83
+
84
+    def test_get_date_range(self):
85
+        args_start = (self.billing.today.year, self.billing.today.month, 1)
86
+        args_end = (self.billing.today.year, self.billing.today.month,
87
+                    self.billing.today.day)
88
+        start = self.billing.get_start(*args_start)
89
+        end = self.billing.get_end(*args_end)
90
+        self.assertEqual(self.billing.get_date_range(),
91
+                         (start, end))
92
+
93
+    @mock.patch('distil_ui.content.billing.base.BaseBilling.get_form')
94
+    def test_get_date_range_valid_form(self, mock_get_form):
95
+        start = datetime.datetime(self.year, self.month, self.day, 0, 0, 0)
96
+        end = datetime.datetime(self.year, self.month, self.day, 23, 59, 59)
97
+        myform = forms.DateForm({'start': start, 'end': end})
98
+        myform.data = {'start': start, 'end': end}
99
+        myform.cleaned_data = {'start': start, 'end': end}
100
+        mock_get_form.return_value = myform
101
+        self.assertEqual(self.billing.get_date_range(),
102
+                         (timezone.make_aware(start, timezone.utc),
103
+                          timezone.make_aware(end, timezone.utc)))
104
+
105
+    def test_init_form(self):
106
+        start = datetime.date(self.billing.today.year,
107
+                              self.billing.today.month, 1)
108
+        end = datetime.date.today()
109
+        self.assertEqual(self.billing.init_form(), (start, end))
110
+
111
+    def test_get_form(self):
112
+        start = datetime.date(self.billing.today.year,
113
+                              self.billing.today.month, 1).strftime("%Y-%m-%d")
114
+        end = datetime.date.today().strftime("%Y-%m-%d")
115
+        self.assertEqual(self.billing.get_form().initial,
116
+                         {"start": start, "end": end})
117
+
118
+    def test_get_billing_list(self):
119
+        self.assertEqual(self.billing.get_billing_list(None, None), [])
120
+
121
+    def test_csv_link(self):
122
+        start = self.billing.today.strftime("%Y-%m-%d")
123
+        end = self.billing.today.strftime("%Y-%m-%d")
124
+        link = "?start={0}&end={1}&format=csv".format(start, end)
125
+        self.assertEqual(self.billing.csv_link(), link)
126
+
127
+
128
+class IndexCsvRendererTest(test.TestCase):
129
+    def setUp(self):
130
+        super(IndexCsvRendererTest, self).setUp()
131
+        request = FakeRequest()
132
+        template = ""
133
+        context = {"current_month": [BILLITEM(id=1, resource='N/A',
134
+                                              count=1, cost=2)]}
135
+        content_type = "text/csv"
136
+        self.csvRenderer = views.IndexCsvRenderer(request=request,
137
+                                                  template=template,
138
+                                                  context=context,
139
+                                                  content_type=content_type)
140
+
141
+    def test_get_row_data(self):
142
+        data = list(self.csvRenderer.get_row_data())
143
+        self.assertEqual(data, [('N/A', 1, u'2.00')])
144
+
145
+
146
+class ViewsTests(test.TestCase):
147
+    def setUp(self):
148
+        super(ViewsTests, self).setUp()
149
+        project_id = "fake_project_id"
150
+        self.view = views.IndexView()
151
+        self.view.request = FakeRequest()
152
+        self.view.billing = base.BaseBilling(self.request, project_id)
153
+
154
+    def test_get_template_names(self):
155
+        self.assertEqual(self.view.get_template_names(),
156
+                         "management/billing/billing.csv")
157
+
158
+    def test_get_content_type(self):
159
+        self.assertEqual(self.view.get_content_type(), "text/csv")
160
+
161
+    def test_get_data(self):
162
+        # TODO(flwang): Will add in next patch
163
+        pass
164
+
165
+    @mock.patch('horizon.tables.DataTableView.get_context_data')
166
+    def test_get_context_data(self, mock_get_context_data):
167
+        # TODO(flwang): Will add in next patch
168
+        pass
169
+
170
+    def test_render_to_response(self):
171
+        self.view.start = datetime.datetime.now()
172
+        self.view.end = datetime.datetime.now()
173
+        context = {"current_month": [BILLITEM(id=1, resource='N/A',
174
+                                              count=1, cost=2)]}
175
+        self.assertIsInstance(self.view.render_to_response(context),
176
+                              views.IndexCsvRenderer)

+ 278
- 9
distil_ui/test/api_tests/rest_api_tests.py View File

@@ -1,8 +1,10 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
1 3
 # Licensed under the Apache License, Version 2.0 (the "License");
2 4
 # you may not use this file except in compliance with the License.
3 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 9
 # Unless required by applicable law or agreed to in writing, software
8 10
 # distributed under the License is distributed on an "AS IS" BASIS,
@@ -10,19 +12,286 @@
10 12
 # See the License for the specific language governing permissions and
11 13
 # limitations under the License.
12 14
 
15
+import datetime
16
+import math
13 17
 import mock
18
+import time
19
+
20
+from mox3 import mox
21
+
22
+from distil_ui.api import distil
23
+from openstack_dashboard.test import helpers as test
24
+
25
+
26
+class FakeUser(object):
27
+    roles = [{'name': 'admin'}]
28
+    token = mock.MagicMock()
29
+    tenant_id = "fake"
30
+    services_region = "fake"
31
+
32
+
33
+class FakeRequest(object):
34
+    user = FakeUser()
35
+
36
+
37
+class 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
+
46
+class 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
 
15
-from 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
 
17
-from 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
 
19
-TEST = 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
 
22
-def mock_resource(resource):
23
-    """Utility function to make mocking more DRY"""
264
+        self.assertIn(distil.BILLITEM(id=2, resource=u'Network', count=3,
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 = \
26
-        [mock.Mock(**{'to_dict.return_value': item}) for item in resource]
271
+    def test_get_month_cost_with_cache(self):
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)

+ 0
- 3
distil_ui/test/helpers.py View File

@@ -15,6 +15,3 @@ from openstack_dashboard.test import helpers
15 15
 
16 16
 class APITestCase(helpers.APITestCase):
17 17
     """Extends the base Horizon APITestCase for distilclient"""
18
-
19
-    def setUp(self):
20
-        super(APITestCase, self).setUp()

+ 0
- 18
distil_ui/test/test_data.py View File

@@ -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
-
13
-from openstack_dashboard.test.test_data import utils
14
-
15
-
16
-def data(TEST):
17
-    # Test Data Container in Horizon
18
-    TEST.queues = utils.TestDataContainer()

+ 2
- 1
test-requirements.txt View File

@@ -26,4 +26,5 @@ testtools>=1.4.0 # MIT
26 26
 # This also needs xvfb library installed on your OS
27 27
 xvfbwrapper>=0.1.3 #license: MIT
28 28
 # Include horizon as test requirement
29
-http://tarballs.openstack.org/horizon/horizon-master.tar.gz#egg=horizon
29
+http://tarballs.openstack.org/horizon/horizon-master.tar.gz#egg=horizon
30
+

+ 13
- 0
tox.ini View File

@@ -25,6 +25,7 @@ commands = {posargs}
25 25
 
26 26
 [testenv:cover]
27 27
 commands =
28
+  pip install git+https://github.com/openstack/python-distilclient.git
28 29
   coverage erase
29 30
   coverage run {toxinidir}/manage.py test distil_ui
30 31
   coverage xml --omit '.tox/cover/*' -o 'cover/coverage.xml'
@@ -36,6 +37,18 @@ commands =
36 37
     pip install git+https://github.com/openstack/python-distilclient.git
37 38
     python manage.py test {posargs}
38 39
 
40
+[testenv:py27]
41
+basepython = python2.7
42
+commands =
43
+    pip install git+https://github.com/openstack/python-distilclient.git
44
+    python manage.py test {posargs}
45
+
46
+[testenv:py35]
47
+basepython = python3.5
48
+commands =
49
+    pip install git+https://github.com/openstack/python-distilclient.git
50
+    python manage.py test {posargs}
51
+
39 52
 [testenv:eslint]
40 53
 whitelist_externals = npm
41 54
 commands =

Loading…
Cancel
Save