diff --git a/tests/Feature/Common/EventListener/JoinedInheritanceTest.php b/tests/Feature/Common/EventListener/JoinedInheritanceTest.php new file mode 100644 index 0000000..937fb4a --- /dev/null +++ b/tests/Feature/Common/EventListener/JoinedInheritanceTest.php @@ -0,0 +1,96 @@ +title = 'first'; + $invoice->amount = 10; + + $this->save($invoice); + + $row = $this->getDatabase()->select()->from('documents')->fetchAll()[0]; + Assert::same($row['title'], 'first'); + Assert::notNull($row['created_at']); + Assert::notNull($row['updated_at']); + Assert::same((int) $this->getDatabase()->select()->from('invoices')->fetchAll()[0]['amount'], 10); + } + + #[Test] + public function updateWritesParentColumns(): void + { + $invoice = new Invoice(); + $invoice->title = 'first'; + $this->save($invoice); + + $this->orm->getHeap()->clean(); + $invoice = (new Select($this->orm, Invoice::class))->fetchOne(); + $invoice->title = 'second'; + $invoice->amount = 20; + $this->save($invoice); + + $row = $this->getDatabase()->select()->from('documents')->fetchAll()[0]; + Assert::same($row['title'], 'second'); + Assert::same((int) $this->getDatabase()->select()->from('invoices')->fetchAll()[0]['amount'], 20); + } + + #[BeforeTest] + protected function setUp(): void + { + $this->makeTable('documents', [ + 'id' => 'primary', + 'title' => 'string', + 'created_at' => 'datetime,nullable', + 'updated_at' => 'datetime,nullable', + ]); + $this->makeTable('invoices', ['id' => 'integer', 'amount' => 'integer'], pk: ['id']); + + $this->withSchema(new Schema([ + Document::class => [ + SchemaInterface::ROLE => 'document', + SchemaInterface::DATABASE => 'default', + SchemaInterface::TABLE => 'documents', + SchemaInterface::PRIMARY_KEY => 'id', + SchemaInterface::COLUMNS => [ + 'id' => 'id', + 'title' => 'title', + 'createdAt' => 'created_at', + 'updatedAt' => 'updated_at', + ], + SchemaInterface::LISTENERS => [CreatedAt::class, UpdatedAt::class], + SchemaInterface::TYPECAST => ['id' => 'int', 'createdAt' => 'datetime', 'updatedAt' => 'datetime'], + SchemaInterface::SCHEMA => [], + SchemaInterface::RELATIONS => [], + ], + Invoice::class => [ + SchemaInterface::ROLE => 'invoice', + SchemaInterface::PARENT => 'document', + SchemaInterface::DATABASE => 'default', + SchemaInterface::TABLE => 'invoices', + SchemaInterface::PRIMARY_KEY => 'id', + SchemaInterface::COLUMNS => ['id' => 'id', 'amount' => 'amount'], + SchemaInterface::TYPECAST => ['id' => 'int', 'amount' => 'int'], + SchemaInterface::SCHEMA => [], + SchemaInterface::RELATIONS => [], + ], + ])); + } +} diff --git a/tests/Feature/Common/EventListener/ListenerProviderTest.php b/tests/Feature/Common/EventListener/ListenerProviderTest.php index 575fcea..bb05e81 100644 --- a/tests/Feature/Common/EventListener/ListenerProviderTest.php +++ b/tests/Feature/Common/EventListener/ListenerProviderTest.php @@ -4,11 +4,14 @@ namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\EventListener; +use Cycle\ORM\Entity\Behavior\Attribute\Listen; use Cycle\ORM\Entity\Behavior\Exception\Dispatcher\RuntimeException; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\AuditService; +use Cycle\ORM\Entity\Behavior\Tests\Fixtures\BrokenAttributeService; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\BrokenEventListService; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\EventListener\Post; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\PostService; +use Cycle\ORM\Entity\Behavior\Tests\Fixtures\UncallableEventListService; use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Heap\Heap; use Cycle\ORM\Schema; @@ -65,6 +68,56 @@ public function testEventListMustHoldEventMethodPairs(): never $this->withListeners(BrokenEventListService::class); } + #[Test] + public function testDefinitionOfMissingClassIsSkipped(): void + { + $this->withListeners('Cycle\ORM\Entity\Behavior\Tests\Fixtures\MissingListener', AuditService::class); + + $this->save(new Post()); + + Assert::same($this->fetchPost()->title, 'created'); + } + + #[Test] + public function testListenerWithoutEventsIsSkipped(): void + { + $this->withListeners(\ArrayObject::class); + + $this->save(new Post()); + + Assert::null($this->fetchPost()->title); + } + + #[Test] + public function testProvidedListenerMustBeCallable(): never + { + Expect::exception(\Exception::class) + ->withMessage(\sprintf("Cann't create listener `%s` for the `post` role.", UncallableEventListService::class)) + ->withPrevious( + RuntimeException::class, + static fn(ExpectedException $previous) => $previous->withMessage(\sprintf( + "Cann't build callable from instance of `%s` and `missing` method name.", + UncallableEventListService::class, + )), + ); + + $this->withListeners(UncallableEventListService::class); + } + + #[Test] + public function testBrokenListenAttributeIsReported(): never + { + Expect::exception(RuntimeException::class) + ->withMessage(\sprintf( + "Cann't instantiate attribute %s in the %s::onCreate method.", + Listen::class, + BrokenAttributeService::class, + )) + ->withPrevious(\ArgumentCountError::class); + + $this->withListeners(BrokenAttributeService::class); + } + #[BeforeTest] protected function createTable(): void { diff --git a/tests/Feature/Common/OptimisticLock/OptimisticLockTest.php b/tests/Feature/Common/OptimisticLock/OptimisticLockTest.php index 0282eda..80abf79 100644 --- a/tests/Feature/Common/OptimisticLock/OptimisticLockTest.php +++ b/tests/Feature/Common/OptimisticLock/OptimisticLockTest.php @@ -5,7 +5,9 @@ namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\OptimisticLock; use Cycle\Database\ColumnInterface; +use Cycle\ORM\Entity\Behavior\Exception\BehaviorCompilationException; use Cycle\ORM\Entity\Behavior\Listener\OptimisticLock as Listener; +use Cycle\ORM\Entity\Behavior\OptimisticLock; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Article; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Comment; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Item; @@ -17,9 +19,12 @@ use Cycle\ORM\Entity\Behavior\Tests\Support\SchemaTestCase; use Cycle\ORM\Schema\GeneratedField; use Cycle\ORM\SchemaInterface; +use Cycle\Schema\Definition\Entity; +use Cycle\Schema\Registry; use Spiral\Tokenizer\Config\TokenizerConfig; use Spiral\Tokenizer\Tokenizer; use Testo\Assert; +use Testo\Expect; use Testo\Lifecycle\BeforeTest; use Testo\Test; @@ -133,6 +138,21 @@ public function testComputeConfiguresDeclaredField(): void Assert::same($field->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); } + #[Test] + public function testUnknownRuleIsRejected(): never + { + $registry = new Registry($this->dbal); + $entity = (new Entity())->setRole('post'); + $registry->register($entity); + $registry->linkTable($entity, 'default', 'posts'); + + Expect::exception(BehaviorCompilationException::class)->withMessage( + \sprintf('Wrong rule `unknown` for the %s behavior in the `post.version` field.', OptimisticLock::class), + ); + + (new OptimisticLock(rule: 'unknown'))->withRole('post')->render($registry); + } + #[BeforeTest] protected function setUp(): void { diff --git a/tests/Feature/Common/Schema/RegistryModifierTest.php b/tests/Feature/Common/Schema/RegistryModifierTest.php index fea7b6b..be4f1db 100644 --- a/tests/Feature/Common/Schema/RegistryModifierTest.php +++ b/tests/Feature/Common/Schema/RegistryModifierTest.php @@ -16,6 +16,7 @@ use Cycle\Testing\Database\DatabaseTestCase; use Ramsey\Uuid\Uuid; use Testo\Assert; +use Testo\Data\DataSet; use Testo\Expect; use Testo\Lifecycle\BeforeTest; use Testo\Test; @@ -252,6 +253,39 @@ public function testAddExistingStringFieldSetsGenerated(): void ); } + #[Test] + #[DataSet(['addIntegerColumn'], 'integer')] + #[DataSet(['addBigIntegerColumn'], 'big integer')] + #[DataSet(['addDatetimeColumn'], 'datetime')] + #[DataSet(['addStringColumn'], 'string')] + #[DataSet(['addSnowflakeColumn'], 'snowflake')] + #[DataSet(['addUlidColumn'], 'ulid')] + #[DataSet(['addUuidColumn'], 'uuid')] + public function testExistingFieldOfSameTypeIsReused(string $method): void + { + $this->modifier->{$method}('value_column', 'value'); + + $column = $this->modifier->{$method}('value_column', 'value', GeneratedField::BEFORE_INSERT); + + $fields = $this->registry->getEntity(self::ROLE_TEST)->getFields(); + Assert::same($fields->count(), 1); + Assert::same($fields->get('value')->getGenerated(), GeneratedField::BEFORE_INSERT); + Assert::same($column->getName(), 'value_column'); + } + + #[Test] + #[DataSet(['addIntegerColumn', 'Field value must be of type integer.'], 'integer')] + #[DataSet(['addStringColumn', 'Field value must be of type string.'], 'string')] + #[DataSet(['addDatetimeColumn', 'Field value must be of type datetime.'], 'datetime')] + public function testExistingFieldOfOtherTypeIsRejected(string $method, string $message): void + { + $this->modifier->addUuidColumn('value_column', 'value'); + + Expect::exception(BehaviorCompilationException::class)->withMessage($message); + + $this->modifier->{$method}('value_column', 'value'); + } + #[Test] public function testDefaultTypecastHandlerIsNotAddedToEntity(): void { diff --git a/tests/Fixtures/ArgumentlessModifier.php b/tests/Fixtures/ArgumentlessModifier.php new file mode 100644 index 0000000..eeaba72 --- /dev/null +++ b/tests/Fixtures/ArgumentlessModifier.php @@ -0,0 +1,23 @@ + $event->state->register('content', 'hooked'), OnCreate::class), + ); + $event = self::event($orm, OnCreate::class); + + (new Dispatcher(new ListenerProvider($orm->getSchema(), new SimpleContainer())))->dispatch($event); + + $data = $event->state->getData(); + Assert::same($data['createdAt'], $event->timestamp); + Assert::same($data['updatedAt'], $event->timestamp); + Assert::same($data['version'], 1); + Assert::same($data['content'], 'hooked'); + Assert::false(\array_key_exists('deletedAt', $data)); + } + + public function queueCommandListenerReceivesEveryCommand(): void + { + $orm = self::orm(new Hook(static fn() => null, [OnCreate::class])); + $provider = new ListenerProvider($orm->getSchema(), new SimpleContainer()); + + foreach ([OnCreate::class, OnUpdate::class, OnDelete::class] as $class) { + Assert::array($provider->getListenersForEvent(self::event($orm, $class)))->hasCount(1); + } + } + + public function eventWithoutListenersGetsNone(): void + { + $orm = self::orm(new CreatedAt()); + $provider = new ListenerProvider($orm->getSchema(), new SimpleContainer()); + + Assert::same($provider->getListenersForEvent(self::event($orm, OnUpdate::class)), []); + } + + public function roleWithoutListenersGetsNone(): void + { + $orm = self::orm(); + $provider = new ListenerProvider($orm->getSchema(), new SimpleContainer()); + + Assert::same($provider->getListenersForEvent(self::event($orm, OnCreate::class)), []); + } + + private static function orm(BaseModifier ...$behaviors): ORMInterface + { + $schema = []; + foreach ($behaviors as $behavior) { + $behavior->withRole('post')->modifySchema($schema); + } + + return Memory::orm([ + 'post' => $schema + [ + SchemaInterface::ENTITY => Post::class, + SchemaInterface::DATABASE => 'default', + SchemaInterface::TABLE => 'posts', + SchemaInterface::PRIMARY_KEY => 'id', + SchemaInterface::COLUMNS => ['id', 'title', 'content'], + SchemaInterface::SCHEMA => [], + SchemaInterface::RELATIONS => [], + ], + ]); + } + + /** + * @param class-string $class + */ + private static function event(ORMInterface $orm, string $class): QueueCommand + { + return new $class( + 'post', + $orm->getMapper('post'), + new Post(), + new Node(Node::NEW, [], 'post'), + new State(Node::NEW, []), + $orm->getSource('post'), + new \DateTimeImmutable(), + ); + } +} diff --git a/tests/Unit/Schema/BaseModifierTest.php b/tests/Unit/Schema/BaseModifierTest.php index 130b5a3..f6e45fe 100644 --- a/tests/Unit/Schema/BaseModifierTest.php +++ b/tests/Unit/Schema/BaseModifierTest.php @@ -6,7 +6,10 @@ use Cycle\ORM\Entity\Behavior\CreatedAt; use Cycle\ORM\Entity\Behavior\EventListener; +use Cycle\ORM\Entity\Behavior\Tests\Fixtures\ArgumentlessModifier; +use Cycle\ORM\Entity\Behavior\Tests\Fixtures\AuditService; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\PostService; +use Cycle\ORM\SchemaInterface; use Testo\Assert; use Testo\Test; @@ -20,6 +23,15 @@ public function testWithRoleReturnsNewInstance(): void Assert::notSame($modifier->withRole('post'), $modifier); } + public function testListenerWithoutArgumentsIsDeclaredByClassName(): void + { + $schema = []; + + (new ArgumentlessModifier())->modifySchema($schema); + + Assert::same($schema, [SchemaInterface::LISTENERS => [AuditService::class]]); + } + public function testEventListenerWithRoleReturnsNewInstance(): void { $modifier = new EventListener(PostService::class);