Skip to content

Commit 0e90bb9

Browse files
committed
linting
1 parent b1190d8 commit 0e90bb9

File tree

3 files changed

+136
-69
lines changed

3 files changed

+136
-69
lines changed

coral_credits/api/db_exceptions.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ class NoResourceClass(Exception):
2121

2222
pass
2323

24+
2425
class ActiveConsumersInAllocation(Exception):
2526
"""Raised when trying to delete an allocation with active consumers"""
2627

coral_credits/api/views.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,17 @@
1515

1616
LOG = logging.getLogger(__name__)
1717

18+
1819
def destroy_if_no_active_consumers(linked_consumers_queryset, request, destroy_super):
19-
20+
2021
current_time = make_aware(datetime.now())
2122
for consumer in linked_consumers_queryset:
2223
if current_time < consumer.end:
2324
return _http_403_forbidden(repr(db_exceptions.ActiveConsumersInAllocation))
2425
else:
2526
return destroy_super.destroy(request)
2627

28+
2729
class CreditAllocationViewSet(viewsets.ModelViewSet):
2830
queryset = models.CreditAllocation.objects.all()
2931
serializer_class = serializers.CreditAllocationSerializer
@@ -91,7 +93,7 @@ def create(self, request, allocation_pk=None):
9193

9294
def update(self, request, allocation_pk=None, pk=None):
9395
return self._create_update_credit_allocations(request, allocation_pk)
94-
96+
9597
def destroy(self, request, allocation_pk=None, pk=None):
9698
resource = get_object_or_404(self.get_queryset(), pk=pk)
9799
linked_consumers = models.Consumer.objects.filter(
@@ -128,6 +130,7 @@ def destroy(self, request, pk=None):
128130
)
129131
return destroy_if_no_active_consumers(linked_consumers, request, super())
130132

133+
131134
class ResourceProviderAccountViewSet(viewsets.ModelViewSet):
132135
queryset = models.ResourceProviderAccount.objects.all()
133136
serializer_class = serializers.ResourceProviderAccountSerializer
@@ -206,7 +209,7 @@ def retrieve(self, request, pk=None):
206209
)
207210

