Skip to content

Commit

Permalink
Minor reduce of setup tables in tests (#1147)
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek authored Oct 30, 2023
1 parent 515c811 commit 05d5ab0
Show file tree
Hide file tree
Showing 11 changed files with 206 additions and 194 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test-unit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ jobs:
if [ -n "$LOG_COVERAGE" ]; then composer require --no-interaction --no-install phpunit/phpcov; fi
composer update --ansi --prefer-dist --no-interaction --no-progress --optimize-autoloader
if [ "${{ matrix.type }}" = "Phpunit Lowest" ]; then composer update --ansi --prefer-dist --prefer-lowest --prefer-stable --no-interaction --no-progress --optimize-autoloader; fi
if [ "${{ matrix.type }}" = "Phpunit Burn" ]; then sed -i 's~ *public function runBare(): void~public function runBare(): void { gc_collect_cycles(); gc_collect_cycles(); $memDiffs = array_fill(0, '"$(if [ \"$GITHUB_EVENT_NAME\" == \"schedule\" ]; then echo 64; else echo 4; fi)"', 0); for ($i = -1; $i < count($memDiffs); ++$i) { $this->_runBare(); gc_collect_cycles(); gc_collect_cycles(); $mem = memory_get_usage(); if ($i !== -1) { $memDiffs[$i] = $mem - $memPrev; } $memPrev = $mem; rsort($memDiffs); if (array_sum($memDiffs) >= 4096 * 1024 || $memDiffs[2] > 0) { $this->onNotSuccessfulTest(new AssertionFailedError( "Memory leak detected! (" . implode(" + ", array_map(fn ($v) => number_format($v / 1024, 3, ".", " "), array_filter($memDiffs))) . " KB, " . ($i + 2) . " iterations)" )); } } } private function _runBare(): void~' vendor/phpunit/phpunit/src/Framework/TestCase.php && cat vendor/phpunit/phpunit/src/Framework/TestCase.php | grep '_runBare('; fi
if [ "${{ matrix.type }}" = "Phpunit Burn" ]; then sed -i 's~ *public function runBare(): void~public function runBare(): void { gc_collect_cycles(); gc_collect_cycles(); $memDiffs = array_fill(0, '"$(if [ \"$GITHUB_EVENT_NAME\" == \"schedule\" ]; then echo 64; else echo 4; fi)"', 0); for ($i = -1; $i < count($memDiffs); ++$i) { $this->_runBare(); gc_collect_cycles(); gc_collect_cycles(); $mem = memory_get_usage(); if ($i !== -1) { $memDiffs[$i] = $mem - $memPrev; } $memPrev = $mem; rsort($memDiffs); if (array_sum($memDiffs) >= 4096 * 1024 || $memDiffs[2] > 0) { $this->onNotSuccessfulTest(new AssertionFailedError("Memory leak detected! (" . implode(" + ", array_map(static fn ($v) => number_format($v / 1024, 3, ".", " "), array_filter($memDiffs))) . " KB, " . ($i + 2) . " iterations)")); } } } private function _runBare(): void~' vendor/phpunit/phpunit/src/Framework/TestCase.php && cat vendor/phpunit/phpunit/src/Framework/TestCase.php | grep '_runBare('; fi
- name: Init
run: |
Expand Down
2 changes: 1 addition & 1 deletion src/Persistence/Sql.php
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ public function tryLoad(Model $model, $id): ?array

if (!$noId) {
if (!$model->idField) {
throw (new Exception('Unable to load field by "id" when Model->idField is not defined'))
throw (new Exception('Unable to load by "id" when Model->idField is not defined'))
->addMoreInfo('id', $id);
}

Expand Down
10 changes: 5 additions & 5 deletions src/Persistence/Sql/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ abstract class Query extends Expression
* $q->field($q->expr('2 + 2'), 'alias'); // must always use alias
*
* You can use $q->dsql() for subqueries. Subqueries will be wrapped in parentheses.
* $q->field( $q->dsql()->table('x')..., 'alias');
* $q->field($q->dsql()->table('x')..., 'alias');
*
* If you need to use funky name for the field (e.g, one containing
* a dot or a space), you should wrap it into expression:
Expand Down Expand Up @@ -1016,7 +1016,7 @@ public function expr($template = [], array $arguments = []): Expression
*
* @param string|array<string, mixed> $defaults
*
* @return Query
* @return self
*/
public function dsql($defaults = [])
{
Expand All @@ -1040,7 +1040,7 @@ public function exprNow(int $precision = null): Expression
/**
* Returns new Query object of [or] expression.
*
* @return Query
* @return self
*/
public function orExpr()
{
Expand All @@ -1050,7 +1050,7 @@ public function orExpr()
/**
* Returns new Query object of [and] expression.
*
* @return Query
* @return self
*/
public function andExpr()
{
Expand All @@ -1075,7 +1075,7 @@ public function groupConcat($field, string $separator = ',')
*
* @param mixed $operand optional operand for case expression
*
* @return Query
* @return self
*/
public function caseExpr($operand = null)
{
Expand Down
7 changes: 7 additions & 0 deletions tests/ConditionSqlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,13 @@ public function testOperations(): void
self::assertSame('John', $mm2->get('name'));
$mm2 = $mm->tryLoad(2);
self::assertNull($mm2);

$mm = clone $m;
$mm->addCondition('id', 'not in', [1, 3]);
$mm2 = $mm->tryLoad(1);
self::assertNull($mm2);
$mm2 = $mm->tryLoad(2);
self::assertSame('Sue', $mm2->get('name'));
}

public function testExpressions1(): void
Expand Down
2 changes: 2 additions & 0 deletions tests/ModelWithoutIdTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ public function testSetIdException(): void
public function testFail1(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Unable to load by "id" when Model->idField is not defined');
$this->m->load(1);
}

Expand Down Expand Up @@ -134,6 +135,7 @@ public function testLoadCondition(): void
public function testFailDelete1(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Unable to load by "id" when Model->idField is not defined');
$this->m->delete(4);
}
}
2 changes: 1 addition & 1 deletion tests/Persistence/CsvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public function testPersistenceCopy(): void

$m2 = $m->withPersistence($p2);

// TODO should be not needed after https://github.com/atk4/data/pull/690 is merged
// TODO should be not needed once https://github.com/atk4/data/pull/690 is merged
// exception: Csv persistence does not support other than LOAD ANY mode
$m2->reloadAfterSave = false;

Expand Down
7 changes: 4 additions & 3 deletions tests/Persistence/Sql/ExpressionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,21 +157,22 @@ public function provideNoTemplatingInSqlStringCases(): iterable
'\'[\'\']\'',
'\'\'\'[]\'',
'\'[]\'\'\'',
'--[]',
'-- select [a]',
'--[]' . "\n",
'-- select [a]' . "\n",
'/*[]*/',
'/* select [a] */',
] as $testStr) {
$testStr = str_replace('\'', $enclosureChar, $testStr);

yield [$testStr, $testStr, []];
yield [rtrim($testStr, "\n"), $testStr, []];

$testStrs[] = $testStr;
}
}

$fullStr = implode('', $testStrs);
yield [$fullStr, $fullStr, []];
yield [$fullStr . ' :a', $fullStr . ' []', ['foo']];

$fullStr = implode(' ', $testStrs);
yield [$fullStr, $fullStr, []];
Expand Down
41 changes: 22 additions & 19 deletions tests/Persistence/Sql/WithDb/SelectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@

class SelectTest extends TestCase
{
protected function setUp(): void
protected function setupTables(): void
{
parent::setUp();

$model = new Model($this->db, ['table' => 'employee']);
$model->addField('name');
$model->addField('surname');
Expand All @@ -37,7 +35,8 @@ protected function setUp(): void
}

/**
* @param string|Expression $table
* @param string|Expression $table
* @param ($table is null ? never : string) $alias
*/
protected function q($table = null, string $alias = null): Query
{
Expand All @@ -60,6 +59,8 @@ protected function e($template = [], array $arguments = []): Expression

public function testBasicQueries(): void
{
$this->setupTables();

self::assertCount(4, $this->q('employee')->getRows());

self::assertSame(
Expand Down Expand Up @@ -142,6 +143,8 @@ public function testExpression(): void

public function testOtherQueries(): void
{
$this->setupTables();

$this->q('employee')->mode('truncate')->executeStatement();
self::assertSame(
'0',
Expand Down Expand Up @@ -201,6 +204,8 @@ public function testOtherQueries(): void

public function testGetRowEmpty(): void
{
$this->setupTables();

$this->q('employee')->mode('truncate')->executeStatement();
$q = $this->q('employee');

Expand All @@ -209,6 +214,8 @@ public function testGetRowEmpty(): void

public function testGetOneEmptyException(): void
{
$this->setupTables();

$this->q('employee')->mode('truncate')->executeStatement();
$q = $this->q('employee')->field('name');

Expand All @@ -219,6 +226,8 @@ public function testGetOneEmptyException(): void

public function testSelectUnexistingColumnException(): void
{
$this->setupTables();

$q = $this->q('employee')->field('Sqlite must use backticks for identifier escape');

$this->expectException(Exception::class);
Expand All @@ -228,6 +237,8 @@ public function testSelectUnexistingColumnException(): void

public function testWhereExpression(): void
{
$this->setupTables();

self::assertSame([
['id' => '2', 'name' => 'Jack', 'surname' => 'Williams', 'retired' => '1'],
], $this->q('employee')->where('retired', true)->where($this->q()->expr('{}=[] or {}=[]', ['surname', 'Williams', 'surname', 'Smith']))->getRows());
Expand Down Expand Up @@ -276,17 +287,7 @@ public function testExists(): void
->where('first_name', 'John')
->exists();

if ($this->getDatabasePlatform() instanceof MySQLPlatform) {
self::assertSame([
'select exists (select * from `contacts` where `first_name` = :a)',
[':a' => 'John'],
], $q->render());
} elseif ($this->getDatabasePlatform() instanceof PostgreSQLPlatform) {
self::assertSame([
'select exists (select * from "contacts" where "first_name" = :a)',
[':a' => 'John'],
], $q->render());
} elseif ($this->getDatabasePlatform() instanceof SQLServerPlatform) {
if ($this->getDatabasePlatform() instanceof SQLServerPlatform) {
self::assertSame([
'select case when exists(select * from [contacts] where [first_name] = :a) then 1 else 0 end',
[':a' => 'John'],
Expand All @@ -297,10 +298,8 @@ public function testExists(): void
[':xxaaaa' => 'John'],
], $q->render());
} else {
self::assertSame([
'select exists (select * from `contacts` where `first_name` = :a)',
[':a' => 'John'],
], $q->render());
self::assertSameSql('select exists (select * from `contacts` where `first_name` = :a)', $q->render()[0]);
self::assertSame([':a' => 'John'], $q->render()[1]);
}
}

Expand Down Expand Up @@ -455,6 +454,8 @@ public function testImportAndAutoincrement(): void

public function testOrderDuplicate(): void
{
$this->setupTables();

$query = $this->q('employee')->field('name')
->order('id')
->order('name', 'desc')
Expand All @@ -471,6 +472,8 @@ public function testOrderDuplicate(): void

public function testSubqueryWithOrderAndLimit(): void
{
$this->setupTables();

$subQuery = $this->q('employee');
$query = $this->q($subQuery, 't')->field('name')->order('name');

Expand Down
Loading

0 comments on commit 05d5ab0

Please sign in to comment.