refactor: use assertEqualsWithDelta for float comparisons, add @internal to fake()

Replace Assert::assertEquals with Assert::assertEqualsWithDelta (epsilon 0.0001)
in assertSubTotal, assertTotal, and assertTotalQuantity to avoid IEEE 754
floating-point equality pitfalls. Add @internal docblock to fake() to signal
it is test-only. Add regression test for consecutive withItems calls.
This commit is contained in:
Joel Male
2026-05-27 21:35:49 +10:00
parent 8d04d18b48
commit a485bfb6f0
2 changed files with 20 additions and 6 deletions
+12 -6
View File
@@ -52,6 +52,9 @@ public function getDriver(): CartDriver
return $this->driver; return $this->driver;
} }
/**
* @internal For testing purposes only. Not intended for production use.
*/
public function fake(): CartFactory public function fake(): CartFactory
{ {
$this->driver = new NullDriver($this->driver->getSessionKey()); $this->driver = new NullDriver($this->driver->getSessionKey());
@@ -78,27 +81,30 @@ public function assertCount(int $count): void
public function assertTotalQuantity(int|float $quantity): void public function assertTotalQuantity(int|float $quantity): void
{ {
Assert::assertEquals( Assert::assertEqualsWithDelta(
$quantity, $quantity,
$this->getTotalQuantity(), (float) $this->getTotalQuantity(),
0.0001,
"Failed asserting that cart total quantity is [{$quantity}]." "Failed asserting that cart total quantity is [{$quantity}]."
); );
} }
public function assertSubTotal(float $amount): void public function assertSubTotal(float $amount): void
{ {
Assert::assertEquals( Assert::assertEqualsWithDelta(
$amount, $amount,
$this->getSubTotal(false), (float) $this->getSubTotal(false),
0.0001,
"Failed asserting that cart subtotal is [{$amount}]." "Failed asserting that cart subtotal is [{$amount}]."
); );
} }
public function assertTotal(float $amount): void public function assertTotal(float $amount): void
{ {
Assert::assertEquals( Assert::assertEqualsWithDelta(
$amount, $amount,
$this->getTotal(), (float) $this->getTotal(),
0.0001,
"Failed asserting that cart total is [{$amount}]." "Failed asserting that cart total is [{$amount}]."
); );
} }
+8
View File
@@ -58,6 +58,14 @@ function makeCartForFactory(): Cart
expect(array_unique($ids))->toHaveCount(3); expect(array_unique($ids))->toHaveCount(3);
}); });
test('consecutive withItems calls produce unique IDs', function () {
$this->factory->withItems(2)->withItems(2);
$ids = $this->cart->getContent()->keys()->toArray();
expect(array_unique($ids))->toHaveCount(4);
expect($this->cart->getContent()->count())->toBe(4);
});
test('withCoupon adds a coupon condition to the cart', function () { test('withCoupon adds a coupon condition to the cart', function () {
$coupon = new class extends \Wearepixel\Cart\Coupons\Coupon { $coupon = new class extends \Wearepixel\Cart\Coupons\Coupon {
protected string $code = 'SAVE10'; protected string $code = 'SAVE10';