diff --git a/.github/workflows/ci-mysql.yml b/.github/workflows/ci-mysql.yml deleted file mode 100644 index 55b16d7..0000000 --- a/.github/workflows/ci-mysql.yml +++ /dev/null @@ -1,25 +0,0 @@ ---- - -on: # yamllint disable-line rule:truthy - push: - branches: - - 1.x - pull_request: null - -name: MySQL - -permissions: - contents: read - -concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - phpunit: - uses: cycle/gh-actions/.github/workflows/db-mysql.yml@master - with: - php: '["8.2","8.3","8.4","8.5"]' - stability: '["prefer-lowest","prefer-stable"]' - -... diff --git a/.github/workflows/ci-pgsql.yml b/.github/workflows/ci-pgsql.yml deleted file mode 100644 index dd474b7..0000000 --- a/.github/workflows/ci-pgsql.yml +++ /dev/null @@ -1,25 +0,0 @@ ---- - -on: # yamllint disable-line rule:truthy - push: - branches: - - 1.x - pull_request: null - -name: Postgres - -permissions: - contents: read - -concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - phpunit: - uses: cycle/gh-actions/.github/workflows/db-pgsql.yml@master - with: - php: '["8.2","8.3","8.4","8.5"]' - stability: '["prefer-lowest","prefer-stable"]' - -... diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index 388b7dc..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,108 +0,0 @@ ---- - -on: # yamllint disable-line rule:truthy - pull_request: null - push: - branches: - - 1.x - -name: build - -permissions: - contents: read - -concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - sqlite: - name: SQLite PHP ${{ matrix.php-version }}, ${{ matrix.dependencies }} - runs-on: ubuntu-latest - timeout-minutes: 10 - strategy: - fail-fast: false - matrix: - php-version: - - "8.2" - - "8.3" - - "8.4" - - "8.5" - dependencies: - - lowest - - highest - steps: - - name: Checkout - uses: actions/checkout@v7 - with: - persist-credentials: false - - - name: Setup PHP ${{ matrix.php-version }} - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php-version }} - coverage: none - extensions: mbstring, pdo, pdo_sqlite - - - name: Install dependencies with composer - uses: ramsey/composer-install@v4 - with: - dependency-versions: ${{ matrix.dependencies }} - - - name: Execute Tests - env: - DB: sqlite - run: vendor/bin/phpunit --group driver-sqlite --colors=always - - test: - needs: sqlite - name: Test PHP ${{ matrix.php-version }} with Code Coverage - runs-on: ubuntu-latest - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - php-version: - - "8.2" - - "8.3" - - "8.4" - - "8.5" - steps: - - name: Install ODBC driver - run: | - sudo curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list - sudo ACCEPT_EULA=Y apt-get install -y msodbcsql18 - - - name: Checkout - uses: actions/checkout@v7 - with: - persist-credentials: false - - - name: Setup DB services - working-directory: tests - run: docker compose up -d - - - name: Setup PHP ${{ matrix.php-version }} - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php-version }} - coverage: pcov - tools: pecl - extensions: mbstring, pdo, pdo_sqlite, pdo_pgsql, pdo_sqlsrv, pdo_mysql - - - name: Install dependencies with composer - uses: ramsey/composer-install@v4 - with: - dependency-versions: highest - - - name: Execute Tests - run: vendor/bin/phpunit --coverage-clover=coverage.clover - - - name: Upload coverage to Codecov - continue-on-error: true # forks have no token - uses: codecov/codecov-action@v7 - with: - token: ${{ secrets.CODECOV_TOKEN }} - files: ./coverage.clover - -... diff --git a/.github/workflows/ci-mssql.yml b/.github/workflows/testing.yml similarity index 58% rename from .github/workflows/ci-mssql.yml rename to .github/workflows/testing.yml index 23bafb8..0b0fb38 100644 --- a/.github/workflows/ci-mssql.yml +++ b/.github/workflows/testing.yml @@ -1,25 +1,26 @@ --- +name: 🧪 Tests + on: # yamllint disable-line rule:truthy + pull_request: push: branches: - 1.x - pull_request: null - -name: MSSQL - -permissions: - contents: read concurrency: group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +permissions: + contents: read + jobs: - phpunit: - uses: cycle/gh-actions/.github/workflows/db-mssql.yml@master + testo: + name: Testo + uses: cycle/gh-actions/.github/workflows/testo.yml@master with: - php: '["8.2","8.3","8.4","8.5"]' - stability: '["prefer-lowest","prefer-stable"]' + coverage: true + secrets: inherit ... diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0b08636..dbcc070 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,23 +10,25 @@ Please make sure that the following requirements are satisfied before submitting > Use our discord server to check for the advice or suggestion https://discord.gg/FZ9BCWg ## Testing Cycle ORM Entity Behavior -To test Cycle ORM Entity Behavior locally, download the `cycle/entity-behavior` repository and start docker containers inside the tests folder: +Tests run on [Testo](https://github.com/php-testo/testo) through the `cycle/testing` harness: `tests/Unit` needs no +database, `tests/Feature` runs once per database driver. +Reproductions of reported issues go to `tests/Regression/Issue/`; `composer test:new-case -- ` writes a runnable +case there to start from. -```bash -$ cd tests/ -$ docker-composer up -``` - -To run full test suite: +Unit and SQLite tests need no docker: ```bash -$ ./vendor/bin/phpunit +composer test:unit +composer test:sqlite ``` -To run quick test suite: +The other drivers run against the shared test databases: ```bash -$ ./vendor/bin/phpunit --group driver-sqlite +composer db:up # or: composer db:up -- mysql +composer test # every suite; drivers whose server is down are skipped +composer test:mysql # also test:postgres, test:sqlserver +composer db:down ``` ## Help Needed In diff --git a/composer.json b/composer.json index 378aadd..abff212 100644 --- a/composer.json +++ b/composer.json @@ -47,11 +47,12 @@ "bamarni/composer-bin-plugin": "^1.8", "buggregator/trap": "^1.20", "cycle/annotated": "^4.6", + "cycle/testing": "^0.1.1", "llm/skills": "^1.20", - "phpunit/phpunit": "^11.5", "ramsey/uuid": "^4.9", "roxblnfk/unpoly": "^1.8", - "spiral/tokenizer": "^3.18" + "spiral/tokenizer": "^3.18", + "testo/testo": "^0.10.60" }, "autoload": { "psr-4": { @@ -60,9 +61,15 @@ }, "autoload-dev": { "psr-4": { - "Cycle\\ORM\\Entity\\Behavior\\Tests\\": "tests/Behavior" + "Cycle\\ORM\\Entity\\Behavior\\Tests\\": "tests/" } }, + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/cycle/testing" + } + ], "config": { "sort-packages": true, "allow-plugins": { @@ -75,10 +82,21 @@ "scripts": { "cs:diff": "php-cs-fixer fix --dry-run -v --diff --config=vendor-bin/code-style/.php-cs-fixer.dist.php", "cs:fix": "php-cs-fixer fix -v --config=vendor-bin/code-style/.php-cs-fixer.dist.php", + "db:down": "docker compose -f vendor/cycle/testing/resources/docker/compose.yaml down -v", + "db:up": "docker compose -f vendor/cycle/testing/resources/docker/compose.yaml up -d --wait", "psalm": "psalm -c vendor-bin/psalm/psalm.xml", "psalm:baseline": "psalm -c vendor-bin/psalm/psalm.xml --set-baseline=vendor-bin/psalm/psalm-baseline.xml", "psalm:ci": "psalm -c vendor-bin/psalm/psalm.xml --output-format=github --shepherd --show-info=false --stats --threads=4", - "test": "phpunit --color=always" + "test": "testo", + "test:mysql": "testo --suite=Feature/MySQL --suite=Regression/MySQL", + "test:new-case": "cycle-testing new-case --template=orm-behaviors", + "test:postgres": "testo --suite=Feature/Postgres --suite=Regression/Postgres", + "test:sqlite": "testo --suite=Feature/SQLite --suite=Regression/SQLite", + "test:sqlserver": "testo --suite=Feature/SQLServer --suite=Regression/SQLServer", + "test:unit": "testo --suite=Unit" + }, + "scripts-descriptions": { + "test:new-case": "Write a regression case into tests/Regression/Issue: composer test:new-case -- " }, "extra": { "bamarni-bin": { diff --git a/phpunit.xml b/phpunit.xml deleted file mode 100644 index f1d9a19..0000000 --- a/phpunit.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - ./tests/ - ./tests/Behavior/Functional/Driver/Common - - - - - - src - - - diff --git a/testo.php b/testo.php new file mode 100644 index 0000000..4a17e52 --- /dev/null +++ b/testo.php @@ -0,0 +1,12 @@ +unit('tests/Unit') + ->feature('tests/Feature', plugins: [new OrmPlugin()]) + ->regression('tests/Regression', plugins: [new OrmPlugin()]) + ->build(); diff --git a/tests/Behavior/Functional/Driver/Common/BaseListenerTest.php b/tests/Behavior/Functional/Driver/Common/BaseListenerTest.php deleted file mode 100644 index 7f2aad7..0000000 --- a/tests/Behavior/Functional/Driver/Common/BaseListenerTest.php +++ /dev/null @@ -1,51 +0,0 @@ -orm = new ORM( - new Factory( - $this->dbal, - RelationConfig::getDefault(), - null, - new ArrayCollectionFactory(), - ), - $schema, - new EventDrivenCommandGenerator($schema, new SimpleContainer()), - ); - - return $this->orm; - } - - public function tearDown(): void - { - parent::tearDown(); - - $this->orm = null; - } - - protected function save(object ...$entities): void - { - $tr = new Transaction($this->orm); - foreach ($entities as $entity) { - $tr->persist($entity); - } - $tr->run(); - } -} diff --git a/tests/Behavior/Functional/Driver/Common/BaseTest.php b/tests/Behavior/Functional/Driver/Common/BaseTest.php deleted file mode 100644 index 87de2cc..0000000 --- a/tests/Behavior/Functional/Driver/Common/BaseTest.php +++ /dev/null @@ -1,97 +0,0 @@ -driver)) { - $this->driver = $config->driver::create($config); - } - - return static::$driverCache[static::DRIVER] = $this->driver; - } - - protected function setUp(): void - { - $this->setUpLogger($this->getDriver()); - if (self::$config['debug'] ?? false) { - $this->enableProfiling(); - } else { - $this->disableProfiling(); - } - - $this->dbal = new DatabaseManager(new DatabaseConfig()); - $this->dbal->addDatabase( - new Database( - 'default', - '', - $this->getDriver(), - ), - ); - } - - public function tearDown(): void - { - $this->dropDatabase($this->dbal->database('default')); - - $this->dbal = null; - - if (\function_exists('gc_collect_cycles')) { - \gc_collect_cycles(); - } - } - - protected function dropDatabase(?Database $database = null): void - { - if ($database === null) { - return; - } - - foreach ($database->getTables() as $table) { - $schema = $table->getSchema(); - - foreach ($schema->getForeignKeys() as $foreign) { - $schema->dropForeignKey($foreign->getColumns()); - } - - $schema->save(Handler::DROP_FOREIGN_KEYS); - } - - foreach ($database->getTables() as $table) { - $schema = $table->getSchema(); - $schema->declareDropped(); - $schema->save(); - } - } - - protected function getDatabase(): Database - { - return $this->dbal->database('default'); - } -} diff --git a/tests/Behavior/Functional/Driver/Common/CreatedAt/CreatedAtTest.php b/tests/Behavior/Functional/Driver/Common/CreatedAt/CreatedAtTest.php deleted file mode 100644 index 0e8ef3f..0000000 --- a/tests/Behavior/Functional/Driver/Common/CreatedAt/CreatedAtTest.php +++ /dev/null @@ -1,47 +0,0 @@ -registry->getEntity(Post::class)->getFields(); - - $this->assertTrue($fields->has('createdAt')); - $this->assertTrue($fields->hasColumn('created_at')); - $this->assertSame('datetime', $fields->get('createdAt')->getType()); - $this->assertSame(GeneratedField::BEFORE_INSERT, $fields->get('createdAt')->getGenerated()); - - // No new fields added - $this->assertSame(3, $fields->count()); - } - - public function testAddedColumn(): void - { - $fields = $this->registry->getEntity(Post::class)->getFields(); - - $this->assertTrue($fields->has('newField')); - $this->assertTrue($fields->hasColumn('new_field')); - $this->assertSame('datetime', $fields->get('newField')->getType()); - $this->assertSame(GeneratedField::BEFORE_INSERT, $fields->get('newField')->getGenerated()); - } - - public function setUp(): void - { - parent::setUp(); - - $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/CreatedAt'], - 'exclude' => [], - ]))); - } -} diff --git a/tests/Behavior/Functional/Driver/Common/Hook/HookTest.php b/tests/Behavior/Functional/Driver/Common/Hook/HookTest.php deleted file mode 100644 index cfe7d10..0000000 --- a/tests/Behavior/Functional/Driver/Common/Hook/HookTest.php +++ /dev/null @@ -1,50 +0,0 @@ -schema->define(Post::class, SchemaInterface::LISTENERS); - - $this->assertIsArray($listeners); - $this->assertCount(2, $listeners); - $this->assertIsArray($listeners[0]); - $this->assertIsArray($listeners[1]); - - $this->assertSame(Hook::class, $listeners[0][0]); - $this->assertSame( - ['callable' => [PostService::class, 'update'], 'events' => [OnUpdate::class]], - $listeners[0][1], - ); - - $this->assertSame(Hook::class, $listeners[1][0]); - $this->assertSame( - ['callable' => [Post::class, 'touch'], 'events' => [OnCreate::class, OnUpdate::class]], - $listeners[1][1], - ); - } - - public function setUp(): void - { - parent::setUp(); - - $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/Hook'], - 'exclude' => [], - ]))); - } -} diff --git a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/CaseTest.php b/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/CaseTest.php deleted file mode 100644 index 9f33e2c..0000000 --- a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/CaseTest.php +++ /dev/null @@ -1,130 +0,0 @@ -orm, Entity\User::class)) - ->load('posts') - ->wherePK(2) - ->fetchOne(); - \assert($user instanceof Entity\User); - - // Check results - self::assertNotNull($user->createdAt); - self::assertNotNull($user->updatedAt); - self::assertSame(0, $user->createdAt <=> $user->updatedAt); - } - - public function testCreatedAt(): void - { - // Get entity - $user = $this->orm->make(Entity\User::class, ['login' => 'new-user', 'passwordHash' => '123456789']); - - self::assertFalse(isset($user->createdAt)); - $this->save($user); - - self::assertNotNull($user->createdAt); - - // Reload entity - $id = $user->id; - $this->cleanHeap(); - $user = (new Select($this->orm, Entity\User::class)) - ->wherePK($id) - ->fetchOne(); - self::assertNotNull($user->createdAt); - } - - public function testUpdatedAt(): void - { - // Get entity - $user = (new Select($this->orm, Entity\User::class)) - ->wherePK(2) - ->fetchOne(); - \assert($user instanceof Entity\User); - $updatedAt = $user->updatedAt; - - // Change data - $user->passwordHash = 'new-password-hash'; - $this->save($user); - - // Check results - self::assertSame(1, $user->updatedAt <=> $updatedAt); - } - - protected function setUp(): void - { - // Init DB - parent::setUp(); - $this->prepareOrm(__DIR__ . '/Entity'); - $this->save(...$this->fillData()); - $this->orm->getHeap()->clean(); - } - - private function fillData(): iterable - { - /** - * @var callable(class-string, array): object $c - */ - $c = \Closure::fromCallable([$this->orm, 'make']); - - // Users - $u1 = $c(Entity\User::class, ['login' => 'user-1', 'passwordHash' => '123456789']); - $u2 = $c(Entity\User::class, ['login' => 'user-2', 'passwordHash' => '852741963']); - $u3 = $c(Entity\User::class, ['login' => 'user-3', 'passwordHash' => '321654987']); - $u4 = $c(Entity\User::class, ['login' => 'user-4', 'passwordHash' => '321456987']); - - // Posts - $p1 = $c(Entity\Post::class, ['slug' => 'slug-string-1', 'title' => 'Title 1', 'public' => true, 'content' => 'Foo-bar-baz content 1']); - $p2 = $c(Entity\Post::class, ['slug' => 'slug-string-2', 'title' => 'Title 2', 'public' => true, 'content' => 'Foo-bar-baz content 2']); - $p3 = $c(Entity\Post::class, ['slug' => 'slug-string-3', 'title' => 'Title 3', 'public' => false, 'content' => 'Foo-bar-baz content 3']); - $p4 = $c(Entity\Post::class, ['slug' => 'slug-string-4', 'title' => 'Title 4', 'public' => true, 'content' => 'Foo-bar-baz content 4']); - $p5 = $c(Entity\Post::class, ['slug' => 'slug-string-5', 'title' => 'Title 5', 'public' => true, 'content' => 'Foo-bar-baz content 5']); - $p6 = $c(Entity\Post::class, ['slug' => 'slug-string-6', 'title' => 'Title 6', 'public' => true, 'content' => 'Foo-bar-baz content 6']); - - // Link posts with users - $u1->posts = [$p1]; - $u2->posts = [$p2, $p3]; - $u3->posts = [$p4, $p5, $p6]; - - // Comments - $c1 = $c(Entity\Comment::class, ['post' => $p1, 'user' => $u2, 'content' => 'Foo-bar-baz comment 1', 'public' => true]); - $c2 = $c(Entity\Comment::class, ['post' => $p1, 'user' => $u1, 'content' => 'Reply to comment 1', 'public' => true]); - $c3 = $c(Entity\Comment::class, ['post' => $p2, 'user' => $u1, 'content' => 'Foo-bar-baz comment 2', 'public' => true]); - $c4 = $c(Entity\Comment::class, ['post' => $p2, 'user' => $u2, 'content' => 'Reply to comment 2', 'public' => true]); - $c5 = $c(Entity\Comment::class, ['post' => $p2, 'user' => $u3, 'content' => 'Foo-bar-baz comment 3', 'public' => true]); - $c6 = $c(Entity\Comment::class, ['post' => $p2, 'user' => $u4, 'content' => 'Hidden comment', 'public' => false]); - $c7 = $c(Entity\Comment::class, ['post' => $p2, 'user' => $u4, 'content' => 'Yet another comment', 'public' => true]); - - // Tags - $t1 = $c(Entity\Tag::class, ['label' => 'tag-1']); - $t2 = $c(Entity\Tag::class, ['label' => 'tag-2']); - $t3 = $c(Entity\Tag::class, ['label' => 'tag-3']); - $t4 = $c(Entity\Tag::class, ['label' => 'tag-4']); - $t5 = $c(Entity\Tag::class, ['label' => 'tag-5']); - - // Link tags with posts - $t1->posts = [$p1, $p2]; - $t2->posts = [$p2, $p3]; - $t3->posts = [$p3, $p4, $p5]; - $t4->posts = [$p4, $p5]; - $t5->posts = [$p5, $p6, $p1]; - - // yield all the entities - yield from [$u1, $u2, $u3, $u4]; - yield from [$p1, $p2, $p3, $p4, $p5, $p6]; - yield from [$c1, $c2, $c3, $c4, $c5, $c6, $c7]; - yield from [$t1, $t2, $t3, $t4, $t5]; - } -} diff --git a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/Comment.php b/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/Comment.php deleted file mode 100644 index 95e547b..0000000 --- a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/Comment.php +++ /dev/null @@ -1,51 +0,0 @@ - */ - #[ManyToMany(target: Tag::class, innerKey: 'id', outerKey: 'id', throughInnerKey: 'postId', throughOuterKey: 'tagId', through: PostTag::class)] - public iterable $tags = []; - - /** @var iterable */ - #[HasMany(target: Comment::class, innerKey: 'id', outerKey: 'postId', fkCreate: false)] - public iterable $comments = []; - - private function __construct() {} -} diff --git a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/PostTag.php b/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/PostTag.php deleted file mode 100644 index f26ca38..0000000 --- a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/PostTag.php +++ /dev/null @@ -1,20 +0,0 @@ - */ - #[ManyToMany(target: Post::class, innerKey: 'id', outerKey: 'id', throughInnerKey: 'tagId', throughOuterKey: 'postId', through: PostTag::class)] - public iterable $posts = []; - - private function __construct() {} -} diff --git a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/User.php b/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/User.php deleted file mode 100644 index 736fc1d..0000000 --- a/tests/Behavior/Functional/Driver/Common/Integration/CaseTemplate/Entity/User.php +++ /dev/null @@ -1,41 +0,0 @@ - */ - #[HasMany(target: Post::class, innerKey: 'id', outerKey: 'userId', fkCreate: false)] - public iterable $posts = []; - - /** @var iterable */ - #[HasMany(target: Comment::class, innerKey: 'id', outerKey: 'userId', fkCreate: false)] - public iterable $comments = []; - - private function __construct() {} -} diff --git a/tests/Behavior/Functional/Driver/Common/OptimisticLock/OptimisticLockTest.php b/tests/Behavior/Functional/Driver/Common/OptimisticLock/OptimisticLockTest.php deleted file mode 100644 index a0e4053..0000000 --- a/tests/Behavior/Functional/Driver/Common/OptimisticLock/OptimisticLockTest.php +++ /dev/null @@ -1,116 +0,0 @@ -registry->getEntity(Post::class)->getFields(); - - $this->assertTrue($fields->has('version')); - $this->assertTrue($fields->hasColumn('version')); - $this->assertSame('integer', $fields->get('version')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('version')->getGenerated(), - ); - } - - public function testAddStringColumn(): void - { - $fields = $this->registry->getEntity(Comment::class)->getFields(); - - $this->assertTrue($fields->has('version')); - $this->assertTrue($fields->hasColumn('version')); - $this->assertSame(ColumnInterface::STRING, $fields->get('version')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('version')->getGenerated(), - ); - } - - public function testAddDatetimeColumn(): void - { - $fields = $this->registry->getEntity(Page::class)->getFields(); - - $this->assertTrue($fields->has('version')); - $this->assertTrue($fields->hasColumn('version')); - $this->assertSame('datetime', $fields->get('version')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('version')->getGenerated(), - ); - } - - public function testExistColumn(): void - { - $fields = $this->registry->getEntity(Item::class)->getFields(); - - $this->assertTrue($fields->has('revision')); - $this->assertTrue($fields->hasColumn('revision_field')); - $this->assertSame('integer', $fields->get('revision')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('revision')->getGenerated(), - ); - - // not added new columns - $this->assertSame(2, $fields->count()); - } - - public function testExistColumnAndAllOptimisticLockParameters(): void - { - $fields = $this->registry->getEntity(WithAllParameters::class)->getFields(); - - $this->assertTrue($fields->has('revision')); - $this->assertTrue($fields->hasColumn('revision_field')); - $this->assertSame('integer', $fields->get('revision')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('revision')->getGenerated(), - ); - - // not added new columns - $this->assertSame(2, $fields->count()); - } - - public function testAddDefaultColumAndRule(): void - { - $fields = $this->registry->getEntity(News::class)->getFields(); - - $this->assertTrue($fields->has('version')); - $this->assertTrue($fields->hasColumn('version')); - $this->assertSame('integer', $fields->get('version')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('version')->getGenerated(), - ); - - $this->assertSame(2, $fields->count()); - } - - public function setUp(): void - { - parent::setUp(); - - $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/OptimisticLock'], - 'exclude' => [], - ]))); - } -} diff --git a/tests/Behavior/Functional/Driver/Common/SoftDelete/SoftDeleteTest.php b/tests/Behavior/Functional/Driver/Common/SoftDelete/SoftDeleteTest.php deleted file mode 100644 index 0f8764c..0000000 --- a/tests/Behavior/Functional/Driver/Common/SoftDelete/SoftDeleteTest.php +++ /dev/null @@ -1,47 +0,0 @@ -registry->getEntity(Post::class)->getFields(); - - $this->assertTrue($fields->has('deletedAt')); - $this->assertTrue($fields->hasColumn('deleted_at')); - $this->assertSame('datetime', $fields->get('deletedAt')->getType()); - $this->assertSame(GeneratedField::BEFORE_UPDATE, $fields->get('deletedAt')->getGenerated()); - - // No new fields added - $this->assertSame(3, $fields->count()); - } - - public function testAddedColumn(): void - { - $fields = $this->registry->getEntity(Post::class)->getFields(); - - $this->assertTrue($fields->has('newField')); - $this->assertTrue($fields->hasColumn('new_field')); - $this->assertSame('datetime', $fields->get('newField')->getType()); - $this->assertSame(GeneratedField::BEFORE_UPDATE, $fields->get('newField')->getGenerated()); - } - - public function setUp(): void - { - parent::setUp(); - - $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/SoftDelete'], - 'exclude' => [], - ]))); - } -} diff --git a/tests/Behavior/Functional/Driver/Common/UpdatedAt/UpdatedAtTest.php b/tests/Behavior/Functional/Driver/Common/UpdatedAt/UpdatedAtTest.php deleted file mode 100644 index 7611859..0000000 --- a/tests/Behavior/Functional/Driver/Common/UpdatedAt/UpdatedAtTest.php +++ /dev/null @@ -1,53 +0,0 @@ -registry->getEntity(Post::class)->getFields(); - - $this->assertTrue($fields->has('updatedAt')); - $this->assertTrue($fields->hasColumn('updated_at')); - $this->assertSame('datetime', $fields->get('updatedAt')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('updatedAt')->getGenerated(), - ); - - // No new fields added - $this->assertSame(3, $fields->count()); - } - - public function testAddedColumn(): void - { - $fields = $this->registry->getEntity(Post::class)->getFields(); - - $this->assertTrue($fields->has('newField')); - $this->assertTrue($fields->hasColumn('new_field')); - $this->assertSame('datetime', $fields->get('newField')->getType()); - $this->assertSame( - GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE, - $fields->get('newField')->getGenerated(), - ); - } - - public function setUp(): void - { - parent::setUp(); - - $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/UpdatedAt'], - 'exclude' => [], - ]))); - } -} diff --git a/tests/Behavior/Functional/Driver/MySQL/CreatedAt/CreatedAtTest.php b/tests/Behavior/Functional/Driver/MySQL/CreatedAt/CreatedAtTest.php deleted file mode 100644 index cf93805..0000000 --- a/tests/Behavior/Functional/Driver/MySQL/CreatedAt/CreatedAtTest.php +++ /dev/null @@ -1,17 +0,0 @@ -setLogger(static::$logger); - } - - return $this; - } - - protected function enableProfiling(): void - { - static::$logger->enable(); - } - - protected function disableProfiling(): void - { - static::$logger->disable(); - } -} diff --git a/tests/Behavior/Traits/TableTrait.php b/tests/Behavior/Traits/TableTrait.php deleted file mode 100644 index c33c142..0000000 --- a/tests/Behavior/Traits/TableTrait.php +++ /dev/null @@ -1,80 +0,0 @@ -getDatabase()->table($table)->getSchema(); - $renderer = new TableRenderer(); - $renderer->renderColumns($schema, $columns, $defaults); - - foreach ($fk as $column => $options) { - if (isset($options['from'])) { - $column = $options['from']; - } - $fkState = $schema->foreignKey((array) $column)->references($options['table'], (array) $options['column']); - $fkState->onUpdate($options['onUpdate'] ?? ForeignKeyInterface::CASCADE); - $fkState->onDelete($options['onDelete'] ?? ForeignKeyInterface::CASCADE); - } - - if (!empty($pk)) { - $schema->setPrimaryKeys($pk); - } - - $schema->save(); - } - - public function makeFK( - string $from, - string|array $fromKey, - string $to, - string|array $toColumn, - string $onDelete = ForeignKeyInterface::CASCADE, - string $onUpdate = ForeignKeyInterface::CASCADE, - ): void { - $schema = $this->getDatabase()->table($from)->getSchema(); - $schema->foreignKey((array) $fromKey) - ->references($to, (array) $toColumn) - ->onDelete($onDelete) - ->onUpdate($onUpdate); - $schema->save(); - } - - public function makeCompositeFK( - string $from, - array $fromKeys, - string $to, - array $toColumns, - string $onDelete = ForeignKeyInterface::CASCADE, - string $onUpdate = ForeignKeyInterface::CASCADE, - ): void { - $schema = $this->getDatabase()->table($from)->getSchema(); - $schema->foreignKey($fromKeys)->references($to, $toColumns)->onDelete($onDelete)->onUpdate($onUpdate); - $schema->save(); - } - - public function makeIndex( - string $table, - array $columns, - bool $unique, - ): void { - $schema = $this->getDatabase()->table($table)->getSchema(); - $schema->index($columns)->unique($unique); - $schema->save(); - } - - abstract protected function getDatabase(): Database; -} diff --git a/tests/Behavior/Unit/Schema/RegistryModifierTest.php b/tests/Behavior/Unit/Schema/RegistryModifierTest.php deleted file mode 100644 index d6b88d5..0000000 --- a/tests/Behavior/Unit/Schema/RegistryModifierTest.php +++ /dev/null @@ -1,171 +0,0 @@ -assertTrue(RegistryModifier::isIntegerType($type)); - } - - /** - * @dataProvider datetimeDataProvider - * @dataProvider stringDataProvider - * @dataProvider invalidDataProvider - */ - public function testIsIntegerTypeFalse(mixed $type): void - { - $this->assertFalse(RegistryModifier::isIntegerType($type)); - } - - /** - * @dataProvider bigIntegerDataProvider - */ - public function testIsBigIntegerTypeTrue(mixed $type): void - { - $this->assertTrue(RegistryModifier::isBigIntegerType($type)); - } - - /** - * @dataProvider datetimeDataProvider - * @dataProvider stringDataProvider - * @dataProvider invalidDataProvider - */ - public function testIsBigIntegerTypeFalse(mixed $type): void - { - $this->assertFalse(RegistryModifier::isBigIntegerType($type)); - } - - /** - * @dataProvider datetimeDataProvider - */ - public function testIsDatetimeTypeTrue(mixed $type): void - { - $this->assertTrue(RegistryModifier::isDatetimeType($type)); - } - - /** - * @dataProvider integerDataProvider - * @dataProvider stringDataProvider - * @dataProvider invalidDataProvider - */ - public function testIsDatetimeTypeFalse(mixed $type): void - { - $this->assertFalse(RegistryModifier::isDatetimeType($type)); - } - - /** - * @dataProvider stringDataProvider - */ - public function testIsStringTypeTrue(mixed $type): void - { - $this->assertTrue(RegistryModifier::isStringType($type)); - } - - /** - * @dataProvider integerDataProvider - * @dataProvider datetimeDataProvider - * @dataProvider invalidDataProvider - */ - public function testIsStringTypeFalse(mixed $type): void - { - $this->assertFalse(RegistryModifier::isStringType($type)); - } - - public function testIsSnowflakeTypeTrue(): void - { - $this->assertTrue(RegistryModifier::isSnowflakeType('snowflake')); - } - - /** - * @dataProvider integerDataProvider - * @dataProvider datetimeDataProvider - * @dataProvider invalidDataProvider - * @dataProvider stringDataProvider - */ - public function testIsSnowflakeTypeFalse(mixed $type): void - { - $this->assertFalse(RegistryModifier::isSnowflakeType($type)); - } - - public function testIsUlidTypeTrue(): void - { - $this->assertTrue(RegistryModifier::isUlidType('ulid')); - } - - /** - * @dataProvider integerDataProvider - * @dataProvider datetimeDataProvider - * @dataProvider invalidDataProvider - * @dataProvider stringDataProvider - */ - public function testIsUlidTypeFalse(mixed $type): void - { - $this->assertFalse(RegistryModifier::isUlidType($type)); - } - - public function testIsUuidTypeTrue(): void - { - $this->assertTrue(RegistryModifier::isUuidType('uuid')); - } - - /** - * @dataProvider integerDataProvider - * @dataProvider datetimeDataProvider - * @dataProvider invalidDataProvider - * @dataProvider stringDataProvider - */ - public function testIsUuidTypeFalse(mixed $type): void - { - $this->assertFalse(RegistryModifier::isUuidType($type)); - } -} diff --git a/tests/Behavior/Utils/SimpleContainer.php b/tests/Behavior/Utils/SimpleContainer.php deleted file mode 100644 index 67ebbd9..0000000 --- a/tests/Behavior/Utils/SimpleContainer.php +++ /dev/null @@ -1,47 +0,0 @@ -definitions = $definitions; - $this->factory = $factory ?? static function (string $id): void { - throw new class("No definition or class found for \"$id\".") extends \Exception implements NotFoundExceptionInterface {}; - }; - } - - public function get($id): mixed - { - if (!\array_key_exists($id, $this->definitions)) { - $this->definitions[$id] = ($this->factory)($id); - } - return $this->definitions[$id]; - } - - public function has($id): bool - { - if (\array_key_exists($id, $this->definitions)) { - return true; - } - try { - $this->get($id); - return true; - } catch (\Throwable $e) { - return false; - } - } -} diff --git a/tests/Behavior/Utils/TableRenderer.php b/tests/Behavior/Utils/TableRenderer.php deleted file mode 100644 index 1ec383b..0000000 --- a/tests/Behavior/Utils/TableRenderer.php +++ /dev/null @@ -1,193 +0,0 @@ - 'primary', - * 'time' => 'datetime, nullable', - * 'status' => 'enum(active, disabled)' - * ], - * [ - * 'status' => 'active', - * 'time' => null, - * ] - * ); - * - * @throws SchemaException - */ - public function renderColumns(AbstractTable $table, array $columns, array $defaults): void - { - $primaryKeys = []; - foreach ($columns as $name => $definition) { - $type = $this->parse($table->getName(), $name, $definition); - - if ($this->hasFlag($type, 'primary')) { - $primaryKeys[] = $name; - } - - $this->renderColumn( - $table->column($name), - $type, - \array_key_exists($name, $defaults), - $defaults[$name] ?? null, - ); - } - - if (\count($primaryKeys)) { - $table->setPrimaryKeys($primaryKeys); - } - } - - /** - * Cast (specify) column schema based on provided column definition and default value. - * Spiral will force default values (internally) for every NOT NULL column except primary keys! - * - * Column definition are compatible with database Migrations and AbstractColumn types. - * - * Column definition examples (by default all columns has flag NOT NULL): - * const SCHEMA = [ - * 'id' => 'primary', - * 'name' => 'string', //Default length is 255 characters. - * 'email' => 'string(255), nullable', //Can be NULL - * 'status' => 'enum(active, pending, disabled)', //Enum values, trimmed - * 'balance' => 'decimal(10, 2)', - * 'message' => 'text, null', //Alias for nullable - * 'time_expired' => 'timestamp' - * ]; - * - * Attention, column state will be affected! - * - * @param bool $hasDefault Must be set to true if default value was set by user. - * @param mixed $default Default value declared by record schema. - * - * @throws SchemaException - * - * @see AbstractColumn - */ - protected function renderColumn(AbstractColumn $column, array $type, bool $hasDefault, $default = null): void - { - // ORM force EVERY column to NOT NULL state unless different is said - $column->nullable(false); - - if ($this->hasFlag($type, 'null') || $this->hasFlag($type, 'nullable')) { - // indication that column is nullable - $column->nullable(true); - } - - try { - // bypassing call to AbstractColumn->__call method (or specialized column method) - \call_user_func_array([$column, $type['type']], $type['options']); - } catch (\Throwable $e) { - throw new SchemaException( - "Invalid column type definition in '{$column->getTable()}'.'{$column->getName()}'", - $e->getCode(), - $e, - ); - } - - if (\in_array($column->getAbstractType(), ['primary', 'bigPrimary'])) { - // no default value can be set of primary keys - return; - } - - if (!$hasDefault && !$column->isNullable()) { - if (!$this->hasFlag($type, 'required') && !$this->hasFlag($type, 'primary')) { - // we have to come up with some default value - $column->defaultValue($this->castDefault($column)); - } - - return; - } - - if ($default === null) { - // default value is stated and NULL, clear what to do - $column->nullable(true); - } - - $column->defaultValue($default); - } - - protected function parse(string $table, string $column, string $definition): array - { - if ( - !\preg_match( - '/(?P[a-z]+)(?: *\((?P[^\)]+)\))?(?: *, *(?P.+))?/i', - $definition, - $type, - ) - ) { - throw new SchemaException("Invalid column type definition in '{$table}'.'{$column}'"); - } - - if (empty($type['options'])) { - $type['options'] = []; - } else { - $type['options'] = \array_map('trim', \explode(',', $type['options'] ?? '')); - } - - if (empty($type['flags'])) { - $type['flags'] = []; - } else { - $type['flags'] = \array_map('trim', \explode(',', $type['flags'] ?? '')); - } - - unset($type[0], $type[1], $type[2], $type[3]); - - return $type; - } - - protected function hasFlag(array $type, string $flag): bool - { - return \in_array($flag, $type['flags'], true); - } - - /** - * Cast default value based on column type. Required to prevent conflicts when not nullable - * column added to existed table with data in. - * - * @return mixed - */ - protected function castDefault(AbstractColumn $column) - { - if (\in_array($column->getAbstractType(), ['timestamp', 'datetime', 'time', 'date'])) { - return 0; - } - - if ($column->getAbstractType() === 'enum') { - // we can use first enum value as default - return $column->getEnumValues()[0]; - } - - switch ($column->getType()) { - case 'int': - return 0; - case 'float': - return 0.0; - case 'bool': - return false; - } - - return ''; - } -} diff --git a/tests/Behavior/Utils/TestLogger.php b/tests/Behavior/Utils/TestLogger.php deleted file mode 100644 index d0bcd03..0000000 --- a/tests/Behavior/Utils/TestLogger.php +++ /dev/null @@ -1,45 +0,0 @@ -enabled = true; - } - - public function disable(): void - { - $this->enabled = false; - } - - public function log(mixed $level, mixed $message, array $context = []): void - { - if (!$this->enabled) { - return; - } - - if ($level === LogLevel::ERROR) { - echo " \n! \033[31m" . $message . "\033[0m"; - } elseif ($level === LogLevel::ALERT) { - echo " \n! \033[35m" . $message . "\033[0m"; - } elseif (\strpos($message, 'SHOW') === 0) { - echo " \n> \033[34m" . $message . "\033[0m"; - } elseif (\strpos($message, 'SELECT') === 0) { - echo " \n> \033[32m" . $message . "\033[0m"; - } else { - echo " \n> \033[33m" . $message . "\033[0m"; - } - } -} diff --git a/tests/Feature/Common/CreatedAt/CreatedAtTest.php b/tests/Feature/Common/CreatedAt/CreatedAtTest.php new file mode 100644 index 0000000..99bcc1d --- /dev/null +++ b/tests/Feature/Common/CreatedAt/CreatedAtTest.php @@ -0,0 +1,51 @@ +registry->getEntity(Post::class)->getFields(); + + Assert::true($fields->has('createdAt')); + Assert::true($fields->hasColumn('created_at')); + Assert::same($fields->get('createdAt')->getType(), 'datetime'); + Assert::same($fields->get('createdAt')->getGenerated(), GeneratedField::BEFORE_INSERT); + + // No new fields added + Assert::same($fields->count(), 3); + } + + #[Test] + public function testAddedColumn(): void + { + $fields = $this->registry->getEntity(Post::class)->getFields(); + + Assert::true($fields->has('newField')); + Assert::true($fields->hasColumn('new_field')); + Assert::same($fields->get('newField')->getType(), 'datetime'); + Assert::same($fields->get('newField')->getGenerated(), GeneratedField::BEFORE_INSERT); + } + + #[BeforeTest] + protected function setUp(): void + { + $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/CreatedAt'], + 'exclude' => [], + ]))); + } +} diff --git a/tests/Behavior/Functional/Driver/Common/CreatedAt/ListenerTest.php b/tests/Feature/Common/CreatedAt/ListenerTest.php similarity index 79% rename from tests/Behavior/Functional/Driver/Common/CreatedAt/ListenerTest.php rename to tests/Feature/Common/CreatedAt/ListenerTest.php index b423edc..a636772 100644 --- a/tests/Behavior/Functional/Driver/Common/CreatedAt/ListenerTest.php +++ b/tests/Feature/Common/CreatedAt/ListenerTest.php @@ -2,21 +2,22 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\CreatedAt; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\CreatedAt; use Cycle\ORM\Entity\Behavior\Listener\CreatedAt; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\CreatedAt\Post; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest; -use Cycle\ORM\Entity\Behavior\Tests\Traits\TableTrait; +use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Heap\Heap; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; use Cycle\ORM\Select; +use Testo\Assert; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class ListenerTest extends BaseListenerTest +final class ListenerTest extends ListenerTestCase { - use TableTrait; - + #[Test] public function testCreate(): void { $post = new Post(); @@ -25,10 +26,11 @@ public function testCreate(): void $select = new Select($this->orm->with(heap: new Heap()), Post::class); $data = $select->fetchOne(); - $this->assertNotNull($data->createdAt); - $this->assertNotNull($data->customCreatedAt); + Assert::notNull($data->createdAt); + Assert::notNull($data->customCreatedAt); } + #[Test] public function testUpdate(): void { $post = new Post(); @@ -48,15 +50,14 @@ public function testUpdate(): void $select = new Select($this->orm->with(heap: new Heap()), Post::class); $data = $select->fetchOne(); - $this->assertSame(0, $data->createdAt <=> $createdAt); - $this->assertSame(0, $data->customCreatedAt <=> $customCreatedAt); - $this->assertSame('test', $data->content); + Assert::same($data->createdAt <=> $createdAt, 0); + Assert::same($data->customCreatedAt <=> $customCreatedAt, 0); + Assert::same($data->content, 'test'); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->makeTable( 'posts', [ diff --git a/tests/Behavior/Functional/Driver/Common/EventListener/EventListenerTest.php b/tests/Feature/Common/EventListener/EventListenerTest.php similarity index 50% rename from tests/Behavior/Functional/Driver/Common/EventListener/EventListenerTest.php rename to tests/Feature/Common/EventListener/EventListenerTest.php index b250ec7..58e35d0 100644 --- a/tests/Behavior/Functional/Driver/Common/EventListener/EventListenerTest.php +++ b/tests/Feature/Common/EventListener/EventListenerTest.php @@ -2,44 +2,48 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\EventListener; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\EventListener; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\CommentService; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\EventListener\Comment; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\EventListener\Post; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\PostService; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseSchemaTest; +use Cycle\ORM\Entity\Behavior\Tests\Support\SchemaTestCase; use Cycle\ORM\SchemaInterface; use Spiral\Tokenizer\Config\TokenizerConfig; use Spiral\Tokenizer\Tokenizer; +use Testo\Assert; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class EventListenerTest extends BaseSchemaTest +final class EventListenerTest extends SchemaTestCase { + #[Test] public function testSchemaWithArgs(): void { $listeners = $this->schema->define(Post::class, SchemaInterface::LISTENERS); - $this->assertIsArray($listeners); - $this->assertIsArray($listeners[0]); - $this->assertSame(PostService::class, $listeners[0][0]); - $this->assertSame(['foo' => 'modified by EventListener', 'bar' => ['baz']], $listeners[0][1]); - $this->assertCount(2, $listeners[0]); + Assert::array($listeners); + Assert::array($listeners[0]); + Assert::same($listeners[0][0], PostService::class); + Assert::same($listeners[0][1], ['foo' => 'modified by EventListener', 'bar' => ['baz']]); + Assert::count($listeners[0], 2); } + #[Test] public function testSchema(): void { $listeners = $this->schema->define(Comment::class, SchemaInterface::LISTENERS); - $this->assertIsArray($listeners); - $this->assertSame(CommentService::class, $listeners[0]); - $this->assertCount(1, $listeners); + Assert::array($listeners); + Assert::same($listeners[0], CommentService::class); + Assert::count($listeners, 1); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/EventListener'], + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/EventListener'], 'exclude' => [], ]))); } diff --git a/tests/Behavior/Functional/Driver/Common/EventListener/ListenerTest.php b/tests/Feature/Common/EventListener/ListenerTest.php similarity index 76% rename from tests/Behavior/Functional/Driver/Common/EventListener/ListenerTest.php rename to tests/Feature/Common/EventListener/ListenerTest.php index 5898203..821d2bf 100644 --- a/tests/Behavior/Functional/Driver/Common/EventListener/ListenerTest.php +++ b/tests/Feature/Common/EventListener/ListenerTest.php @@ -2,21 +2,22 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\EventListener; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\EventListener; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\EventListener\Post; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\PostService; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest; -use Cycle\ORM\Entity\Behavior\Tests\Traits\TableTrait; +use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Heap\Heap; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; use Cycle\ORM\Select; +use Testo\Assert; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class ListenerTest extends BaseListenerTest +final class ListenerTest extends ListenerTestCase { - use TableTrait; - + #[Test] public function testApply(): void { $post = new Post(); @@ -26,14 +27,13 @@ public function testApply(): void $select = new Select($this->orm->with(heap: new Heap()), Post::class); $data = $select->fetchOne(); - $this->assertSame('modified by EventListener', $data->title); - $this->assertSame('baz', $data->content); + Assert::same($data->title, 'modified by EventListener'); + Assert::same($data->content, 'baz'); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->makeTable( 'posts', [ diff --git a/tests/Feature/Common/Hook/HookTest.php b/tests/Feature/Common/Hook/HookTest.php new file mode 100644 index 0000000..f477adf --- /dev/null +++ b/tests/Feature/Common/Hook/HookTest.php @@ -0,0 +1,47 @@ +schema->define(Post::class, SchemaInterface::LISTENERS); + + Assert::array($listeners); + Assert::count($listeners, 2); + Assert::array($listeners[0]); + Assert::array($listeners[1]); + + Assert::same($listeners[0][0], Hook::class); + Assert::same($listeners[0][1], ['callable' => [PostService::class, 'update'], 'events' => [OnUpdate::class]]); + + Assert::same($listeners[1][0], Hook::class); + Assert::same($listeners[1][1], ['callable' => [Post::class, 'touch'], 'events' => [OnCreate::class, OnUpdate::class]]); + } + + #[BeforeTest] + protected function setUp(): void + { + $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/Hook'], + 'exclude' => [], + ]))); + } +} diff --git a/tests/Behavior/Functional/Driver/Common/Hook/ListenerTest.php b/tests/Feature/Common/Hook/ListenerTest.php similarity index 78% rename from tests/Behavior/Functional/Driver/Common/Hook/ListenerTest.php rename to tests/Feature/Common/Hook/ListenerTest.php index 5c7ab3c..596e4be 100644 --- a/tests/Behavior/Functional/Driver/Common/Hook/ListenerTest.php +++ b/tests/Feature/Common/Hook/ListenerTest.php @@ -2,24 +2,25 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\Hook; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\Hook; use Cycle\ORM\Entity\Behavior\Event\Mapper\Command\OnCreate; use Cycle\ORM\Entity\Behavior\Event\Mapper\Command\OnUpdate; use Cycle\ORM\Entity\Behavior\Listener\Hook; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\Hook\Post; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\PostService; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest; -use Cycle\ORM\Entity\Behavior\Tests\Traits\TableTrait; +use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Heap\Heap; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; use Cycle\ORM\Select; +use Testo\Assert; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class ListenerTest extends BaseListenerTest +final class ListenerTest extends ListenerTestCase { - use TableTrait; - + #[Test] public function testCreate(): void { $post = $this->createPost(); @@ -27,13 +28,14 @@ public function testCreate(): void $select = new Select($this->orm->with(heap: new Heap()), Post::class); $data = $select->fetchOne(); - $this->assertNotNull($data->createdAt); - $this->assertNotNull($data->updatedAt); - $this->assertNull($data->content); - $this->assertSame('test', $post->slug); - $this->assertSame(OnCreate::class, $data->lastEvent); + Assert::notNull($data->createdAt); + Assert::notNull($data->updatedAt); + Assert::null($data->content); + Assert::same($post->slug, 'test'); + Assert::same($data->lastEvent, OnCreate::class); } + #[Test] public function testUpdate(): void { $this->createPost(); @@ -50,23 +52,22 @@ public function testUpdate(): void $data = $select->fetchOne(); // Triggered OnUpdate event - $this->assertNull($content); - $this->assertSame('modified by service', $data->content); + Assert::null($content); + Assert::same($data->content, 'modified by service'); // Not triggered OnCreate event, slug NOT changed. - $this->assertSame('test', $data->slug); - $this->assertSame('TEST 2', $data->title); + Assert::same($data->slug, 'test'); + Assert::same($data->title, 'TEST 2'); // Triggered union type event OnCreate|OnUpdate - $this->assertNotNull($data->updatedAt); - $this->assertNotNull($data->createdAt); - $this->assertSame(OnUpdate::class, $data->lastEvent); + Assert::notNull($data->updatedAt); + Assert::notNull($data->createdAt); + Assert::same($data->lastEvent, OnUpdate::class); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->makeTable( 'posts', [ diff --git a/tests/Behavior/Functional/Driver/Common/OptimisticLock/InquiredRelationTest.php b/tests/Feature/Common/OptimisticLock/InquiredRelationTest.php similarity index 72% rename from tests/Behavior/Functional/Driver/Common/OptimisticLock/InquiredRelationTest.php rename to tests/Feature/Common/OptimisticLock/InquiredRelationTest.php index dda09a4..5b8e9ce 100644 --- a/tests/Behavior/Functional/Driver/Common/OptimisticLock/InquiredRelationTest.php +++ b/tests/Feature/Common/OptimisticLock/InquiredRelationTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\OptimisticLock; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\OptimisticLock; use Cycle\Annotated\Embeddings; use Cycle\Annotated\Entities; @@ -10,16 +10,9 @@ use Cycle\Annotated\Locator\TokenizerEntityLocator; use Cycle\Annotated\MergeColumns; use Cycle\Annotated\MergeIndexes; -use Cycle\ORM\Collection\ArrayCollectionFactory; -use Cycle\ORM\Config\RelationConfig; -use Cycle\ORM\Entity\Behavior\EventDrivenCommandGenerator; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\InquiredRelations\Product; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\InquiredRelations\ProductBox; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest; -use Cycle\ORM\Entity\Behavior\Tests\Traits\TableTrait; -use Cycle\ORM\Entity\Behavior\Tests\Utils\SimpleContainer; -use Cycle\ORM\Factory; -use Cycle\ORM\ORM; +use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; use Cycle\Schema\Compiler; @@ -36,11 +29,13 @@ use Spiral\Attributes\AttributeReader; use Spiral\Tokenizer\Config\TokenizerConfig; use Spiral\Tokenizer\Tokenizer; +use Testo\Assert; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class InquiredRelationTest extends BaseListenerTest +final class InquiredRelationTest extends ListenerTestCase { - use TableTrait; - + #[Test] public function testUpdateWithSelectCollection(): void { $repo = $this->orm->getRepository(Product::class); @@ -66,41 +61,31 @@ public function testUpdateWithSelectCollection(): void $this->save($product1, $product2); // Persist 2 with Fetch all products - $this->assertSame(1, $product1->revision); - $this->assertSame(1, $product2->revision); + Assert::same($product1->revision, 1); + Assert::same($product2->revision, 1); $product1->name = '222'; // Persist 2 $this->save($product1); - $this->assertSame(2, $product1->revision); + Assert::same($product1->revision, 2); // Persist 3 with Fetch all products $product1->name = '333'; $products = $repo->findAll(); $this->save($product1); - $this->assertEquals(3, $product1->revision); + Assert::equals($product1->revision, 3); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $schema = $this->compileSchema(new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/OptimisticLock/InquiredRelations'], + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/OptimisticLock/InquiredRelations'], 'exclude' => [], ]))); - $this->orm = new ORM( - new Factory( - $this->dbal, - RelationConfig::getDefault(), - null, - new ArrayCollectionFactory(), - ), - $schema, - new EventDrivenCommandGenerator($schema, new SimpleContainer()), - ); + $this->withSchema($schema); } private function compileSchema(Tokenizer $tokenizer): SchemaInterface diff --git a/tests/Behavior/Functional/Driver/Common/OptimisticLock/ListenerTest.php b/tests/Feature/Common/OptimisticLock/ListenerTest.php similarity index 80% rename from tests/Behavior/Functional/Driver/Common/OptimisticLock/ListenerTest.php rename to tests/Feature/Common/OptimisticLock/ListenerTest.php index 70b81fe..efa91cf 100644 --- a/tests/Behavior/Functional/Driver/Common/OptimisticLock/ListenerTest.php +++ b/tests/Feature/Common/OptimisticLock/ListenerTest.php @@ -2,26 +2,28 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\OptimisticLock; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\OptimisticLock; use Cycle\ORM\Entity\Behavior\Exception\OptimisticLock\ChangedVersionException; use Cycle\ORM\Entity\Behavior\Exception\OptimisticLock\RecordIsLockedException; use Cycle\ORM\Entity\Behavior\Listener\OptimisticLock; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Author; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Comment; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest; -use Cycle\ORM\Entity\Behavior\Tests\Traits\TableTrait; +use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Heap\Heap; use Cycle\ORM\Relation; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; use Cycle\ORM\Select; use Cycle\ORM\Transaction; +use Testo\Assert; +use Testo\Expect; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class ListenerTest extends BaseListenerTest +final class ListenerTest extends ListenerTestCase { - use TableTrait; - + #[Test] public function testAddVersionOnCreate(): void { $comment = new Comment(); @@ -34,12 +36,13 @@ public function testAddVersionOnCreate(): void $comment = $select->fetchOne(); - $this->assertSame(1, $comment->versionInt); - $this->assertInstanceOf(\DateTimeImmutable::class, $comment->versionDatetime); - $this->assertIsString($comment->versionMicrotime); - $this->assertIsString($comment->versionStr); + Assert::same($comment->versionInt, 1); + Assert::instanceOf($comment->versionDatetime, \DateTimeImmutable::class); + Assert::string($comment->versionMicrotime); + Assert::string($comment->versionStr); } + #[Test] public function testManualAddVersionOnCreate(): void { $comment = new Comment(); @@ -56,12 +59,13 @@ public function testManualAddVersionOnCreate(): void $comment = $select->fetchOne(); - $this->assertSame(3, $comment->versionInt); - $this->assertSame(1638275394, $comment->versionDatetime->getTimestamp()); - $this->assertSame('1638275263.792011', $comment->versionMicrotime); - $this->assertSame('b0b55bb7237bb75611f7df8175e926d1', $comment->versionStr); + Assert::same($comment->versionInt, 3); + Assert::same($comment->versionDatetime->getTimestamp(), 1638275394); + Assert::same($comment->versionMicrotime, '1638275263.792011'); + Assert::same($comment->versionStr, 'b0b55bb7237bb75611f7df8175e926d1'); } + #[Test] public function testManualVersionControl(): void { $comment = new Comment(); @@ -74,14 +78,15 @@ public function testManualVersionControl(): void $select = new Select($this->orm, Comment::class); $comment = $select->fetchOne(); - $this->assertSame(1, $comment->versionCustom); + Assert::same($comment->versionCustom, 1); $comment->versionCustom = 2; $this->save($comment); - $this->assertSame(2, $comment->versionCustom); + Assert::same($comment->versionCustom, 2); } + #[Test] public function testExceptionOnChangeVersion(): void { $comment = new Comment(); @@ -93,15 +98,15 @@ public function testExceptionOnChangeVersion(): void $select = new Select($this->orm, Comment::class); $comment = $select->fetchOne(); - $this->assertSame(1, $comment->versionInt); + Assert::same($comment->versionInt, 1); $comment->versionInt = 2; - $this->expectException(ChangedVersionException::class); - $this->expectExceptionMessage('Record version change detected. Old value `1`, a new value `2`'); + Expect::exception(ChangedVersionException::class)->withMessageContaining('Record version change detected. Old value `1`, a new value `2`'); $this->save($comment); } + #[Test] public function testUpdate(): void { $comment = new Comment(); @@ -114,8 +119,8 @@ public function testUpdate(): void $comment = $select->fetchOne(); - $this->assertSame(1, $comment->versionInt); - $this->assertSame('test', $comment->content); + Assert::same($comment->versionInt, 1); + Assert::same($comment->content, 'test'); $comment->content = 'changed'; @@ -124,10 +129,11 @@ public function testUpdate(): void $select = new Select($this->orm->with(heap: new Heap()), Comment::class); $data = $select->fetchOne(); - $this->assertSame('changed', $data->content); - $this->assertSame(2, $data->versionInt); + Assert::same($data->content, 'changed'); + Assert::same($data->versionInt, 2); } + #[Test] public function testLock(): void { $comment = new Comment(); @@ -146,15 +152,13 @@ public function testLock(): void (new Transaction($orm))->persist($data1)->run(); - $this->expectException(RecordIsLockedException::class); - $this->expectExceptionMessage('The `comment` record is locked.'); + Expect::exception(RecordIsLockedException::class)->withMessageContaining('The `comment` record is locked.'); (new Transaction($orm2))->persist($data2)->run(); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->makeTable( 'comments', [ diff --git a/tests/Feature/Common/OptimisticLock/OptimisticLockTest.php b/tests/Feature/Common/OptimisticLock/OptimisticLockTest.php new file mode 100644 index 0000000..170210d --- /dev/null +++ b/tests/Feature/Common/OptimisticLock/OptimisticLockTest.php @@ -0,0 +1,106 @@ +registry->getEntity(Post::class)->getFields(); + + Assert::true($fields->has('version')); + Assert::true($fields->hasColumn('version')); + Assert::same($fields->get('version')->getType(), 'integer'); + Assert::same($fields->get('version')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + } + + #[Test] + public function testAddStringColumn(): void + { + $fields = $this->registry->getEntity(Comment::class)->getFields(); + + Assert::true($fields->has('version')); + Assert::true($fields->hasColumn('version')); + Assert::same($fields->get('version')->getType(), ColumnInterface::STRING); + Assert::same($fields->get('version')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + } + + #[Test] + public function testAddDatetimeColumn(): void + { + $fields = $this->registry->getEntity(Page::class)->getFields(); + + Assert::true($fields->has('version')); + Assert::true($fields->hasColumn('version')); + Assert::same($fields->get('version')->getType(), 'datetime'); + Assert::same($fields->get('version')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + } + + #[Test] + public function testExistColumn(): void + { + $fields = $this->registry->getEntity(Item::class)->getFields(); + + Assert::true($fields->has('revision')); + Assert::true($fields->hasColumn('revision_field')); + Assert::same($fields->get('revision')->getType(), 'integer'); + Assert::same($fields->get('revision')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + + // not added new columns + Assert::same($fields->count(), 2); + } + + #[Test] + public function testExistColumnAndAllOptimisticLockParameters(): void + { + $fields = $this->registry->getEntity(WithAllParameters::class)->getFields(); + + Assert::true($fields->has('revision')); + Assert::true($fields->hasColumn('revision_field')); + Assert::same($fields->get('revision')->getType(), 'integer'); + Assert::same($fields->get('revision')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + + // not added new columns + Assert::same($fields->count(), 2); + } + + #[Test] + public function testAddDefaultColumAndRule(): void + { + $fields = $this->registry->getEntity(News::class)->getFields(); + + Assert::true($fields->has('version')); + Assert::true($fields->hasColumn('version')); + Assert::same($fields->get('version')->getType(), 'integer'); + Assert::same($fields->get('version')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + + Assert::same($fields->count(), 2); + } + + #[BeforeTest] + protected function setUp(): void + { + $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/OptimisticLock'], + 'exclude' => [], + ]))); + } +} diff --git a/tests/Behavior/Functional/Driver/Common/Schema/ErrorsTest.php b/tests/Feature/Common/Schema/ErrorsTest.php similarity index 64% rename from tests/Behavior/Functional/Driver/Common/Schema/ErrorsTest.php rename to tests/Feature/Common/Schema/ErrorsTest.php index 02d850f..afd1006 100644 --- a/tests/Behavior/Functional/Driver/Common/Schema/ErrorsTest.php +++ b/tests/Feature/Common/Schema/ErrorsTest.php @@ -2,28 +2,31 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\Schema; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\Schema; use Cycle\ORM\Entity\Behavior\Exception\BehaviorCompilationException; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseSchemaTest; +use Cycle\ORM\Entity\Behavior\Tests\Support\SchemaTestCase; use Spiral\Tokenizer\Config\TokenizerConfig; use Spiral\Tokenizer\Tokenizer; +use Testo\Data\DataProvider; +use Testo\Expect; +use Testo\Test; -abstract class ErrorsTest extends BaseSchemaTest +final class ErrorsTest extends SchemaTestCase { public static function errorsProvider(): array { return [ 'Field type' => [ new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/Wrong/FieldType'], + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/Wrong/FieldType'], 'exclude' => [], ])), 'Field wrongCreatedAt must be of type datetime.', ], 'Column name' => [ new Tokenizer(new TokenizerConfig([ - 'directories' => [\dirname(__DIR__, 4) . '/Fixtures/Wrong/ColumnName'], + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/Wrong/ColumnName'], 'exclude' => [], ])), 'Ambiguous column name definition. The `updatedAt` field already linked with the `custom_updated_at`', @@ -31,13 +34,11 @@ public static function errorsProvider(): array ]; } - /** - * @dataProvider errorsProvider - */ + #[Test] + #[DataProvider('errorsProvider')] public function testErrors(Tokenizer $tokenizer, string $message): void { - $this->expectException(BehaviorCompilationException::class); - $this->expectExceptionMessageMatches(\sprintf('/%s/', $message)); + Expect::exception(BehaviorCompilationException::class)->withMessageMatchingRegex(\sprintf('/%s/', $message)); $this->compileWithTokenizer($tokenizer); } diff --git a/tests/Behavior/Functional/Driver/Common/Schema/RegistryModifierTest.php b/tests/Feature/Common/Schema/RegistryModifierTest.php similarity index 63% rename from tests/Behavior/Functional/Driver/Common/Schema/RegistryModifierTest.php rename to tests/Feature/Common/Schema/RegistryModifierTest.php index 0f8f1f4..1c0eb2d 100644 --- a/tests/Behavior/Functional/Driver/Common/Schema/RegistryModifierTest.php +++ b/tests/Feature/Common/Schema/RegistryModifierTest.php @@ -2,26 +2,31 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\Schema; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\Schema; use Cycle\Database\ColumnInterface; use Cycle\ORM\Entity\Behavior\Exception\BehaviorCompilationException; use Cycle\ORM\Entity\Behavior\Schema\RegistryModifier; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\CustomTypecast; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseTest; use Cycle\ORM\Parser\Typecast; use Cycle\ORM\SchemaInterface; use Cycle\Schema\Definition\Entity; use Cycle\Schema\Registry; +use Cycle\Testing\Database\DatabaseTestCase; use Ramsey\Uuid\Uuid; +use Testo\Assert; +use Testo\Expect; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class RegistryModifierTest extends BaseTest +final class RegistryModifierTest extends DatabaseTestCase { private const ROLE_TEST = 'test'; protected RegistryModifier $modifier; protected Registry $registry; + #[Test] public function testAddDatetimeField(): void { $this->modifier->addDatetimeColumn('created_at', 'createdAt'); @@ -29,11 +34,12 @@ public function testAddDatetimeField(): void $entity = $this->registry->getEntity(self::ROLE_TEST); $fields = $entity->getFields(); - $this->assertTrue($fields->has('createdAt')); - $this->assertSame('datetime', $fields->get('createdAt')->getType()); - $this->assertSame('created_at', $fields->get('createdAt')->getColumn()); + Assert::true($fields->has('createdAt')); + Assert::same($fields->get('createdAt')->getType(), 'datetime'); + Assert::same($fields->get('createdAt')->getColumn(), 'created_at'); } + #[Test] public function testAddStringField(): void { $this->modifier->addStringColumn('version_str', 'version'); @@ -41,11 +47,12 @@ public function testAddStringField(): void $entity = $this->registry->getEntity(self::ROLE_TEST); $fields = $entity->getFields(); - $this->assertTrue($fields->has('version')); - $this->assertSame(ColumnInterface::STRING, $fields->get('version')->getType()); - $this->assertSame('version_str', $fields->get('version')->getColumn()); + Assert::true($fields->has('version')); + Assert::same($fields->get('version')->getType(), ColumnInterface::STRING); + Assert::same($fields->get('version')->getColumn(), 'version_str'); } + #[Test] public function testAddIntegerField(): void { $this->modifier->addIntegerColumn('version_int', 'version'); @@ -53,11 +60,12 @@ public function testAddIntegerField(): void $entity = $this->registry->getEntity(self::ROLE_TEST); $fields = $entity->getFields(); - $this->assertTrue($fields->has('version')); - $this->assertSame('integer', $fields->get('version')->getType()); - $this->assertSame('version_int', $fields->get('version')->getColumn()); + Assert::true($fields->has('version')); + Assert::same($fields->get('version')->getType(), 'integer'); + Assert::same($fields->get('version')->getColumn(), 'version_int'); } + #[Test] public function testAddBigIntegerField(): void { $this->modifier->addBigIntegerColumn('snowflake_column', 'snowflake'); @@ -65,21 +73,22 @@ public function testAddBigIntegerField(): void $entity = $this->registry->getEntity(self::ROLE_TEST); $fields = $entity->getFields(); - $this->assertTrue($fields->has('snowflake')); - $this->assertSame('bigInteger', $fields->get('snowflake')->getType()); - $this->assertSame('snowflake_column', $fields->get('snowflake')->getColumn()); + Assert::true($fields->has('snowflake')); + Assert::same($fields->get('snowflake')->getType(), 'bigInteger'); + Assert::same($fields->get('snowflake')->getColumn(), 'snowflake_column'); } + #[Test] public function testAddBigIntegerFieldThrowsException(): void { $this->modifier->addIntegerColumn('snowflake_column', 'snowflake'); - $this->expectException(BehaviorCompilationException::class); - $this->expectExceptionMessage('Field snowflake must be of type big integer.'); + Expect::exception(BehaviorCompilationException::class)->withMessageContaining('Field snowflake must be of type big integer.'); $this->modifier->addBigIntegerColumn('snowflake_column', 'snowflake'); } + #[Test] public function testAddSnowflakeField(): void { $this->modifier->addSnowflakeColumn('snowflake_column', 'snowflake'); @@ -87,21 +96,22 @@ public function testAddSnowflakeField(): void $entity = $this->registry->getEntity(self::ROLE_TEST); $fields = $entity->getFields(); - $this->assertTrue($fields->has('snowflake')); - $this->assertSame('snowflake', $fields->get('snowflake')->getType()); - $this->assertSame('snowflake_column', $fields->get('snowflake')->getColumn()); + Assert::true($fields->has('snowflake')); + Assert::same($fields->get('snowflake')->getType(), 'snowflake'); + Assert::same($fields->get('snowflake')->getColumn(), 'snowflake_column'); } + #[Test] public function testAddSnowflakeFieldThrowsException(): void { $this->modifier->addStringColumn('snowflake_column', 'snowflake'); - $this->expectException(BehaviorCompilationException::class); - $this->expectExceptionMessage('Field snowflake must be of type snowflake.'); + Expect::exception(BehaviorCompilationException::class)->withMessageContaining('Field snowflake must be of type snowflake.'); $this->modifier->addSnowflakeColumn('snowflake_column', 'snowflake'); } + #[Test] public function testAddUlidField(): void { $this->modifier->addUlidColumn('ulid_column', 'ulid'); @@ -109,21 +119,22 @@ public function testAddUlidField(): void $entity = $this->registry->getEntity(self::ROLE_TEST); $fields = $entity->getFields(); - $this->assertTrue($fields->has('ulid')); - $this->assertSame('ulid', $fields->get('ulid')->getType()); - $this->assertSame('ulid_column', $fields->get('ulid')->getColumn()); + Assert::true($fields->has('ulid')); + Assert::same($fields->get('ulid')->getType(), 'ulid'); + Assert::same($fields->get('ulid')->getColumn(), 'ulid_column'); } + #[Test] public function testAddUlidFieldThrowsException(): void { $this->modifier->addIntegerColumn('ulid_column', 'ulid'); - $this->expectException(BehaviorCompilationException::class); - $this->expectExceptionMessage('Field ulid must be of type ulid.'); + Expect::exception(BehaviorCompilationException::class)->withMessageContaining('Field ulid must be of type ulid.'); $this->modifier->addUlidColumn('ulid_column', 'ulid'); } + #[Test] public function testAddUuidField(): void { $this->modifier->addUuidColumn('uuid_column', 'uuid'); @@ -131,21 +142,22 @@ public function testAddUuidField(): void $entity = $this->registry->getEntity(self::ROLE_TEST); $fields = $entity->getFields(); - $this->assertTrue($fields->has('uuid')); - $this->assertSame('uuid', $fields->get('uuid')->getType()); - $this->assertSame('uuid_column', $fields->get('uuid')->getColumn()); + Assert::true($fields->has('uuid')); + Assert::same($fields->get('uuid')->getType(), 'uuid'); + Assert::same($fields->get('uuid')->getColumn(), 'uuid_column'); } + #[Test] public function testAddUuidFieldThrowsException(): void { $this->modifier->addIntegerColumn('uuid_column', 'uuid'); - $this->expectException(BehaviorCompilationException::class); - $this->expectExceptionMessage('Field uuid must be of type uuid.'); + Expect::exception(BehaviorCompilationException::class)->withMessageContaining('Field uuid must be of type uuid.'); $this->modifier->addUuidColumn('uuid_column', 'uuid'); } + #[Test] public function testAddTypecast(): void { $this->modifier->addUuidColumn('uuid_column', 'uuid'); @@ -160,17 +172,15 @@ public function testAddTypecast(): void $this->modifier->setTypecast($field3, 'int', CustomTypecast::class); // field has custom UUID typecast - $this->assertSame([Uuid::class, 'fromString'], $field1->getTypecast()); - $this->assertSame('int', $field2->getTypecast()); - $this->assertSame('int', $field3->getTypecast()); + Assert::same($field1->getTypecast(), [Uuid::class, 'fromString']); + Assert::same($field2->getTypecast(), 'int'); + Assert::same($field3->getTypecast(), 'int'); // entity has default typecast - $this->assertSame( - [Typecast::class, CustomTypecast::class], - $this->registry->getEntity(self::ROLE_TEST)->getTypecast(), - ); + Assert::same($this->registry->getEntity(self::ROLE_TEST)->getTypecast(), [Typecast::class, CustomTypecast::class]); } + #[Test] public function testAddTypecastEntityWithTypecast(): void { $this->registry->getEntity(self::ROLE_TEST)->setTypecast(CustomTypecast::class); @@ -181,15 +191,13 @@ public function testAddTypecastEntityWithTypecast(): void $this->modifier->setTypecast($field, [Uuid::class, 'fromString']); // field has custom UUID typecast - $this->assertSame([Uuid::class, 'fromString'], $field->getTypecast()); + Assert::same($field->getTypecast(), [Uuid::class, 'fromString']); // entity has default typecast and custom typecast - $this->assertSame( - [CustomTypecast::class, Typecast::class], - $this->registry->getEntity(self::ROLE_TEST)->getTypecast(), - ); + Assert::same($this->registry->getEntity(self::ROLE_TEST)->getTypecast(), [CustomTypecast::class, Typecast::class]); } + #[Test] public function testAddTypecastShouldBeSkipped(): void { $this->registry->getEntity(self::ROLE_TEST); @@ -197,18 +205,20 @@ public function testAddTypecastShouldBeSkipped(): void $this->modifier->addUuidColumn('uuid_column', 'uuid'); $this->registry->getDefaults()->offsetSet(SchemaInterface::TYPECAST_HANDLER, Typecast::class); - $this->assertNull($this->registry->getEntity(self::ROLE_TEST)->getTypecast()); + Assert::null($this->registry->getEntity(self::ROLE_TEST)->getTypecast()); } + #[Test] public function testAddTypecastShouldBeDuplicated(): void { $this->registry->getEntity(self::ROLE_TEST)->setTypecast(CustomTypecast::class); $this->modifier->addUuidColumn('uuid_column', 'uuid'); - $this->assertSame(CustomTypecast::class, $this->registry->getEntity(self::ROLE_TEST)->getTypecast()); + Assert::same($this->registry->getEntity(self::ROLE_TEST)->getTypecast(), CustomTypecast::class); } + #[Test] public function testCustomTypecastNotOverridden(): void { $this->modifier->addUuidColumn('uuid_column', 'uuid'); @@ -218,13 +228,12 @@ public function testCustomTypecastNotOverridden(): void $this->modifier->setTypecast($field, [Uuid::class, 'fromString']); - $this->assertSame(['foo', 'bar'], $field->getTypecast()); + Assert::same($field->getTypecast(), ['foo', 'bar']); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->registry = new Registry($this->dbal); $entity = (new Entity())->setRole(self::ROLE_TEST); diff --git a/tests/Behavior/Functional/Driver/Common/SoftDelete/ListenerTest.php b/tests/Feature/Common/SoftDelete/ListenerTest.php similarity index 77% rename from tests/Behavior/Functional/Driver/Common/SoftDelete/ListenerTest.php rename to tests/Feature/Common/SoftDelete/ListenerTest.php index 09affe9..a565061 100644 --- a/tests/Behavior/Functional/Driver/Common/SoftDelete/ListenerTest.php +++ b/tests/Feature/Common/SoftDelete/ListenerTest.php @@ -2,22 +2,23 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\SoftDelete; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\SoftDelete; use Cycle\ORM\Entity\Behavior\Listener\SoftDelete; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\SoftDelete\Post; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest; -use Cycle\ORM\Entity\Behavior\Tests\Traits\TableTrait; +use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Heap\Heap; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; use Cycle\ORM\Select; use Cycle\ORM\Transaction; +use Testo\Assert; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class ListenerTest extends BaseListenerTest +final class ListenerTest extends ListenerTestCase { - use TableTrait; - + #[Test] public function testDelete(): void { $this->save(new Post()); @@ -25,8 +26,8 @@ public function testDelete(): void $select = new Select($this->orm, Post::class); $post = $select->fetchOne(); - $this->assertNull($post->deletedAt); - $this->assertNull($post->customDeletedAt); + Assert::null($post->deletedAt); + Assert::null($post->customDeletedAt); $tr = new Transaction($this->orm); $tr->delete($post); @@ -35,15 +36,14 @@ public function testDelete(): void $select = new Select($this->orm->with(heap: new Heap()), Post::class); $data = $select->fetchOne(); - $this->assertInstanceOf(Post::class, $data); - $this->assertNotNull($data->deletedAt); - $this->assertNotNull($data->customDeletedAt); + Assert::instanceOf($data, Post::class); + Assert::notNull($data->deletedAt); + Assert::notNull($data->customDeletedAt); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->makeTable( 'posts', [ diff --git a/tests/Feature/Common/SoftDelete/SoftDeleteTest.php b/tests/Feature/Common/SoftDelete/SoftDeleteTest.php new file mode 100644 index 0000000..8f3e54a --- /dev/null +++ b/tests/Feature/Common/SoftDelete/SoftDeleteTest.php @@ -0,0 +1,51 @@ +registry->getEntity(Post::class)->getFields(); + + Assert::true($fields->has('deletedAt')); + Assert::true($fields->hasColumn('deleted_at')); + Assert::same($fields->get('deletedAt')->getType(), 'datetime'); + Assert::same($fields->get('deletedAt')->getGenerated(), GeneratedField::BEFORE_UPDATE); + + // No new fields added + Assert::same($fields->count(), 3); + } + + #[Test] + public function testAddedColumn(): void + { + $fields = $this->registry->getEntity(Post::class)->getFields(); + + Assert::true($fields->has('newField')); + Assert::true($fields->hasColumn('new_field')); + Assert::same($fields->get('newField')->getType(), 'datetime'); + Assert::same($fields->get('newField')->getGenerated(), GeneratedField::BEFORE_UPDATE); + } + + #[BeforeTest] + protected function setUp(): void + { + $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/SoftDelete'], + 'exclude' => [], + ]))); + } +} diff --git a/tests/Behavior/Functional/Driver/Common/UpdatedAt/ListenerTest.php b/tests/Feature/Common/UpdatedAt/ListenerTest.php similarity index 80% rename from tests/Behavior/Functional/Driver/Common/UpdatedAt/ListenerTest.php rename to tests/Feature/Common/UpdatedAt/ListenerTest.php index fae6ce0..f195a82 100644 --- a/tests/Behavior/Functional/Driver/Common/UpdatedAt/ListenerTest.php +++ b/tests/Feature/Common/UpdatedAt/ListenerTest.php @@ -2,21 +2,22 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\UpdatedAt; +namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\UpdatedAt; use Cycle\ORM\Entity\Behavior\Listener\UpdatedAt; use Cycle\ORM\Entity\Behavior\Tests\Fixtures\UpdatedAt\Post; -use Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest; -use Cycle\ORM\Entity\Behavior\Tests\Traits\TableTrait; +use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase; use Cycle\ORM\Heap\Heap; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; use Cycle\ORM\Select; +use Testo\Assert; +use Testo\Lifecycle\BeforeTest; +use Testo\Test; -abstract class ListenerTest extends BaseListenerTest +final class ListenerTest extends ListenerTestCase { - use TableTrait; - + #[Test] public function testCreate(): void { $post = new Post(); @@ -25,10 +26,11 @@ public function testCreate(): void $select = new Select($this->orm->with(heap: new Heap()), Post::class); $data = $select->fetchOne(); - $this->assertNull($data->updatedAt); - $this->assertNull($data->customUpdatedAt); + Assert::null($data->updatedAt); + Assert::null($data->customUpdatedAt); } + #[Test] public function testCreateNotNullable(): void { $post = new Post(); @@ -39,9 +41,10 @@ public function testCreateNotNullable(): void $select = new Select($this->orm, Post::class); $data = $select->fetchOne(); - $this->assertInstanceOf(\DateTimeImmutable::class, $data->notNullableUpdatedAt); + Assert::instanceOf($data->notNullableUpdatedAt, \DateTimeImmutable::class); } + #[Test] public function testUpdate(): void { $post = new Post(); @@ -60,15 +63,14 @@ public function testUpdate(): void $select = new Select($this->orm->with(heap: new Heap()), Post::class); $data = $select->fetchOne(); - $this->assertGreaterThan(0, $data->updatedAt <=> $updatedAt); - $this->assertGreaterThan(0, $data->customUpdatedAt <=> $customUpdatedAt); - $this->assertSame('test', $data->content); + Assert::numeric($data->updatedAt <=> $updatedAt)->greaterThan(0); + Assert::numeric($data->customUpdatedAt <=> $customUpdatedAt)->greaterThan(0); + Assert::same($data->content, 'test'); } - public function setUp(): void + #[BeforeTest] + protected function setUp(): void { - parent::setUp(); - $this->makeTable( 'posts', [ diff --git a/tests/Feature/Common/UpdatedAt/UpdatedAtTest.php b/tests/Feature/Common/UpdatedAt/UpdatedAtTest.php new file mode 100644 index 0000000..ba022ab --- /dev/null +++ b/tests/Feature/Common/UpdatedAt/UpdatedAtTest.php @@ -0,0 +1,51 @@ +registry->getEntity(Post::class)->getFields(); + + Assert::true($fields->has('updatedAt')); + Assert::true($fields->hasColumn('updated_at')); + Assert::same($fields->get('updatedAt')->getType(), 'datetime'); + Assert::same($fields->get('updatedAt')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + + // No new fields added + Assert::same($fields->count(), 3); + } + + #[Test] + public function testAddedColumn(): void + { + $fields = $this->registry->getEntity(Post::class)->getFields(); + + Assert::true($fields->has('newField')); + Assert::true($fields->hasColumn('new_field')); + Assert::same($fields->get('newField')->getType(), 'datetime'); + Assert::same($fields->get('newField')->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE); + } + + #[BeforeTest] + protected function setUp(): void + { + $this->compileWithTokenizer(new Tokenizer(new TokenizerConfig([ + 'directories' => [\dirname(__DIR__, 3) . '/Fixtures/UpdatedAt'], + 'exclude' => [], + ]))); + } +} diff --git a/tests/Behavior/Fixtures/CommentService.php b/tests/Fixtures/CommentService.php similarity index 100% rename from tests/Behavior/Fixtures/CommentService.php rename to tests/Fixtures/CommentService.php diff --git a/tests/Behavior/Fixtures/CreatedAt/Post.php b/tests/Fixtures/CreatedAt/Post.php similarity index 100% rename from tests/Behavior/Fixtures/CreatedAt/Post.php rename to tests/Fixtures/CreatedAt/Post.php diff --git a/tests/Behavior/Fixtures/CustomTypecast.php b/tests/Fixtures/CustomTypecast.php similarity index 100% rename from tests/Behavior/Fixtures/CustomTypecast.php rename to tests/Fixtures/CustomTypecast.php diff --git a/tests/Behavior/Fixtures/EventListener/Comment.php b/tests/Fixtures/EventListener/Comment.php similarity index 100% rename from tests/Behavior/Fixtures/EventListener/Comment.php rename to tests/Fixtures/EventListener/Comment.php diff --git a/tests/Behavior/Fixtures/EventListener/Post.php b/tests/Fixtures/EventListener/Post.php similarity index 100% rename from tests/Behavior/Fixtures/EventListener/Post.php rename to tests/Fixtures/EventListener/Post.php diff --git a/tests/Behavior/Fixtures/Hook/Post.php b/tests/Fixtures/Hook/Post.php similarity index 100% rename from tests/Behavior/Fixtures/Hook/Post.php rename to tests/Fixtures/Hook/Post.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/Author.php b/tests/Fixtures/OptimisticLock/Author.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/Author.php rename to tests/Fixtures/OptimisticLock/Author.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/Comment.php b/tests/Fixtures/OptimisticLock/Comment.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/Comment.php rename to tests/Fixtures/OptimisticLock/Comment.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/InquiredRelations/Product.php b/tests/Fixtures/OptimisticLock/InquiredRelations/Product.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/InquiredRelations/Product.php rename to tests/Fixtures/OptimisticLock/InquiredRelations/Product.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/InquiredRelations/ProductBox.php b/tests/Fixtures/OptimisticLock/InquiredRelations/ProductBox.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/InquiredRelations/ProductBox.php rename to tests/Fixtures/OptimisticLock/InquiredRelations/ProductBox.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/Item.php b/tests/Fixtures/OptimisticLock/Item.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/Item.php rename to tests/Fixtures/OptimisticLock/Item.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/News.php b/tests/Fixtures/OptimisticLock/News.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/News.php rename to tests/Fixtures/OptimisticLock/News.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/Page.php b/tests/Fixtures/OptimisticLock/Page.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/Page.php rename to tests/Fixtures/OptimisticLock/Page.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/Post.php b/tests/Fixtures/OptimisticLock/Post.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/Post.php rename to tests/Fixtures/OptimisticLock/Post.php diff --git a/tests/Behavior/Fixtures/OptimisticLock/WithAllParameters.php b/tests/Fixtures/OptimisticLock/WithAllParameters.php similarity index 100% rename from tests/Behavior/Fixtures/OptimisticLock/WithAllParameters.php rename to tests/Fixtures/OptimisticLock/WithAllParameters.php diff --git a/tests/Behavior/Fixtures/PostService.php b/tests/Fixtures/PostService.php similarity index 100% rename from tests/Behavior/Fixtures/PostService.php rename to tests/Fixtures/PostService.php diff --git a/tests/Behavior/Fixtures/SoftDelete/Post.php b/tests/Fixtures/SoftDelete/Post.php similarity index 100% rename from tests/Behavior/Fixtures/SoftDelete/Post.php rename to tests/Fixtures/SoftDelete/Post.php diff --git a/tests/Behavior/Fixtures/UpdatedAt/Post.php b/tests/Fixtures/UpdatedAt/Post.php similarity index 100% rename from tests/Behavior/Fixtures/UpdatedAt/Post.php rename to tests/Fixtures/UpdatedAt/Post.php diff --git a/tests/Behavior/Fixtures/Wrong/ColumnName/User.php b/tests/Fixtures/Wrong/ColumnName/User.php similarity index 100% rename from tests/Behavior/Fixtures/Wrong/ColumnName/User.php rename to tests/Fixtures/Wrong/ColumnName/User.php diff --git a/tests/Behavior/Fixtures/Wrong/FieldType/User.php b/tests/Fixtures/Wrong/FieldType/User.php similarity index 100% rename from tests/Behavior/Fixtures/Wrong/FieldType/User.php rename to tests/Fixtures/Wrong/FieldType/User.php diff --git a/tests/Behavior/Functional/Driver/Common/Integration/BaseTest.php b/tests/Support/IntegrationTestCase.php similarity index 67% rename from tests/Behavior/Functional/Driver/Common/Integration/BaseTest.php rename to tests/Support/IntegrationTestCase.php index 8b84e24..d87bf5f 100644 --- a/tests/Behavior/Functional/Driver/Common/Integration/BaseTest.php +++ b/tests/Support/IntegrationTestCase.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\Integration; +namespace Cycle\ORM\Entity\Behavior\Tests\Support; use Cycle\Annotated\Embeddings; use Cycle\Annotated\Entities; @@ -11,15 +11,7 @@ use Cycle\Annotated\MergeColumns; use Cycle\Annotated\MergeIndexes; use Cycle\Annotated\TableInheritance; -use Cycle\ORM\Collection\ArrayCollectionFactory; -use Cycle\ORM\Config\RelationConfig; -use Cycle\ORM\Entity\Behavior\EventDrivenCommandGenerator; -use Cycle\ORM\Entity\Behavior\Tests\Utils\SimpleContainer; -use Cycle\ORM\Factory; -use Cycle\ORM\ORM; -use Cycle\ORM\ORMInterface; use Cycle\ORM\Schema; -use Cycle\ORM\SchemaInterface; use Cycle\ORM\Transaction\UnitOfWork; use Cycle\Schema\Compiler; use Cycle\Schema\Generator\ForeignKeys; @@ -37,18 +29,11 @@ use Spiral\Tokenizer\Config\TokenizerConfig; use Spiral\Tokenizer\Tokenizer; -abstract class BaseTest extends \Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseTest +/** + * Base of the regression cases: compiles the case's entities, creates their tables and builds the ORM. + */ +abstract class IntegrationTestCase extends ListenerTestCase { - protected SchemaInterface $schema; - protected ORMInterface $orm; - - public function tearDown(): void - { - $this->disableProfiling(); - unset($this->orm, $this->schema); - parent::tearDown(); - } - /** * @param non-empty-array|non-empty-string $entitiesPath */ @@ -63,7 +48,7 @@ protected function prepareOrm(string|array $entitiesPath): void $classLocator = $tokenizer->classLocator(); - $this->schema = new Schema((new Compiler())->compile(new Registry($this->dbal), [ + $this->withSchema(new Schema((new Compiler())->compile(new Registry($this->dbal), [ new ResetTables(), new Embeddings(new TokenizerEmbeddingLocator($classLocator, $reader), $reader), new Entities(new TokenizerEntityLocator($classLocator, $reader), $reader), @@ -79,18 +64,7 @@ protected function prepareOrm(string|array $entitiesPath): void new MergeIndexes($reader), new SyncTables(), new GenerateTypecast(), - ])); - - $this->orm = new ORM( - new Factory( - $this->dbal, - RelationConfig::getDefault(), - null, - new ArrayCollectionFactory(), - ), - $this->schema, - new EventDrivenCommandGenerator($this->schema, new SimpleContainer()), - ); + ]))); } protected function save(object ...$entities): void diff --git a/tests/Support/ListenerTestCase.php b/tests/Support/ListenerTestCase.php new file mode 100644 index 0000000..05790b4 --- /dev/null +++ b/tests/Support/ListenerTestCase.php @@ -0,0 +1,33 @@ +orm = new ORM( + new Factory($this->dbal, RelationConfig::getDefault(), null, new ArrayCollectionFactory()), + $schema, + new EventDrivenCommandGenerator($schema, new SimpleContainer()), + ); + } +} diff --git a/tests/Behavior/Functional/Driver/Common/BaseSchemaTest.php b/tests/Support/SchemaTestCase.php similarity index 79% rename from tests/Behavior/Functional/Driver/Common/BaseSchemaTest.php rename to tests/Support/SchemaTestCase.php index ebf7cf3..bf17e03 100644 --- a/tests/Behavior/Functional/Driver/Common/BaseSchemaTest.php +++ b/tests/Support/SchemaTestCase.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common; +namespace Cycle\ORM\Entity\Behavior\Tests\Support; use Cycle\Annotated\Embeddings; use Cycle\Annotated\Entities; @@ -22,15 +22,19 @@ use Cycle\Schema\Generator\ResetTables; use Cycle\Schema\Generator\ValidateEntities; use Cycle\Schema\Registry; +use Cycle\Testing\Database\DatabaseTestCase; use Spiral\Attributes\AttributeReader; use Spiral\Tokenizer\Tokenizer; -abstract class BaseSchemaTest extends BaseTest +/** + * Compiles the annotated entities of a directory without creating tables. + */ +abstract class SchemaTestCase extends DatabaseTestCase { - protected ?Registry $registry = null; - protected ?SchemaInterface $schema = null; + protected Registry $registry; + protected SchemaInterface $schema; - public function compileWithTokenizer(Tokenizer $tokenizer): void + protected function compileWithTokenizer(Tokenizer $tokenizer): void { $reader = new AttributeReader(); @@ -51,12 +55,4 @@ public function compileWithTokenizer(Tokenizer $tokenizer): void new GenerateTypecast(), ])); } - - public function tearDown(): void - { - parent::tearDown(); - - $this->schema = null; - $this->registry = null; - } } diff --git a/tests/Unit/Schema/RegistryModifierTest.php b/tests/Unit/Schema/RegistryModifierTest.php new file mode 100644 index 0000000..ab60029 --- /dev/null +++ b/tests/Unit/Schema/RegistryModifierTest.php @@ -0,0 +1,152 @@ + new Database\Config\SQLiteDriverConfig( - queryCache: true, - options: [ - 'logInterpolatedQueries' => true, - ], - ), - 'mysql' => new Database\Config\MySQLDriverConfig( - connection: new Database\Config\MySQL\TcpConnectionConfig( - database: 'spiral', - host: '127.0.0.1', - port: 13306, - user: 'root', - password: 'YourStrong!Passw0rd', - ), - queryCache: true, - options: [ - 'logInterpolatedQueries' => true, - ], - ), - 'postgres' => new Database\Config\PostgresDriverConfig( - connection: new Database\Config\Postgres\TcpConnectionConfig( - database: 'spiral', - host: '127.0.0.1', - port: 15432, - user: 'postgres', - password: 'YourStrong!Passw0rd', - ), - schema: 'public', - queryCache: true, - options: [ - 'logInterpolatedQueries' => true, - ], - ), - 'sqlserver' => new Database\Config\SQLServerDriverConfig( - connection: new Database\Config\SQLServer\TcpConnectionConfig( - database: 'tempdb', - host: '127.0.0.1', - port: 11433, - trustServerCertificate: true, - user: 'SA', - password: 'YourStrong!Passw0rd', - ), - queryCache: true, - options: [ - 'logInterpolatedQueries' => true, - ], - ), -]; - -$db = \getenv('DB') ?: null; -\Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseTest::$config = [ - 'debug' => \getenv('DB_DEBUG') ?: false, -] + ( - $db === null - ? $drivers - : \array_intersect_key($drivers, \array_flip((array) $db)) -); diff --git a/tests/docker-compose.yml b/tests/docker-compose.yml deleted file mode 100644 index 4a6c6c1..0000000 --- a/tests/docker-compose.yml +++ /dev/null @@ -1,27 +0,0 @@ -services: - sqlserver: - image: mcr.microsoft.com/mssql/server:2019-latest - ports: - - "11433:1433" - environment: - SA_PASSWORD: "YourStrong!Passw0rd" - ACCEPT_EULA: "Y" - - mysql_latest: - image: mysql:8.0 - command: --default-authentication-plugin=mysql_native_password - ports: - - "13306:3306" - environment: - MYSQL_DATABASE: "spiral" - MYSQL_ROOT_PASSWORD: "YourStrong!Passw0rd" - MYSQL_ROOT_HOST: "%" - - postgres: - image: postgres:12 - ports: - - "15432:5432" - environment: - POSTGRES_DB: "spiral" - POSTGRES_USER: "postgres" - POSTGRES_PASSWORD: "YourStrong!Passw0rd" diff --git a/tests/generate-case.php b/tests/generate-case.php deleted file mode 100644 index 2ea6030..0000000 --- a/tests/generate-case.php +++ /dev/null @@ -1,84 +0,0 @@ -getRealPath(); - $target = \substr($filePath, \strlen($caseTemplateDir)); - - // creating directory... - $dirName = \dirname($copyDir . $target); - if (!\is_dir($dirName)) { - \mkdir($dirName, recursive: true); - } - - $contents = \str_replace($caseTemplateDirName, \basename($copyDir), \file_get_contents($filePath)); - \file_put_contents($copyDir . $target, $contents); - } -} - -$options = \getopt('', [ - 'case-name:', - 'template:', -]); - -$copyDir = isset($options['case-name']) - ? $integrationDir . DIRECTORY_SEPARATOR . $options['case-name'] - : defaultCaseName($integrationDir); - -if (\file_exists($copyDir)) { - echo "Error. Tests folder `$copyDir` already exists\n"; - exit(1); -} - -echo \sprintf("Generating new test case '%s'... \n", \basename($copyDir)); - -\mkdir($copyDir); -$copyDir = \realpath($copyDir); - -copyTemplateFiles($copyDir, $options['template'] ?? 'CaseTemplate'); - -require 'generate.php'; - -echo "Done. New test case is here:\n$copyDir\n"; diff --git a/tests/generate.php b/tests/generate.php deleted file mode 100644 index a0e51a1..0000000 --- a/tests/generate.php +++ /dev/null @@ -1,116 +0,0 @@ - [__DIR__ . '/Behavior/Functional/Driver/Common'], - 'exclude' => [], -])); - -$databases = [ - 'sqlite' => [ - 'namespace' => 'Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\SQLite', - 'directory' => __DIR__ . '/Behavior/Functional/Driver/SQLite/', - ], - 'mysql' => [ - 'namespace' => 'Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\MySQL', - 'directory' => __DIR__ . '/Behavior/Functional/Driver/MySQL/', - ], - 'postgres' => [ - 'namespace' => 'Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Postgres', - 'directory' => __DIR__ . '/Behavior/Functional/Driver/Postgres/', - ], - 'sqlserver' => [ - 'namespace' => 'Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\SQLServer', - 'directory' => __DIR__ . '/Behavior/Functional/Driver/SQLServer/', - ], -]; - -echo "Generating test classes for all database types...\n"; - -$classes = $tokenizer - ->classLocator() - ->getClasses(\Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseTest::class); - -foreach ($classes as $class) { - foreach ($class->getMethods() as $method) { - if ($method->isAbstract()) { - echo "Skip class {$class->getName()} with abstract methods.\n"; - continue 2; - } - } - - if ( - !$class->isAbstract() - // Has abstract methods - || $class->getName() == \Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseTest::class - || $class->getName() == \Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseListenerTest::class - || $class->getName() == \Cycle\ORM\Entity\Behavior\Tests\Functional\Driver\Common\BaseSchemaTest::class - ) { - continue; - } - - echo "Found {$class->getName()}\n"; - - $path = \str_replace( - [\str_replace('\\', '/', __DIR__), 'Behavior/Functional/Driver/Common/'], - '', - \str_replace('\\', '/', $class->getFileName()), - ); - - $path = \ltrim($path, '/'); - - foreach ($databases as $driver => $details) { - $filename = \sprintf('%s%s', $details['directory'], $path); - $dir = \pathinfo($filename, PATHINFO_DIRNAME); - - $namespace = \str_replace( - 'Cycle\\ORM\\Entity\\Behavior\\Tests\\Functional\\Driver\\Common', - $details['namespace'], - $class->getNamespaceName(), - ); - - if (!\is_dir($dir)) { - \mkdir($dir, recursive: true); - } - - \file_put_contents( - $filename, - \sprintf( - <<getName(), - $driver, - $class->getShortName(), - $driver, - ), - ); - } -}