Skip to content

Commit 9987599

Browse files
authored
Merge pull request #55 from synkd/implement_session-scoped_inventory
Use session-scoped inventory by default
2 parents 5821185 + 89488f9 commit 9987599

File tree

4 files changed

+66
-28
lines changed

4 files changed

+66
-28
lines changed

manifester/commands.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ def inventory(details, sync, offline_token):
8080
border = "-" * 38
8181
if sync:
8282
helpers.update_inventory(
83-
Manifester(minimal_init=True, offline_token=offline_token).subscription_allocations
83+
Manifester(minimal_init=True, offline_token=offline_token).subscription_allocations,
84+
sync=True,
8485
)
8586
inv = helpers.load_inventory_file(Path(settings.inventory_path))
8687
if not details:

manifester/helpers.py

+35-7
Original file line numberDiff line numberDiff line change
@@ -171,15 +171,43 @@ def load_inventory_file(file):
171171
return yaml.load(f, Loader=yaml.FullLoader) or []
172172

173173

174-
def update_inventory(inventory_data):
174+
def _dump_inventory_file(inventory_path, inventory):
175+
"""Write inventory data to local inventory file."""
176+
with inventory_path.open("w") as inventory_file:
177+
yaml.dump(inventory, inventory_file, allow_unicode=True)
178+
179+
180+
def _update_inventory(inventory_path, inventory, allocation):
181+
"""Add new allocation, remove and recreate inventory file."""
182+
inventory.append(allocation)
183+
inventory_path.unlink()
184+
inventory_path.touch()
185+
_dump_inventory_file(inventory_path, inventory)
186+
187+
188+
def update_inventory(inventory_data, sync=False, remove=False, uuid=None):
175189
"""Replace the existing inventory file with current subscription allocations."""
176190
inventory_path = Path(settings.inventory_path)
177-
if load_inventory_file(inventory_path):
178-
inventory_path.unlink()
179-
inventory_path.touch()
180-
if inventory_data != []:
181-
with inventory_path.open("w") as inventory_file:
182-
yaml.dump(inventory_data, inventory_file, allow_unicode=True)
191+
if sync:
192+
if load_inventory_file(inventory_path):
193+
inventory_path.unlink()
194+
inventory_path.touch()
195+
if inventory_data != []:
196+
_dump_inventory_file(inventory_path, inventory_data)
197+
elif remove:
198+
inv = load_inventory_file(inventory_path)
199+
_dump_inventory_file(inventory_path, [alloc for alloc in inv if uuid not in alloc["uuid"]])
200+
else:
201+
current_allocation = next(
202+
iter([alloc for alloc in inventory_data if alloc["uuid"] == uuid])
203+
)
204+
inv = load_inventory_file(inventory_path)
205+
uuids = [alloc["uuid"] for alloc in inv]
206+
if current_allocation["uuid"] not in uuids:
207+
_update_inventory(inventory_path, inv, current_allocation)
208+
else:
209+
inv = [alloc for alloc in inv if uuid not in alloc["uuid"]]
210+
_update_inventory(inventory_path, inv, current_allocation)
183211

184212

185213
def fake_http_response_code(good_codes=None, bad_codes=None, fail_rate=0):

manifester/manifester.py

+11-13
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,9 @@ def create_subscription_allocation(self):
170170
cmd_kwargs=allocation_data,
171171
).json()
172172
logger.debug(f"Received response {self.allocation} when attempting to create allocation.")
173-
self.allocation_uuid = self.allocation["body"]["uuid"]
173+
self.allocation_uuid = (
174+
self.allocation.uuid if self.is_mock else self.allocation["body"]["uuid"]
175+
)
174176
if self.simple_content_access == "disabled":
175177
simple_retry(
176178
self.requester.put,
@@ -185,7 +187,7 @@ def create_subscription_allocation(self):
185187
f"Subscription allocation created with name {self.allocation_name} "
186188
f"and UUID {self.allocation_uuid}"
187189
)
188-
update_inventory(self.subscription_allocations)
190+
update_inventory(self.subscription_allocations, uuid=self.allocation_uuid)
189191
return self.allocation_uuid
190192

191193
def delete_subscription_allocation(self, uuid=None):
@@ -196,14 +198,14 @@ def delete_subscription_allocation(self, uuid=None):
196198
"proxies": self.manifest_data.get("proxies"),
197199
"params": {"force": "true"},
198200
}
199-
if self.is_mock:
200-
self.allocation_uuid = self.allocation_uuid.uuid
201201
response = simple_retry(
202202
self.requester.delete,
203203
cmd_args=[f"{self.allocations_url}/{uuid if uuid else self.allocation_uuid}"],
204204
cmd_kwargs=data,
205205
)
206-
update_inventory(self.subscription_allocations)
206+
update_inventory(
207+
self.subscription_allocations, remove=True, uuid=uuid if uuid else self.allocation_uuid
208+
)
207209
return response
208210