208211
return Response(account_summary)
209-
212+
210213
def destroy(self, request, pk=None):
211214
account = get_object_or_404(self.queryset, pk=pk)
212215
linked_consumers = models.Consumer.objects.filter(
@@ -223,11 +226,13 @@ class ConsumerViewSet(viewsets.ModelViewSet):
223226
# TODO: need to split the Consumer and ConsumerRequest logic really
224227
def retrieve(self, request, pk=None):
225228
consumer = get_object_or_404(self.queryset, pk=pk)
226-
serializer = serializers.Consumer(consumer, context={'request': request})
229+
serializer = serializers.Consumer(consumer, context={"request": request})
227230
return Response(serializer.data)
228-
231+
229232
def list(self, request):
230-
serializer = serializers.Consumer(self.queryset, many=True, context={'request': request})
233+
serializer = serializers.Consumer(
234+
self.queryset, many=True, context={"request": request}
235+
)
231236
return Response(serializer.data)
232237

233238
@action(detail=False, methods=["post"], url_path="create")

tofu/tests/tofu_tests.py

Lines changed: 124 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -7,115 +7,146 @@
77
import uuid
88

99
coral_uri = os.environ.get("TF_VAR_coral_uri")
10-
headers = {"Authorization": "Bearer "+os.environ.get("TF_VAR_auth_token")}
10+
headers = {"Authorization": "Bearer " + os.environ.get("TF_VAR_auth_token")}
11+
1112

1213
def get_lease_request_json():
1314
start_time = datetime.now().strftime("%Y-%m-%d-%H:%M:%S")
1415
end_time = (datetime.now() + relativedelta(months=1)).strftime("%Y-%m-%d-%H:%M:%S")
1516
return {
16-
"context": {
17-
"user_id": "caa8b54a-eb5e-4134-8ae2-a3946a428ec7",
18-
"project_id": "c2eced313b324cdb8e670e6e30bf387d",
19-
"auth_url": "http://api.example.com:5000/v3",
20-
"region_name": "RegionOne"
21-
},
22-
"lease": {
23-
"id": str(uuid.uuid4()),
24-
"name": "my_new_lease",
25-
"start_date": start_time,
26-
"end_date": end_time,
27-
"reservations": [
28-
{ "amount": 2,
29-
"flavor_id": "e26a4241-b83d-4516-8e0e-8ce2665d1966",
30-
"resource_type": "flavor:instance",
31-
"affinity" : None,
32-
"allocations": []
33-
}
34-
],
35-
"resource_requests": {
36-
"DISK_GB": 35,
37-
"MEMORY_MB": 1000,
38-
"VCPU": 4
17+
"context": {
18+
"user_id": "caa8b54a-eb5e-4134-8ae2-a3946a428ec7",
19+
"project_id": "c2eced313b324cdb8e670e6e30bf387d",
20+
"auth_url": "http://api.example.com:5000/v3",
21+
"region_name": "RegionOne",
22+
},
23+
"lease": {
24+
"id": str(uuid.uuid4()),
25+
"name": "my_new_lease",
26+
"start_date": start_time,
27+
"end_date": end_time,
28+
"reservations": [
29+
{
30+
"amount": 2,
31+
"flavor_id": "e26a4241-b83d-4516-8e0e-8ce2665d1966",
32+
"resource_type": "flavor:instance",
33+
"affinity": None,
34+
"allocations": [],
3935
}
40-
}
41-
}
36+
],
37+
"resource_requests": {"DISK_GB": 35, "MEMORY_MB": 1000, "VCPU": 4},
38+
},
39+
}
4240

4341

4442
lease_request_json = get_lease_request_json()
4543

44+
4645
@pytest.fixture(scope="session")
4746
def terraform_rest_setup():
4847
working_dir = os.path.join(os.path.dirname(__file__), "..")
4948
var_file = os.path.join(working_dir, "tests", "tofu_configs", "initial.tfvars")
5049
delete_file = os.path.join(working_dir, "tests", "tofu_configs", "empty.tfvars")
51-
50+
5251
tf = Tofu(cwd=working_dir)
5352
tf.init()
54-
tf.apply(extra_args=["--var-file="+var_file])
53+
tf.apply(extra_args=["--var-file=" + var_file])
5554

5655
yield tf
5756

58-
destroy = tf.apply(extra_args=["--var-file="+delete_file])
57+
destroy = tf.apply(extra_args=["--var-file=" + delete_file])
5958
assert len(destroy.errors) == 0
6059

60+
6161
@pytest.fixture(scope="session")
6262
def add_consumer_request(terraform_rest_setup):
6363
# Add consumer outside of tofu to simulate requests from Blazar
6464

65-
consumer = requests.post(coral_uri+"/consumer/create",headers={
66-
"Authorization": "Bearer "+os.environ.get("TF_VAR_auth_token"),
67-
"Content-Type": "application/json"
68-
},
69-
json=lease_request_json
70-
)
71-
yield dict(status = consumer.status_code, tf_workspace = terraform_rest_setup)
72-
requests.post(coral_uri+"/consumer/on-end",headers={
73-
"Authorization": "Bearer "+os.environ.get("TF_VAR_auth_token"),
74-
"Content-Type": "application/json"
65+
consumer = requests.post(
66+
coral_uri + "/consumer/create",
67+
headers={
68+
"Authorization": "Bearer " + os.environ.get("TF_VAR_auth_token"),
69+
"Content-Type": "application/json",
7570
},
76-
json=lease_request_json
71+
json=lease_request_json,
7772
)
73+
yield dict(status=consumer.status_code, tf_workspace=terraform_rest_setup)
74+
7875

7976
@pytest.fixture(scope="session")
8077
def try_delete_active_allocation(add_consumer_request):
81-
delete_file = os.path.join(os.path.dirname(__file__), "..", "tests", "tofu_configs", "delete-active.tfvars")
82-
try_delete = add_consumer_request["tf_workspace"].apply(extra_args=["--var-file="+delete_file])
83-
return dict(error_count = len(try_delete.errors),tf_workspace = add_consumer_request["tf_workspace"])
78+
delete_file = os.path.join(
79+
os.path.dirname(__file__), "..", "tests", "tofu_configs", "delete-active.tfvars"
80+
)
81+
try_delete = add_consumer_request["tf_workspace"].apply(
82+
extra_args=["--var-file=" + delete_file]
83+
)
84+
return dict(
85+
error_count=len(try_delete.errors),
86+
tf_workspace=add_consumer_request["tf_workspace"],
87+
)
88+
8489

8590
@pytest.fixture(scope="session")
8691
def try_destroy_with_active_consumers(try_delete_active_allocation):
87-
all_file = os.path.join(os.path.dirname(__file__), "..", "tests", "tofu_configs", "initial.tfvars")
88-
delete_file = os.path.join(os.path.dirname(__file__), "..", "tests", "tofu_configs", "empty.tfvars")
89-
try_delete = try_delete_active_allocation["tf_workspace"].apply(extra_args=["--var-file="+delete_file])
92+
all_file = os.path.join(
93+
os.path.dirname(__file__), "..", "tests", "tofu_configs", "initial.tfvars"
94+
)
95+
delete_file = os.path.join(
96+
os.path.dirname(__file__), "..", "tests", "tofu_configs", "empty.tfvars"
97+
)
98+
try_delete = try_delete_active_allocation["tf_workspace"].apply(
99+
extra_args=["--var-file=" + delete_file]
100+
)
90101
yield len(try_delete.errors)
91102
# Undo any destroys
92-
reapply = try_delete_active_allocation["tf_workspace"].apply(extra_args=["--var-file="+all_file])
103+
reapply = try_delete_active_allocation["tf_workspace"].apply(
104+
extra_args=["--var-file=" + all_file]
105+
)
93106
assert len(reapply.errors) == 0
94107

95108

109+
@pytest.fixture(scope="session")
110+
def delete_consumer(try_destroy_with_active_consumers):
111+
requests.post(
112+
coral_uri + "/consumer/on-end",
113+
headers={
114+
"Authorization": "Bearer " + os.environ.get("TF_VAR_auth_token"),
115+
"Content-Type": "application/json",
116+
},
117+
json=lease_request_json,
118+
)
119+
return
120+
121+
96122
def api_get_request(resource):
97-
return requests.get(coral_uri+"/"+resource,headers=headers).json()
123+
return requests.get(coral_uri + "/" + resource, headers=headers).json()
124+
98125

99126
def contains_only(actual, expected):
100127
return len(actual) == len(expected) and set(expected).issubset(actual)
101128

129+
102130
def test_resource_classes_created(terraform_rest_setup):
103131
resp = api_get_request("resource_class")
104132
created_resource_classes = [c["name"] for c in resp]
105133

106134
assert contains_only(created_resource_classes, ["DISK_GB", "MEMORY_MB", "VCPU"])
107135

136+
108137
def test_resource_provider_created(terraform_rest_setup):
109138
providers = api_get_request("resource_provider")
110139
provider_names = [p["name"] for p in providers]
111-
140+
112141
assert contains_only(provider_names, ["Test Provider"])
113142

143+
114144
def test_accounts_created(terraform_rest_setup):
115145
accounts = api_get_request("account")
116146
account_names = [a["name"] for a in accounts]
117147

118-
assert contains_only(account_names, ["TestAccount1","TestAccount2"])
148+
assert contains_only(account_names, ["TestAccount1", "TestAccount2"])
149+
119150

120151
def test_rpas_created(terraform_rest_setup):
121152
rpas = api_get_request("resource_provider_account")
@@ -124,11 +155,13 @@ def test_rpas_created(terraform_rest_setup):
124155
account_urls = [a["url"] for a in accounts]
125156
assert contains_only(rpa_account_urls, account_urls)
126157

158+
127159
def test_allocations_created(terraform_rest_setup):
128160
allocations = api_get_request("allocation")
129161
allocations_names = [a["name"] for a in allocations]
130162

131-
assert contains_only(allocations_names, ["Q1-0","Q1-1","Q2-0"])
163+
assert contains_only(allocations_names, ["Q1-0", "Q1-1", "Q2-0"])
164+
132165

133166
def test_allocation_user_mappings(terraform_rest_setup):
134167
allocations = api_get_request("allocation")
@@ -141,9 +174,13 @@ def test_allocation_user_mappings(terraform_rest_setup):
141174
q1_allocated_accounts = [a["account"] for a in q1_allocations]
142175
q2_allocated_accounts = [a["account"] for a in q2_allocations]
143176

144-
assert contains_only(q1_allocated_accounts, [account_urls["TestAccount1"],account_urls["TestAccount2"]])
177+
assert contains_only(
178+
q1_allocated_accounts,
179+
[account_urls["TestAccount1"], account_urls["TestAccount2"]],
180+
)
145181
assert contains_only(q2_allocated_accounts, [account_urls["TestAccount1"]])
146182

183+
147184
def test_allocation_date_mappings(terraform_rest_setup):
148185
allocations = api_get_request("allocation")
149186
q1_allocations = [a for a in allocations if a["name"][:2] == "Q1"]
@@ -156,12 +193,17 @@ def test_allocation_date_mappings(terraform_rest_setup):
156193
assert len(q2_allocation_starts) == 1
157194
assert q1_allocation_starts[0] != q2_allocation_starts[0]
158195

196+
159197
def to_resource_map(allocation_resources):
160-
return {a["resource_class"]["name"] : a["resource_hours"] for a in allocation_resources}
198+
return {
199+
a["resource_class"]["name"]: a["resource_hours"] for a in allocation_resources
200+
}
201+
161202

162203
def test_only_allocation_resources_returned(terraform_rest_setup):
163204
allocation_id = api_get_request("allocation")[0]["id"]
164-
assert len(api_get_request("allocation/"+str(allocation_id)+"/resources")) == 3
205+
assert len(api_get_request("allocation/" + str(allocation_id) + "/resources")) == 3
206+
165207

166208
@pytest.mark.parametrize(
167209
"fixture_name, expected_resources",
@@ -183,46 +225,65 @@ def test_only_allocation_resources_returned(terraform_rest_setup):
183225
"Q2-0": {"VCPU": 80000, "MEMORY_MB": 8000000, "DISK_GB": 300000},
184226
},
185227
),
228+
(
229+
"delete_consumer",
230+
{
231+
# historical consumer consumption data should be preserved
232+
"Q1-0": {"VCPU": 37120, "MEMORY_MB": 3703680, "DISK_GB": 82800},
233+
"Q1-1": {"VCPU": 20000, "MEMORY_MB": 2000000, "DISK_GB": 200000},
234+
"Q2-0": {"VCPU": 80000, "MEMORY_MB": 8000000, "DISK_GB": 300000},
235+
},
236+
),
186237
],
187238
)
188-
def test_resource_allocations_have_correct_resources(request, fixture_name,expected_resources):
189-
request.getfixturevalue(fixture_name) # needed to dynamically set fixtures
239+
def test_resource_allocations_have_correct_resources(
240+
request, fixture_name, expected_resources
241+
):
242+
request.getfixturevalue(fixture_name) # needed to dynamically set fixtures
190243
allocations = api_get_request("allocation")
191244
allocation_resources = {
192-
a["name"]: to_resource_map(api_get_request("allocation/"+str(a["id"])+"/resources"))
245+
a["name"]: to_resource_map(
246+
api_get_request("allocation/" + str(a["id"]) + "/resources")
247+
)
193248
for a in allocations
194249
}
195250
assert allocation_resources["Q1-0"] == expected_resources["Q1-0"]
196251
assert allocation_resources["Q1-1"] == expected_resources["Q1-1"]
197252
assert allocation_resources["Q2-0"] == expected_resources["Q2-0"]
198253

