diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 2ec6f6e..de6a4ce 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -5,7 +5,9 @@ diff --git a/tests/Sikofitt/Tests/UserAgentTest.php b/tests/Sikofitt/Tests/UserAgentTest.php new file mode 100644 index 0000000..3a72f14 --- /dev/null +++ b/tests/Sikofitt/Tests/UserAgentTest.php @@ -0,0 +1,109 @@ +. + */ + +namespace Sikofitt\Tests; + +use PHPUnit\Framework\TestCase; +use Sikofitt\UserAgent\UserAgent; + +class UserAgentTest extends TestCase +{ + private $zts; + private $arch; + + public function setUp(): void + { + $this->zts = (bool)PHP_ZTS ? '-zts' : ''; + $this->arch = 9223372036854775807 === PHP_INT_MAX ? 'x86_64' : 'i386'; + + parent::setUp(); + } + + public function testExtendUserAgent(): void + { + $userAgent = new class extends UserAgent { + protected static $format = 'PHP/%d.%d.%d (%d)'; + protected static $params = [ + PHP_MAJOR_VERSION, + PHP_MINOR_VERSION, + PHP_RELEASE_VERSION, + PHP_VERSION_ID, + ]; + }; + + $expected = sprintf( + 'PHP/%d.%d.%d (%d)', + PHP_MAJOR_VERSION, + PHP_MINOR_VERSION, + PHP_RELEASE_VERSION, + PHP_VERSION_ID + ); + $actual = $userAgent::create(); + $this->assertSame($expected, $actual); + } + + public function testFailure(): void + { + $userAgent = new class extends UserAgent { + protected static $format = ''; + protected static $params = []; + }; + + $this->assertNotSame(UserAgent::create(), $userAgent::create()); + $this->assertNotSame(UserAgent::create(), ''); + } + + public function testDefaultUserAgent(): void + { + $format = 'PHP/%d.%d%s-%d (%s; %s %s) PHP/%s%s; %s (%s)'; + $params = [ + PHP_MAJOR_VERSION, + PHP_MINOR_VERSION, + $this->zts, + PHP_VERSION_ID, + 'sikofitt/user-agent', + PHP_OS_FAMILY, + $this->arch, + PHP_VERSION, + $this->zts, + $this->getGuzzleVersionString(), + 'https://packagist.org/sikofitt/user-agent', + ]; + $expected = sprintf($format, ...$params); + + $userAgent = UserAgent::create(); + $this->assertSame($expected, $userAgent); + } + + private function getGuzzleVersionString(): string + { + /** @noinspection ClassConstantCanBeUsedInspection */ + if (class_exists('GuzzleHttp\Client')) { + /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */ + $guzzleClient = new \GuzzleHttp\Client(); + $guzzleHeaders = $guzzleClient->getConfig('headers'); + $guzzleUserAgent = $guzzleHeaders['User-Agent']; + return trim(explode('php', strtolower($guzzleUserAgent))[0]); + } + + return ''; + } +}