209211
def add_entitlements_to_allocation(self, pool_id, entitlement_quantity):
@@ -322,15 +324,15 @@ def process_subscription_pools(self, subscription_pools, subscription_data):
322324
f"{subscription_data['name']} to the allocation."
323325
)
324326
self._active_pools.append(match)
325-
update_inventory(self.subscription_allocations)
327+
update_inventory(self.subscription_allocations, uuid=self.allocation_uuid)
326328
break
327329
elif add_entitlements.status_code == SUCCESS_CODE:
328330
logger.debug(
329331
f"Successfully added {subscription_data['quantity']} entitlements of "
330332
f"{subscription_data['name']} to the allocation."
331333
)
332334
self._active_pools.append(match)
333-
update_inventory(self.subscription_allocations)
335+
update_inventory(self.subscription_allocations, uuid=self.allocation_uuid)
334336
break
335337
else:
336338
raise RuntimeError(
@@ -405,11 +407,8 @@ def trigger_manifest_export(self):
405407
local_file.write_bytes(manifest.content)
406408
manifest.path = local_file
407409
manifest.name = self.manifest_name
408-
if self.is_mock:
409-
manifest.uuid = self.allocation_uuid.uuid
410-
else:
411-
manifest.uuid = self.allocation_uuid
412-
update_inventory(self.subscription_allocations)
410+
manifest.uuid = self.allocation_uuid
411+
update_inventory(self.subscription_allocations, uuid=self.allocation_uuid)
413412
return manifest
414413

415414
def get_manifest(self):
@@ -437,4 +436,3 @@ def __enter__(self):
437436
def __exit__(self, *tb_args):
438437
"""Deletes subscription allocation on teardown unless using CLI."""
439438
self.delete_subscription_allocation()
440-
update_inventory(self.subscription_allocations)

tests/test_manifester.py

+18-7
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,13 @@
8282
+ "".join(random.choices(string.ascii_letters, k=8)),
8383
"type": "Satellite",
8484
"version": f"{MANIFEST_DATA['sat_version']}",
85-
"entitlementQuantity": sum(d["quantity"] for d in MANIFEST_DATA["subscription_data"]),
86-
"url": f"{MANIFEST_DATA['url']['allocations']}/{SUB_ALLOCATION_UUID}",
85+
"entitlementsAttachedQuantity": sum(
86+
d["quantity"] for d in MANIFEST_DATA["subscription_data"]
87+
),
8788
"simpleContentAccess": f"{MANIFEST_DATA['simple_content_access']}",
8889
}
89-
]
90+
],
91+
"status_code": 200,
9092
}
9193

9294

@@ -148,9 +150,9 @@ def get(self, *args, **kwargs):
148150
self.pool_response["body"] += SUB_POOL_RESPONSE["body"]
149151
return self
150152
if args[0].endswith("allocations") and self._has_offset:
151-
if kwargs["params"]["offset"] != 50:
153+
if kwargs["params"]["offset"] != 100:
152154
self.allocations_response = {"body": []}
153-
for _x in range(50):
155+
for _x in range(100):
154156
self.allocations_response["body"].append(
155157
{
156158
"uuid": f"{uuid.uuid4().hex}",
@@ -197,6 +199,15 @@ def delete(self, *args, **kwargs):
197199
self._good_codes = [204]
198200
return self
199201

202+
def __repr__(self):
203+
"""Return a string representation of the RhsmApiStub instance."""
204+
inner = ", ".join(
205+
f"{k}={v}"
206+
for k, v in self.__dict__.items()
207+
if not k.startswith("_") and not callable(v)
208+
)
209+
return f"{self.__class__.__name__}({inner})"
210+
200211

201212
def test_basic_init():
202213
"""Test that manifester can initialize with the minimum required arguments."""
@@ -211,7 +222,7 @@ def test_create_allocation():
211222
"""Test that manifester's create_subscription_allocation method returns a UUID."""
212223
manifester = Manifester(manifest_category=MANIFEST_DATA, requester=RhsmApiStub(in_dict=None))
213224
allocation_uuid = manifester.create_subscription_allocation()
214-
assert allocation_uuid.uuid == SUB_ALLOCATION_UUID
225+
assert allocation_uuid == SUB_ALLOCATION_UUID
215226

216227

217228
def test_negative_simple_retry_timeout():
@@ -300,7 +311,7 @@ def test_invalid_sat_version():
300311
def test_update_inventory():
301312
"""Test that inventory file is populated with expected contents after updating."""
302313
manifester = Manifester(manifest_category=MANIFEST_DATA, requester=RhsmApiStub(in_dict=None))
303-
update_inventory(manifester.subscription_allocations)
314+
update_inventory(manifester.subscription_allocations, sync=True, uuid=SUB_ALLOCATION_UUID)
304315
assert (
305316
load_inventory_file(Path(MANIFEST_DATA["inventory_path"]))
306317
== SUB_ALLOCATIONS_RESPONSE["body"]

0 commit comments

Comments
 (0)