diff --git a/tests/system/Database/Live/FabricatorLiveTest.php b/tests/system/Database/Live/FabricatorLiveTest.php index 2bd25482fb66..9b161778b0e0 100644 --- a/tests/system/Database/Live/FabricatorLiveTest.php +++ b/tests/system/Database/Live/FabricatorLiveTest.php @@ -51,7 +51,7 @@ public function testCreateAddsCountToDatabase(): void // Some countries violate the 40 character limit so override that $fabricator->setOverrides(['country' => 'France']); - + $fabricator->setUnique('email'); $fabricator->create($count); $this->seeNumRecords($count, 'user', []); diff --git a/tests/system/Test/FabricatorTest.php b/tests/system/Test/FabricatorTest.php index 787ed82b9b5e..f00cf6f5f81a 100644 --- a/tests/system/Test/FabricatorTest.php +++ b/tests/system/Test/FabricatorTest.php @@ -14,6 +14,7 @@ namespace CodeIgniter\Test; use CodeIgniter\Config\Factories; +use CodeIgniter\Model; use Tests\Support\Models\EntityModel; use Tests\Support\Models\EventModel; use Tests\Support\Models\FabricatorModel; @@ -491,4 +492,60 @@ public function testResetClearsValue(): void $this->assertSame(0, Fabricator::getCount('giants')); } + + public function testUniqueSetsOutUniqueFieldValues(): void + { + $model = new class () extends Model { + protected $allowedFields = ['email']; + protected $returnType = 'array'; + }; + + $result = (new Fabricator($model)) + ->setUnique('email') + ->make(5000); + + $result = array_map(static fn (array $email): string => $email['email'], $result); + + $this->assertSame(array_unique($result), $result); + } + + public function testOptionalSetsOutOptionalFieldValues(): void + { + $model = new class () extends Model { + protected $allowedFields = ['email']; + protected $returnType = 'array'; + }; + + $result = (new Fabricator($model)) + ->setOptional('email', 0.5, false) // 50% probability of email being `false` + ->make(5000); + + $result = array_map(static fn (array $email) => $email['email'], $result); + + $this->assertLessThan( + count($result), + count(array_filter($result)) + ); + } + + public function testValidSetsOutValidValuesUsingCallback(): void + { + $model = new class () extends Model { + protected $allowedFields = ['digit']; + protected $returnType = 'array'; + }; + + $result = (new Fabricator($model, ['digit' => 'numberBetween'])) + ->setValid('digit', static fn (int $digit): bool => $digit % 2 === 0) + ->make(5000); + $result = array_map(static fn (array $digit): int => $digit['digit'], $result); + + foreach ($result as $digit) { + $this->assertSame( + 0, + $digit % 2, + sprintf('Failed asserting that %s is even.', number_format($digit)) + ); + } + } }