Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions tests/Acceptance/Common/OrmTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use Cycle\Testing\Tests\Fixtures\User;
use Cycle\Testing\Tests\Fixtures\UserSchema;
use Testo\Assert;
use Testo\Assert\State\Assertion\ComparisonFailure;
use Testo\Expect;
use Testo\Lifecycle\BeforeTest;
use Testo\Test;

Expand Down Expand Up @@ -41,6 +43,33 @@ public function savesAndLoads(): void
self::$previousOrm = $this->orm;
}

public function savedEntityIsInSyncWithItsNode(): void
{
$user = new User();
$user->email = 'b@example.com';
$this->save($user);

$extracted = $this->extractEntity($user);
$state = $this->orm->getHeap()->get($user)->getData();

Assert::same($extracted['email'], 'b@example.com');
$this->assertEntitySynced('user', $extracted, $state);
}

public function changedEntityIsOutOfSync(): never
{
$user = new User();
$user->email = 'c@example.com';
$this->save($user);
$state = $this->orm->getHeap()->get($user)->getData();
# The plugin checks the heap after the test: keep the out-of-sync entity out of it.
$this->orm->getHeap()->clean();
$user->email = 'changed@example.com';

Expect::exception(ComparisonFailure::class);
$this->assertEntitySynced('user', $this->extractEntity($user), $state);
}

public function freshOrmPerTest(): void
{
Assert::notSame($this->orm, self::$previousOrm);
Expand Down
22 changes: 22 additions & 0 deletions tests/Feature/Common/DatabaseContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,28 @@ public function tableBuilderMatchesDatabase(): void
SchemaAssert::sameAsInDb($schema);
}

public function compositeForeignKeySpansBothColumns(): void
{
$this->makeTable('pair', ['a' => 'integer', 'b' => 'integer'], pk: ['a', 'b']);
$this->makeTable('pair_ref', ['id' => 'primary', 'pa' => 'integer', 'pb' => 'integer']);

$this->makeCompositeFK('pair_ref', ['pa', 'pb'], 'pair', ['a', 'b']);

$schema = $this->schema('pair_ref');
Assert::true($schema->hasForeignKey(['pa', 'pb']));
Assert::same($schema->foreignKey(['pa', 'pb'])->getForeignKeys(), ['a', 'b']);
}

public function fetchSchemaRereadsTheTable(): void
{
$this->makeTable('reread', ['id' => 'primary']);
$declared = $this->database->table('reread')->getSchema();
$declared->string('added', 16)->nullable(true);

Assert::true($declared->hasColumn('added'));
Assert::false($this->fetchSchema($declared)->hasColumn('added'));
}

public function dbVariantSharesServer(): void
{
$this->makeTable('shared', ['id' => 'primary']);
Expand Down
42 changes: 42 additions & 0 deletions tests/Feature/Common/WrapDriverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Cycle\Testing\Tests\Feature\Common;

use Cycle\Database\Exception\StatementException;
use Cycle\Database\Exception\StatementException\ConnectionException;
use Cycle\Testing\Database\Attribute\WrapDriver;
use Cycle\Testing\Database\DatabaseTestCase;
Expand Down Expand Up @@ -42,6 +43,47 @@ public function knobsAreResetBetweenTests(): void
Assert::same($this->wrapDriver()->disconnectCalls, 0);
}

public function queriesRunThroughTheWrappedPdo(): void
{
$this->makeTable('wrapped', ['id' => 'primary', 'name' => 'string(32)']);
$table = $this->database->table('wrapped');

$table->insertMultiple(['name'], [['a'], ['b']]);

Assert::same($table->select('name')->orderBy('id')->fetchAll(), [['name' => 'a'], ['name' => 'b']]);
Assert::same($table->count(), 2);
}

public function queryCallbackExecutesTheStatements(): void
{
$this->makeTable('called', ['id' => 'primary', 'name' => 'string(32)']);
$seen = [];
$this->wrapDriver()->setQueryCallback(static function (\PDOStatement $statement, ?array $params) use (&$seen): bool {
$seen[] = $statement->queryString;
return $statement->execute($params);
});

$this->database->table('called')->insertOne(['name' => 'a']);
$rows = $this->database->query('SELECT name FROM called WHERE name = ?', ['a'])->fetchAll();

Assert::count(\preg_grep('~^\s*INSERT INTO~i', $seen), 1);
Assert::string(\end($seen))->contains('WHERE name = ?');
Assert::same($rows, [['name' => 'a']]);
}

public function statementErrorsAreMappedByTheDriver(): void
{
try {
$this->database->query('SELECT * FROM no_such_table')->fetchAll();
} catch (StatementException $e) {
Assert::false($e instanceof ConnectionException);
Assert::string($e->getQuery())->contains('no_such_table');
return;
}

Assert::fail('Querying a missing table did not fail.');
}

