|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Amp\Sql\Test; |
| 4 | + |
| 5 | +use Amp\Sql\SqlConfig; |
| 6 | +use PHPUnit\Framework\TestCase; |
| 7 | + |
| 8 | +class SqlConfigTest extends TestCase |
| 9 | +{ |
| 10 | + private function createConfigFromString(string $connectionString): SqlConfig |
| 11 | + { |
| 12 | + return new class($connectionString) extends SqlConfig { |
| 13 | + public function __construct(string $connectionString) |
| 14 | + { |
| 15 | + $parts = self::parseConnectionString($connectionString); |
| 16 | + |
| 17 | + parent::__construct( |
| 18 | + host: $parts["host"] ?? '', |
| 19 | + port: (int) ($parts["port"] ?? 0), |
| 20 | + user: $parts["user"] ?? "", |
| 21 | + password: $parts["password"] ?? "", |
| 22 | + database: $parts["db"] ?? "", |
| 23 | + ); |
| 24 | + } |
| 25 | + }; |
| 26 | + } |
| 27 | + |
| 28 | + public function testPortInHost(): void |
| 29 | + { |
| 30 | + $config = $this->createConfigFromString("host=localhost:5432 user=user database=test"); |
| 31 | + |
| 32 | + self::assertSame("localhost", $config->getHost()); |
| 33 | + self::assertSame(5432, $config->getPort()); |
| 34 | + self::assertSame("user", $config->getUser()); |
| 35 | + self::assertSame("", $config->getPassword()); |
| 36 | + self::assertSame("test", $config->getDatabase()); |
| 37 | + } |
| 38 | + |
| 39 | + public function testBasicSyntax(): void |
| 40 | + { |
| 41 | + $config = $this->createConfigFromString("host=localhost port=5432 user=user pass=test db=test"); |
| 42 | + |
| 43 | + self::assertSame("localhost", $config->getHost()); |
| 44 | + self::assertSame(5432, $config->getPort()); |
| 45 | + self::assertSame("user", $config->getUser()); |
| 46 | + self::assertSame("test", $config->getPassword()); |
| 47 | + self::assertSame("test", $config->getDatabase()); |
| 48 | + } |
| 49 | + |
| 50 | + public function testAlternativeSyntax(): void |
| 51 | + { |
| 52 | + $config = $this->createConfigFromString("host=localhost;port=3306;user=user;password=test;db=test"); |
| 53 | + |
| 54 | + self::assertSame("localhost", $config->getHost()); |
| 55 | + self::assertSame(3306, $config->getPort()); |
| 56 | + self::assertSame("user", $config->getUser()); |
| 57 | + self::assertSame("test", $config->getPassword()); |
| 58 | + self::assertSame("test", $config->getDatabase()); |
| 59 | + } |
| 60 | + |
| 61 | + public function testInvalidString(): void |
| 62 | + { |
| 63 | + $this->expectException(\ValueError::class); |
| 64 | + $this->expectExceptionMessage("Empty key name in connection string"); |
| 65 | + $this->createConfigFromString("invalid =connection string"); |
| 66 | + } |
| 67 | +} |
0 commit comments