199254

200-
def test_resources_still_consumed_after_consumer_delete():
201-
raise NotImplementedError()
202-
203255
def test_consumer_added_or_exists(add_consumer_request):
204256
assert add_consumer_request["status"] == 204
205257

258+
206259
def test_can_query_consumer(add_consumer_request):
207260
assert len(api_get_request("consumer")) == 1
208261

262+
209263
def test_delete_allocation_with_consumer_forbidden(try_delete_active_allocation):
210264
assert try_delete_active_allocation["error_count"] > 0
211265

266+
212267
def test_delete_active_allocation_resources_fails(try_delete_active_allocation):
213268
allocations = api_get_request("allocation")
214269
q1_allocations = [a for a in allocations if a["name"][:2] == "Q1"]
215270
for alloc in q1_allocations:
216-
tst = api_get_request("allocation/"+str(alloc["id"])+"/resources")
271+
tst = api_get_request("allocation/" + str(alloc["id"]) + "/resources")
217272
assert len(tst) == 3
218273

274+
219275
def test_destroy_with_consumers_fails(try_destroy_with_active_consumers):
220276
assert try_destroy_with_active_consumers > 0
221277

222-
def test_all_resources_fail_destroy_for_active_consumers(try_destroy_with_active_consumers):
278+
279+
def test_all_resources_fail_destroy_for_active_consumers(
280+
try_destroy_with_active_consumers,
281+
):
223282
assert len(api_get_request("resource_class")) == 3
224283
assert len(api_get_request("resource_provider")) == 1
225284
assert len(api_get_request("account")) == 2
226285
assert len(api_get_request("resource_provider_account")) == 2
227-
assert len(api_get_request("allocation")) == 2 #Q2 has no active consumers so destroyed
286+
assert (
287+
len(api_get_request("allocation")) == 2
288+
) # Q2 has no active consumers so destroyed
228289
assert len(api_get_request("consumer")) == 1

0 commit comments

Comments
 (0)