public function failsTransactionBegin(): never
{
# The driver reconnects and retries once, so the first two begins must fail.
Expand Down
204 changes: 204 additions & 0 deletions tests/Unit/FakePDOTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
<?php

declare(strict_types=1);

namespace Cycle\Testing\Tests\Unit;

use Cycle\Database\Driver\PDOStatementInterface;
use Cycle\Testing\Database\Mock\FakePDO;
use Testo\Assert;
use Testo\Data\DataSet;
use Testo\Expect;
use Testo\Test;

#[Test]
final class FakePDOTest
{
public function queryExecutesAtOnce(): void
{
$pdo = (new FakePDO())->willReturn([['id' => 1], ['id' => 2]]);

$statement = $pdo->query('SELECT id FROM t');

Assert::same($pdo->executed, [['sql' => 'SELECT id FROM t', 'params' => null]]);
Assert::same($statement->rowCount(), 2);
Assert::same(\iterator_to_array($statement), [['id' => 1], ['id' => 2]]);
}

public function execRecordsAndCountsTheQueuedRows(): void
{
$pdo = (new FakePDO())->willReturn([['a' => 1], ['a' => 2], ['a' => 3]]);

Assert::same($pdo->exec('DELETE FROM t'), 3);
Assert::same($pdo->exec('DELETE FROM t'), 0);
Assert::same($pdo->queries(), ['DELETE FROM t', 'DELETE FROM t']);
}

public function execThrowsTheQueuedException(): never
{
$pdo = (new FakePDO())->willThrow(new \RuntimeException('gone'));

Expect::exception(\RuntimeException::class)->withMessage('gone');
$pdo->exec('DROP TABLE t');
}

public function tracksTheTransaction(): void
{
$pdo = new FakePDO();

Assert::false($pdo->inTransaction());
Assert::true($pdo->beginTransaction());
Assert::true($pdo->inTransaction());
Assert::true($pdo->commit());
Assert::false($pdo->inTransaction());

$pdo->beginTransaction();
Assert::true($pdo->rollBack());
Assert::false($pdo->inTransaction());
}

public function lastInsertIdIsScriptable(): void
{
$pdo = new FakePDO();
Assert::same($pdo->lastInsertId(), '1');

$pdo->lastInsertId = '42';
Assert::same($pdo->lastInsertId('seq'), '42');
}

public function keepsAttributes(): void
{
$pdo = new FakePDO();

Assert::null($pdo->getAttribute(\PDO::ATTR_CASE));
Assert::true($pdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER));
Assert::same($pdo->getAttribute(\PDO::ATTR_CASE), \PDO::CASE_LOWER);
}

public function reportsNoError(): void
{
$pdo = new FakePDO();

Assert::null($pdo->errorCode());
Assert::same($pdo->errorInfo(), ['00000', null, null]);
}

public function quotesByDoublingQuotes(): void
{
Assert::same((new FakePDO())->quote("it's"), "'it''s'");
}

public function boundValuesAreTheParamsWhenExecuteGetsNone(): void
{
$pdo = new FakePDO();
$statement = $pdo->prepare('SELECT ? , ?');
$byRef = 'b';

Assert::true($statement->bindValue(1, 'a'));
Assert::true($statement->bindParam(2, $byRef));
$statement->execute();
$statement->execute(['x']);

Assert::same($pdo->executed[0]['params'], [1 => 'a', 2 => 'b']);
Assert::same($pdo->executed[1]['params'], ['x']);
}

public function withoutBindingsExecutePassesNull(): void
{
$pdo = new FakePDO();

$pdo->prepare('SELECT 1')->execute();

Assert::null($pdo->executed[0]['params']);
}

#[DataSet([\PDO::FETCH_ASSOC, ['id' => 1, 'name' => 'a']], 'assoc')]
#[DataSet([\PDO::FETCH_NUM, [1, 'a']], 'num')]
#[DataSet([\PDO::FETCH_COLUMN, 1], 'column')]
public function fetchShapesTheRow(int $mode, mixed $expected): void
{
$statement = self::executed([['id' => 1, 'name' => 'a']]);

Assert::same($statement->fetch($mode), $expected);
Assert::false($statement->fetch($mode));
}

public function fetchObjModeGivesAnObject(): void
{
$row = self::executed([['id' => 1]])->fetch(\PDO::FETCH_OBJ);

Assert::instanceOf($row, \stdClass::class);
Assert::same($row->id, 1);
}

public function fetchColumnModeOfAnEmptyRowIsNull(): void
{
Assert::null(self::executed([[]])->fetch(\PDO::FETCH_COLUMN));
}

public function fetchAllShapesEveryRowAndDrains(): void
{
$statement = self::executed([['id' => 1, 'n' => 'a'], ['id' => 2, 'n' => 'b']]);

Assert::same($statement->fetchAll(\PDO::FETCH_NUM), [[1, 'a'], [2, 'b']]);
Assert::same($statement->fetchAll(), []);
}

public function fetchColumnTakesOneValuePerRow(): void
{
$statement = self::executed([['id' => 1, 'n' => 'a'], ['id' => 2]]);

Assert::same($statement->fetchColumn(1), 'a');
Assert::null($statement->fetchColumn(1));
Assert::false($statement->fetchColumn());
}

public function fetchObjectGivesAStdClassThenFalse(): void
{
$statement = self::executed([['id' => 7]]);

$row = $statement->fetchObject();

Assert::instanceOf($row, \stdClass::class);
Assert::same($row->id, 7);
Assert::false($statement->fetchObject());
}

public function columnCountComesFromTheFirstRow(): void
{
$statement = self::executed([['id' => 1, 'n' => 'a', 'x' => null]]);

Assert::same($statement->columnCount(), 3);
Assert::true($statement->closeCursor());
Assert::same($statement->columnCount(), 0);
Assert::same($statement->rowCount(), 0);
}

public function statementStubsAnswerNeutrally(): void
{
$statement = self::executed([['id' => 1]]);
$column = null;

Assert::true($statement->bindColumn(1, $column));
Assert::true($statement->setAttribute(\PDO::ATTR_CURSOR_NAME, 'c'));
Assert::null($statement->getAttribute(\PDO::ATTR_CURSOR_NAME));
Assert::true($statement->setFetchMode(\PDO::FETCH_NUM));
Assert::false($statement->getColumnMeta(0));
Assert::false($statement->nextRowset());
Assert::null($statement->errorCode());
Assert::same($statement->errorInfo(), ['00000', null, null]);
Assert::null($statement->debugDumpParams());
Assert::same($statement->fetch(), ['id' => 1]);
}

/**
* @param list<array<array-key, mixed>> $rows
*/
private static function executed(array $rows): PDOStatementInterface
{
$statement = (new FakePDO())->willReturn($rows)->prepare('SELECT');
$statement->execute();

return $statement;
}
}
10 changes: 10 additions & 0 deletions tests/Unit/PurgerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Cycle\Database\Database;
use Cycle\Testing\Database\Memory;
use Cycle\Testing\Database\Mock\StubDriver;
use Cycle\Testing\Database\QueryLog;
use Cycle\Testing\Database\Schema\Purger;
use Cycle\Testing\Database\Schema\TableBuilder;
Expand Down Expand Up @@ -51,6 +52,15 @@ public function dropTablesOnAnEmptyDatabaseOnlyLists(): void
Assert::count($run['queries'], 1);
}

