mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-10-25 18:40:06 -04:00
Strip whitespace from inventory item string values on save
modules/inventory/common.py: _normalize_items now strips leading/trailing whitespace from any string-valued item field before persisting an inventory (name, category, subcategory, location, etc.). Non-string values (numbers, None) are left untouched. Closes #52
This commit is contained in:
parent
540081203f
commit
adce235a7e
2 changed files with 15 additions and 2 deletions
|
|
@ -55,7 +55,7 @@ def _allowed_item_keys(fields_: list) -> set:
|
|||
|
||||
|
||||
def _normalize_items(items: list, fields_: list) -> list:
|
||||
"""Filter each item to the schema's allowed keys and assign stable ids (fresh id for any missing/duplicate)."""
|
||||
"""Filter each item to the schema's allowed keys, strip whitespace from string values, and assign stable ids (fresh id for any missing/duplicate)."""
|
||||
if not isinstance(items, list):
|
||||
raise ValidationError('items must be a list')
|
||||
allowed = _allowed_item_keys(fields_)
|
||||
|
|
@ -63,7 +63,7 @@ def _normalize_items(items: list, fields_: list) -> list:
|
|||
used = set()
|
||||
normalized = []
|
||||
for raw in items:
|
||||
clean = {k: v for k, v in raw.items() if k in allowed}
|
||||
clean = {k: (v.strip() if isinstance(v, str) else v) for k, v in raw.items() if k in allowed}
|
||||
item_id = raw.get('id')
|
||||
if not isinstance(item_id, int) or item_id in used:
|
||||
counter += 1
|
||||
|
|
|
|||
|
|
@ -68,6 +68,19 @@ def test_save_inventory_items(food_inventory_factory, test_inventory_configs):
|
|||
assert [i['name'] for i in saved['items']] == ['Rice']
|
||||
|
||||
|
||||
def test_save_inventory_strips_whitespace(food_inventory_factory, test_inventory_configs):
|
||||
"""Leading/trailing whitespace in string field values is stripped on save (categories, names, etc.)."""
|
||||
config = test_inventory_configs
|
||||
slug = food_inventory_factory()
|
||||
saved = config.save_inventory(slug, dict(items=[
|
||||
dict(name=' Rice ', category=' grains ', count='4'),
|
||||
]))
|
||||
item = saved['items'][0]
|
||||
assert item['name'] == 'Rice'
|
||||
assert item['category'] == 'grains'
|
||||
assert item['count'] == '4'
|
||||
|
||||
|
||||
def test_save_inventory_fields(food_inventory_factory, test_inventory_configs):
|
||||
config = test_inventory_configs
|
||||
slug = food_inventory_factory()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue