diff --git a/spoolman/api/v1/spool.py b/spoolman/api/v1/spool.py index 8bec54c..e133df2 100644 --- a/spoolman/api/v1/spool.py +++ b/spoolman/api/v1/spool.py @@ -42,12 +42,12 @@ class SpoolParameters(BaseModel): ) initial_weight: Optional[float] = Field( ge=0, - description="The initial total weight of the filament and spool. (gross weight)", + description="The initial total weight of the filament and spool, in g. (gross weight)", example=200, ) empty_weight: Optional[float] = Field( ge=0, - description="The weight of an empty spool. (tare weight)", + description="The weight of an empty spool, in g. (tare weight)", example=200, ) remaining_weight: Optional[float] = Field( @@ -86,7 +86,7 @@ class SpoolUseParameters(BaseModel): class SpoolMeasureParameters(BaseModel): - weight: float = Field(description="Current gross weight of the spool.", example=200) + weight: float = Field(description="Current gross weight of the spool, in g.", example=200) @router.get( diff --git a/spoolman/api/v1/vendor.py b/spoolman/api/v1/vendor.py index a7fad79..7803c46 100644 --- a/spoolman/api/v1/vendor.py +++ b/spoolman/api/v1/vendor.py @@ -35,7 +35,7 @@ class VendorParameters(BaseModel): ) empty_spool_weight: Optional[float] = Field( ge=0, - description="The weight of an empty spool.", + description="The weight of an empty spool, in g.", example=200, ) extra: Optional[dict[str, str]] = Field( diff --git a/spoolman/database/spool.py b/spoolman/database/spool.py index 849fea3..a6919fa 100644 --- a/spoolman/database/spool.py +++ b/spoolman/database/spool.py @@ -56,12 +56,15 @@ async def create( # Calculate initial_weight if not provided if initial_weight is None and filament_item.weight is not None: - initial_weight = filament_item.weight - (empty_weight if empty_weight is not None else 0) + initial_weight = filament_item.weight + (empty_weight if empty_weight is not None else 0) if used_weight is None: if remaining_weight is not None: if initial_weight is None or initial_weight == 0: - raise ItemCreateError("remaining_weight can only be used if the initial_weight is defined.") + raise ItemCreateError( + "remaining_weight can only be used if the initial_weight is " + "defined or the filament has a weight set.", + ) used_weight = max(initial_weight - empty_weight - remaining_weight, 0) else: used_weight = 0 @@ -352,7 +355,7 @@ async def measure(db: AsyncSession, spool_id: int, weight: float) -> models.Spoo initial_weight = spool_info[0] empty_weight = spool_info[2] - if initial_weight is None or empty_weight is None: + if initial_weight is None or initial_weight == 0 or empty_weight is None or empty_weight == 0: # Get filament weight and spool_weight result = await db.execute( sqlalchemy.select(models.Filament.weight, models.Filament.spool_weight) @@ -363,11 +366,15 @@ async def measure(db: AsyncSession, spool_id: int, weight: float) -> models.Spoo filament_info = result.one() except NoResultFound as exc: raise ItemNotFoundError("Filament not found for spool.") from exc - if empty_weight is None: + + if empty_weight is None or empty_weight == 0: empty_weight = filament_info[1] - if initial_weight is None: - initial_weight = filament_info[0] + empty_weight + if initial_weight is None or initial_weight == 0: + initial_weight = (filament_info[0] if filament_info[0] is not None else 0) + empty_weight + + if initial_weight is None or initial_weight == 0: + raise SpoolMeasureError("Initial weight is not set.") # Calculate the current gross weight (initial_weight - used_weight) current_use = initial_weight - spool_info[1] diff --git a/tests_integration/tests/spool/test_measure.py b/tests_integration/tests/spool/test_measure.py index c02f25a..13e3552 100644 --- a/tests_integration/tests/spool/test_measure.py +++ b/tests_integration/tests/spool/test_measure.py @@ -142,3 +142,55 @@ def test_measure_spool_sequence(random_filament: dict[str, Any], measurements: l # Clean up httpx.delete(f"{URL}/api/v1/spool/{spool['id']}").raise_for_status() + + +@pytest.mark.parametrize("measurements", [[1244, 1233, 1200], [1000, 900, 800], [1000, 1000, 1000]]) +def test_measure_spool_empty(random_empty_filament: dict[str, Any], measurements: list[float]): + """Test using a spool in the database.""" + # Setup + initial_weight = 1255 + current_weight = initial_weight + empty_weight = 246 + start_weight = 1000 + result = httpx.post( + f"{URL}/api/v1/spool", + json={ + "filament_id": random_empty_filament["id"], + "remaining_weight": start_weight, + "initial_weight": initial_weight, + "empty_weight": empty_weight, + }, + ) + result.raise_for_status() + spool = result.json() + + for m in measurements: + # Execute + result = httpx.put( + f"{URL}/api/v1/spool/{spool['id']}/measure", + json={ + "weight": m, + }, + ) + result.raise_for_status() + + # Verify + spool = result.json() + # remaining_weight should be clamped so it's never negative, + # but used_weight should not be clamped to the net weight + expected_use = min(initial_weight - m, initial_weight - empty_weight) + assert spool["used_weight"] == pytest.approx(expected_use) + expected_remaining = max(m - empty_weight, 0) + assert spool["remaining_weight"] == pytest.approx(expected_remaining) + # Verify that first_used has been updated + diff = abs((datetime.now(tz=timezone.utc) - datetime.fromisoformat(spool["first_used"])).total_seconds()) + assert diff < 60 + + # Verify that last_used has been updated + diff = abs((datetime.now(tz=timezone.utc) - datetime.fromisoformat(spool["last_used"])).total_seconds()) + assert diff < 60 + + current_weight = current_weight - expected_use + + # Clean up + httpx.delete(f"{URL}/api/v1/spool/{spool['id']}").raise_for_status()