public function dropTablesOfAnotherDriverFallsBackToDropAll(): void
{
$database = self::referencedRows(new Database('default', '', StubDriver::make()));

Purger::dropTables($database->getDriver());

Assert::same($database->getTables(), []);
}

/**
* `b_child` references `a_parent`, both have a row, and foreign keys are enforced.
*/
Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/SchemaSourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
use Cycle\Testing\ORM\Schema\SchemaCompiler;
use Cycle\Testing\ORM\SchemaSource;
use Cycle\Testing\Tests\Fixtures\Note;
use Cycle\Testing\Tests\Fixtures\User;
use Cycle\Testing\Tests\Fixtures\UserSchema;
use Testo\Assert;
use Testo\Test;

Expand Down Expand Up @@ -59,6 +61,28 @@ public function ormRunsOnTheTwoDatabaseLayout(): void
Assert::same($orm->getSource(Note::class)->getDatabase()->getName(), 'secondary');
}

public function emptyHasNoRoles(): void
{
Assert::same(SchemaSource::empty()->resolve()->getRoles(), []);
}

public function fromFileReadsTheFileOnce(): void
{
$path = \tempnam(\sys_get_temp_dir(), 'cycle-testing-schema');
\file_put_contents($path, '<?php return ' . \var_export(UserSchema::schema(), true) . ';');
$source = SchemaSource::fromFile($path);

try {
$schema = $source->resolve();
} finally {
\unlink($path);
}

Assert::same($schema->getRoles(), ['user']);
Assert::same($schema->define('user', SchemaInterface::ENTITY), User::class);
Assert::same($source->resolve(), $schema);
}

private static function notes(): SchemaSource
{
return SchemaSource::compiled(
Expand Down
Loading
Loading