Skip to content

Commit

Permalink
phpunit tests: WriterFactory and Validator
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrajodas committed Nov 14, 2023
1 parent 32a5831 commit 3652624
Show file tree
Hide file tree
Showing 12 changed files with 284 additions and 384 deletions.
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@
"@tests-phpunit",
"@tests-datadir"
],
"phpcs": "phpcs -n --ignore=vendor,tests --extensions=php .",
"phpcs": "phpcs -n --ignore=vendor --extensions=php .",
"phpcbf": "phpcbf -n --ignore=vendor --extensions=php .",
"phpstan": "phpstan analyse ./src --level=max --no-progress -c phpstan.neon",
"phpstan": "phpstan analyse ./src ./tests --level=max --no-progress -c phpstan.neon",
"build": [
"@phpstan",
"@phpcs",
"@phpstan",
"@tests"
],
"ci": [
Expand Down
4 changes: 2 additions & 2 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ protected function getConfigDefinitionClass(): string

protected function getValidator(): Validator
{
return new Validator($this->getLogger(), $this->getConfig());
return new Validator($this->getLogger());
}

private function getInputTablePath(string $tableId): string
Expand Down Expand Up @@ -154,7 +154,7 @@ private function getInputTablePath(string $tableId): string
private function checkDatabaseHost(): void
{
$checker = $this->getValidator();
$checker->validateDatabaseHost();
$checker->validateDatabaseHost($this->getConfig());
}

private function isRowConfiguration(array $parameters): bool
Expand Down
13 changes: 8 additions & 5 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@

readonly class Validator
{
public function __construct(public LoggerInterface $logger, public BaseConfig $config)
public function __construct(public LoggerInterface $logger)
{
}

/**
* @throws InvalidDatabaseHostException
*/
public function validateDatabaseHost(): void
public function validateDatabaseHost(BaseConfig $config): void
{
if (!isset($this->config->getImageParameters()['approvedHostnames'])) {
if (!isset($config->getImageParameters()['approvedHostnames'])) {
return;
}
$approvedHostnames = $this->config->getImageParameters()['approvedHostnames'];
$db = $this->config->getParameters()['db'];
$approvedHostnames = $config->getImageParameters()['approvedHostnames'];
$db = $config->getParameters()['db'];
$validHostname = array_filter($approvedHostnames, function ($v) use ($db) {
return $v['host'] === $db['host'] && $v['port'] === $db['port'];
});
Expand All @@ -42,6 +42,9 @@ public function validateDatabaseHost(): void
}
}

/**
* @throws ApplicationException
*/
public function validateTableItems(string $tablePath, array $items): array
{
$manifestPath = $tablePath . '.manifest';
Expand Down
13 changes: 12 additions & 1 deletion tests/functional/DatadirTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace Keboola\DbWriter\TestsFunctional;

use Keboola\Csv\CsvWriter;
use Keboola\Csv\Exception;
use Keboola\Csv\InvalidArgumentException;
use Keboola\DatadirTests\DatadirTestCase;
use Keboola\DatadirTests\DatadirTestSpecificationInterface;
use Keboola\DbWriter\Traits\CloseSshTunnelsTrait;
Expand All @@ -19,6 +21,10 @@ class DatadirTest extends DatadirTestCase

public PdoConnection $connection;

protected string $testProjectDir;

protected string $testTempDir;

protected function getScript(): string
{
return $this->getTestFileDir() . '/../../tests/Fixtures/run.php';
Expand Down Expand Up @@ -66,14 +72,19 @@ public function testDatadir(DatadirTestSpecificationInterface $specification): v
$this->assertMatchesSpecification($specification, $process, $tempDatadir->getTmpFolder());
}

protected function exportTablesData($testTempDir): void
/**
* @throws Exception
* @throws InvalidArgumentException
*/
protected function exportTablesData(string $testTempDir): void
{
$sqlTables = <<<SQL
SELECT `table_schema`,`table_name`
FROM information_schema.tables
WHERE TABLE_SCHEMA NOT IN ("performance_schema", "mysql", "information_schema", "sys");
SQL;

/** @var array<array> $tables */
$tables = $this->connection->fetchAll($sqlTables, 3);

foreach ($tables as $table) {
Expand Down
24 changes: 0 additions & 24 deletions tests/phpunit/Base.php

This file was deleted.

189 changes: 189 additions & 0 deletions tests/phpunit/ValidatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
<?php

declare(strict_types=1);

namespace Keboola\DbWriter\Tests;

use Generator;
use Keboola\DbWriter\Exception\ApplicationException;
use Keboola\DbWriter\Exception\InvalidDatabaseHostException;
use Keboola\DbWriter\Validator;
use Keboola\DbWriterConfig\Config;
use Keboola\DbWriterConfig\Configuration\ActionConfigDefinition;
use Keboola\Temp\Temp;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use Psr\Log\Test\TestLogger;

class ValidatorTest extends TestCase
{
public function testValidHostname(): void
{
$config = new Config($this->getConfig(), new ActionConfigDefinition());

$validator = new Validator(new TestLogger());
$validator->validateDatabaseHost($config);

Assert::assertTrue(true);
}

/**
* @dataProvider invalidHostnameProvider
*/
public function testInvalidHostname(array $config, string $expectedMessage): void
{
$config = new Config($config, new ActionConfigDefinition());
$validator = new Validator(new TestLogger());

$this->expectException(InvalidDatabaseHostException::class);
$this->expectExceptionMessage($expectedMessage);
$validator->validateDatabaseHost($config);
}

/**
* @dataProvider validateTableItemsProvider
*/
public function testValidateTableItems(array $items, array $expectedItems): void
{
$manifest = [
'columns' => ['test', 'test2'],
];

$temp = new Temp();
$file = $temp->createFile('table.csv.manifest');
file_put_contents($file->getPathname(), json_encode($manifest));

$validator = new Validator(new TestLogger());
$result = $validator->validateTableItems(
substr($file->getPathname(), 0, -9),
$items,
);

Assert::assertEquals($expectedItems, $result);
}

/**
* @dataProvider invalidTableItemsProvider
*/
public function testInvalidTableItems(
?array $manifestContent,
bool $encodeJsonContent,
string $expectedExceptionMessage,
): void {
if ($manifestContent) {
$temp = new Temp();
$expectedExceptionMessage = sprintf(
$expectedExceptionMessage,
$temp->getTmpFolder(),
);
$file = $temp->createFile('table.csv.manifest');
file_put_contents(
$file->getPathname(),
$encodeJsonContent ? json_encode($manifestContent) : $manifestContent,
);
$tablePath = substr($file->getPathname(), 0, -9);
} else {
$tablePath = 'table.csv';
}

$validator = new Validator(new TestLogger());

$this->expectException(ApplicationException::class);
$this->expectExceptionMessage($expectedExceptionMessage);
$validator->validateTableItems($tablePath, []);
}

private function getConfig(): array
{
return [
'parameters' => [
'data_dir' => '/data/',
'writer_class' => 'Common',
'db' => [
'host' => 'localhost',
'port' => '3306',
'database' => 'test',
'user' => 'root',
'#password' => 'root',
],
],
'image_parameters' => [
'approvedHostnames' => [
[
'host' => 'localhost',
'port' => '3306',
],
],
],
];
}

public function invalidHostnameProvider(): Generator
{
$config = $this->getConfig();
$config['image_parameters']['approvedHostnames'][0]['host'] = 'wrongHost';

yield 'wrongHost' => [
$config,
'Hostname "localhost" with port "3306" is not approved.',
];

$config['image_parameters']['approvedHostnames'][0]['port'] = 'wrongPort';
yield 'wrongPort' => [
$config,
'Hostname "localhost" with port "3306" is not approved.',
];

$config['image_parameters']['approvedHostnames'] = [];
yield 'emptyImageParamsArray' => [
$config,
'Hostname "localhost" with port "3306" is not approved.',
];
}

public function validateTableItemsProvider(): Generator
{
$baseItems = [
[
'name' => 'test',
'type' => 'varchar',
'size' => '255',
],
[
'name' => 'test2',
'type' => 'varchar',
'size' => '255',
],
];
yield 'valid' => [
$baseItems,
$baseItems,
];

yield 'reorderItems' => [
array_reverse($baseItems),
$baseItems,
];
}

public function invalidTableItemsProvider(): Generator
{
yield 'manifestNotExists' => [
null,
true,
'Manifest "table.csv.manifest" not found.',
];

yield 'manifestNotValidJson' => [
['test'],
false,
'Manifest "%s/table.csv.manifest" is not valid JSON.',
];

yield 'manifestMissingColumns' => [
['test'],
true,
'Manifest "%s/table.csv.manifest" is missing "columns" key.',
];
}
}
68 changes: 68 additions & 0 deletions tests/phpunit/WriterFactoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

namespace Keboola\DbWriter\Tests;

use Keboola\DbWriter\Exception\UserException;
use Keboola\DbWriter\WriterFactory;
use Keboola\DbWriterConfig\Config;
use Keboola\DbWriterConfig\Configuration\ActionConfigDefinition;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use Psr\Log\Test\TestLogger;

class WriterFactoryTest extends TestCase
{
public function testCreateWriterClass(): void
{
$config = new Config(
[
'action' => 'testConnection',
'parameters' => [
'data_dir' => '/data',
'writer_class' => 'Common',
'db' => [
'host' => (string) getenv('COMMON_DB_HOST'),
'port' => (int) getenv('COMMON_DB_PORT'),
'database' => (string) getenv('COMMON_DB_DATABASE'),
'user' => (string) getenv('COMMON_DB_USER'),
'#password' => (string) getenv('COMMON_DB_PASSWORD'),
],
],
],
new ActionConfigDefinition(),
);

$writerFactory = new WriterFactory($config);
$writer = $writerFactory->create(new TestLogger());

Assert::assertSame('Keboola\DbWriter\Writer\Common', get_class($writer));
}

public function testUnknownWriterClass(): void
{
$config = new Config(
[
'action' => 'testConnection',
'parameters' => [
'data_dir' => '/data',
'writer_class' => 'Unknown',
'db' => [
'host' => (string) getenv('COMMON_DB_HOST'),
'port' => (int) getenv('COMMON_DB_PORT'),
'database' => (string) getenv('COMMON_DB_DATABASE'),
'user' => (string) getenv('COMMON_DB_USER'),
'#password' => (string) getenv('COMMON_DB_PASSWORD'),
],
],
],
new ActionConfigDefinition(),
);

$writerFactory = new WriterFactory($config);
$this->expectException(UserException::class);
$this->expectExceptionMessage("Writer class 'Keboola\DbWriter\Writer\Unknown' doesn't exist");
$writerFactory->create(new TestLogger());
}
}
Loading

0 comments on commit 3652624

Please sign in to comment.