Skip to content

Commit

Permalink
Add PostgreSqlContainer
Browse files Browse the repository at this point in the history
  • Loading branch information
flavioheleno committed Mar 18, 2024
1 parent 3d11055 commit e4c8c72
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/Module/PostgreSql/PostgreSqlContainer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace Testcontainers\Module\PostgreSql;

use PDO;
use Testcontainers\GenericContainer;

final class PostgreSqlContainer extends GenericContainer
{
public function __construct(
string $image = 'postgres',
public readonly string $username = 'test',
public readonly string $password = 'test',
public readonly string $database = 'test',
) {
parent::__construct($image);

$this
->withExposedPorts('5432/tcp')
->withEnv([
"POSTGRES_USER={$this->username}",
"POSTGRES_PASSWORD={$this->password}",
"POSTGRES_DB={$this->database}",
]);
}

public function getDsn(): string
{
return "pgsql:host={$this->getHost()};port={$this->getFirstMappedPort()};dbname={$this->database}";
}

public function createPdo(): PDO
{
return new PDO($this->getDsn(), $this->username, $this->password);
}

public function start(int $wait = 15): self
{
return parent::start($wait); // TODO: Properly wait for PostgreSQL to be ready
}
}
50 changes: 50 additions & 0 deletions tests/Module/PostgreSqlContainerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

declare(strict_types=1);

namespace Test\Testcontainers\Module;

use PHPUnit\Framework\TestCase;
use Testcontainers\Module\PostgreSql\PostgreSqlContainer;

/**
* @internal
*/
final class PostgreSqlContainerTest extends TestCase
{
private static PostgreSqlContainer $container;

public static function setUpBeforeClass(): void
{
if (extension_loaded('pdo_pgsql') === false) {
self::markTestSkipped('The pdo_pgsql extension is not installed/enabled.');

return;
}

self::$container = new PostgreSqlContainer();
self::$container->start();
}

protected function tearDown(): void
{
self::$container->stop();
}

public function testCRUD(): void
{
$pdo = self::$container->createPdo();

self::assertNotFalse($pdo->exec('CREATE TABLE testcontainers (foo INT)'));
self::assertNotFalse($pdo->exec('INSERT INTO testcontainers (foo) VALUES (1)'));

$stmt = $pdo->query('SELECT foo FROM testcontainers');
self::assertSame(1, $stmt->fetchColumn());

self::assertNotFalse($pdo->exec('UPDATE testcontainers SET foo = 2 WHERE foo = 1'));
$stmt = $pdo->query('SELECT foo FROM testcontainers');
self::assertSame(2, $stmt->fetchColumn());

self::assertNotFalse($pdo->exec('DELETE FROM testcontainers'));
}
}

0 comments on commit e4c8c72

Please sign in to comment.