Add new tests, remove redundant code

This commit is contained in:
crazywhalecc 2024-10-03 14:52:46 +08:00 committed by Jerry Ma
parent c800e3b93a
commit 732fa06abb
14 changed files with 2021 additions and 1050 deletions

View File

@ -11,6 +11,7 @@
"require": {
"php": ">= 8.1",
"ext-mbstring": "*",
"ext-zlib": "*",
"laravel/prompts": "^0.1.12",
"symfony/console": "^5.4 || ^6 || ^7",
"zhamao/logger": "^1.0"
@ -22,7 +23,7 @@
"humbug/box": "^4.5",
"nunomaduro/collision": "^7.8",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^10.3 || ^9"
"phpunit/phpunit": "^10.3"
},
"autoload": {
"psr-4": {

2473
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -418,30 +418,6 @@ abstract class BuilderBase
}
}
/**
* Check if all libs are downloaded.
* If not, throw exception.
*
* @throws RuntimeException
*/
protected function checkLibsSource(): void
{
$not_downloaded = [];
foreach ($this->libs as $lib) {
if (!file_exists($lib->getSourceDir())) {
$not_downloaded[] = $lib::NAME;
}
}
if ($not_downloaded !== []) {
throw new RuntimeException(
'"' . implode(', ', $not_downloaded) .
'" totally ' . count($not_downloaded) .
' source' . (count($not_downloaded) === 1 ? '' : 's') .
' not downloaded, maybe you need to "fetch" ' . (count($not_downloaded) === 1 ? 'it' : 'them') . ' first?'
);
}
}
/**
* Generate micro extension test php code.
*/

View File

@ -6,7 +6,6 @@ namespace SPC\builder\linux;
use SPC\builder\traits\UnixSystemUtilTrait;
use SPC\exception\RuntimeException;
use SPC\exception\WrongUsageException;
class SystemUtil
{
@ -83,52 +82,6 @@ class SystemUtil
};
}
/**
* @throws RuntimeException
* @throws WrongUsageException
* @throws WrongUsageException
*/
public static function getArchCFlags(string $cc, string $arch): string
{
if (php_uname('m') === $arch) {
return '';
}
return match (static::getCCType($cc)) {
'clang' => match ($arch) {
'x86_64' => '--target=x86_64-unknown-linux',
'arm64', 'aarch64' => '--target=arm64-unknown-linux',
default => throw new WrongUsageException('unsupported arch: ' . $arch),
},
'gcc' => '',
default => throw new WrongUsageException('cc compiler ' . $cc . ' is not supported'),
};
}
/**
* @throws RuntimeException
*/
public static function getTuneCFlags(string $arch): array
{
return match ($arch) {
'x86_64', 'arm64', 'aarch64' => [],
default => throw new RuntimeException('unsupported arch: ' . $arch),
};
}
public static function checkCCFlags(array $flags, string $cc): array
{
return array_filter($flags, fn ($flag) => static::checkCCFlag($flag, $cc));
}
public static function checkCCFlag(string $flag, string $cc): string
{
[$ret] = shell()->execWithResult("echo | {$cc} -E -x c - {$flag} 2>/dev/null");
if ($ret != 0) {
return '';
}
return $flag;
}
/**
* @throws RuntimeException
* @noinspection PhpUnused

View File

@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
namespace SPC\Tests\builder;
use PHPUnit\Framework\TestCase;
use SPC\builder\BuilderBase;
use SPC\builder\BuilderProvider;
use Symfony\Component\Console\Input\ArgvInput;
/**
* @internal
*/
class BuilderProviderTest extends TestCase
{
public static function setUpBeforeClass(): void
{
BuilderProvider::makeBuilderByInput(new ArgvInput());
BuilderProvider::getBuilder();
}
public function testMakeBuilderByInput(): void
{
$this->assertInstanceOf(BuilderBase::class, BuilderProvider::makeBuilderByInput(new ArgvInput()));
$this->assertInstanceOf(BuilderBase::class, BuilderProvider::getBuilder());
}
}

View File

@ -0,0 +1,248 @@
<?php
declare(strict_types=1);
namespace SPC\Tests\builder;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use SPC\builder\BuilderBase;
use SPC\builder\BuilderProvider;
use SPC\builder\Extension;
use SPC\builder\LibraryBase;
use SPC\exception\RuntimeException;
use SPC\exception\WrongUsageException;
use SPC\store\FileSystem;
use SPC\util\CustomExt;
use SPC\util\DependencyUtil;
use Symfony\Component\Console\Input\ArgvInput;
/**
* @internal
*/
class BuilderTest extends TestCase
{
private BuilderBase $builder;
public static function setUpBeforeClass(): void
{
BuilderProvider::makeBuilderByInput(new ArgvInput());
BuilderProvider::getBuilder();
}
public function setUp(): void
{
$this->builder = BuilderProvider::makeBuilderByInput(new ArgvInput());
[$extensions, $libs] = DependencyUtil::getExtsAndLibs(['mbregex']);
$this->builder->proveLibs($libs);
CustomExt::loadCustomExt();
foreach ($extensions as $extension) {
$class = CustomExt::getExtClass($extension);
$ext = new $class($extension, $this->builder);
$this->builder->addExt($ext);
}
foreach ($this->builder->getExts() as $ext) {
$ext->checkDependency();
}
}
public function testMakeBuilderByInput(): void
{
$this->assertInstanceOf(BuilderBase::class, BuilderProvider::makeBuilderByInput(new ArgvInput()));
$this->assertInstanceOf(BuilderBase::class, BuilderProvider::getBuilder());
}
public function testGetLibAndGetLibs()
{
$this->assertIsArray($this->builder->getLibs());
$this->assertInstanceOf(LibraryBase::class, $this->builder->getLib('onig'));
}
public function testGetExtAndGetExts()
{
$this->assertIsArray($this->builder->getExts());
$this->assertInstanceOf(Extension::class, $this->builder->getExt('mbregex'));
}
public function testHasCpp()
{
// mbregex doesn't have cpp
$this->assertFalse($this->builder->hasCpp());
}
public function testMakeExtensionArgs()
{
$this->assertStringContainsString('--enable-mbstring', $this->builder->makeExtensionArgs());
}
public function testIsLibsOnly()
{
// mbregex is not libs only
$this->assertFalse($this->builder->isLibsOnly());
}
public function testGetPHPVersionID()
{
if (file_exists(SOURCE_PATH . '/php-src/main/php_version.h')) {
$file = SOURCE_PATH . '/php-src/main/php_version.h';
$cnt = preg_match('/PHP_VERSION_ID (\d+)/', $file, $match);
if ($cnt !== 0) {
$this->assertEquals(intval($match[1]), $this->builder->getPHPVersionID());
} else {
$this->expectException(RuntimeException::class);
$this->builder->getPHPVersionID();
}
} else {
$this->expectException(WrongUsageException::class);
$this->builder->getPHPVersionID();
}
}
public function testGetPHPVersion()
{
if (file_exists(SOURCE_PATH . '/php-src/main/php_version.h')) {
$file = SOURCE_PATH . '/php-src/main/php_version.h';
$cnt = preg_match('/PHP_VERSION "(\d+\.\d+\.\d+)"/', $file, $match);
if ($cnt !== 0) {
$this->assertEquals($match[1], $this->builder->getPHPVersion());
} else {
$this->expectException(RuntimeException::class);
$this->builder->getPHPVersion();
}
} else {
$this->expectException(WrongUsageException::class);
$this->builder->getPHPVersion();
}
}
public function testGetPHPVersionFromArchive()
{
$lock = file_exists(DOWNLOAD_PATH . '/.lock.json') ? file_get_contents(DOWNLOAD_PATH . '/.lock.json') : false;
if ($lock === false) {
$this->assertFalse($this->builder->getPHPVersionFromArchive());
} else {
$lock = json_decode($lock, true);
$file = $lock['php-src']['filename'] ?? null;
if ($file === null) {
$this->assertFalse($this->builder->getPHPVersionFromArchive());
} else {
$cnt = preg_match('/php-(\d+\.\d+\.\d+)/', $file, $match);
if ($cnt !== 0) {
$this->assertEquals($match[1], $this->builder->getPHPVersionFromArchive());
} else {
$this->assertFalse($this->builder->getPHPVersionFromArchive());
}
}
}
}
public function testGetMicroVersion()
{
$file = FileSystem::convertPath(SOURCE_PATH . '/php-src/sapi/micro/php_micro.h');
if (!file_exists($file)) {
$this->assertFalse($this->builder->getMicroVersion());
} else {
$content = file_get_contents($file);
$ver = '';
preg_match('/#define PHP_MICRO_VER_MAJ (\d)/m', $content, $match);
$ver .= $match[1] . '.';
preg_match('/#define PHP_MICRO_VER_MIN (\d)/m', $content, $match);
$ver .= $match[1] . '.';
preg_match('/#define PHP_MICRO_VER_PAT (\d)/m', $content, $match);
$ver .= $match[1];
$this->assertEquals($ver, $this->builder->getMicroVersion());
}
}
public static function providerGetBuildTypeName(): array
{
return [
[BUILD_TARGET_CLI, 'cli'],
[BUILD_TARGET_FPM, 'fpm'],
[BUILD_TARGET_MICRO, 'micro'],
[BUILD_TARGET_EMBED, 'embed'],
[BUILD_TARGET_ALL, 'cli, micro, fpm, embed'],
[BUILD_TARGET_CLI | BUILD_TARGET_EMBED, 'cli, embed'],
];
}
#[DataProvider('providerGetBuildTypeName')]
public function testGetBuildTypeName(int $target, string $name): void
{
$this->assertEquals($name, $this->builder->getBuildTypeName($target));
}
public function testGetOption()
{
// we cannot assure the option exists, so just tests default value
$this->assertEquals('foo', $this->builder->getOption('bar', 'foo'));
}
public function testGetOptions()
{
$this->assertIsArray($this->builder->getOptions());
}
public function testSetOptionIfNotExist()
{
$this->assertEquals(null, $this->builder->getOption('bar'));
$this->builder->setOptionIfNotExist('bar', 'foo');
$this->assertEquals('foo', $this->builder->getOption('bar'));
}
public function testSetOption()
{
$this->assertEquals(null, $this->builder->getOption('bar'));
$this->builder->setOption('bar', 'foo');
$this->assertEquals('foo', $this->builder->getOption('bar'));
}
public function testGetEnvString()
{
$this->assertIsString($this->builder->getEnvString());
putenv('TEST_SPC_BUILDER=foo');
$this->assertStringContainsString('TEST_SPC_BUILDER=foo', $this->builder->getEnvString(['TEST_SPC_BUILDER']));
}
public function testValidateLibsAndExts()
{
$this->builder->validateLibsAndExts();
$this->assertTrue(true);
}
public static function providerEmitPatchPoint(): array
{
return [
['before-libs-extract'],
['after-libs-extract'],
['before-php-extract'],
['after-php-extract'],
['before-micro-extract'],
['after-micro-extract'],
['before-exts-extract'],
['after-exts-extract'],
['before-php-buildconf'],
['before-php-configure'],
['before-php-make'],
['before-sanity-check'],
];
}
#[DataProvider('providerEmitPatchPoint')]
public function testEmitPatchPoint(string $point)
{
$code = '<?php if (patch_point() === "' . $point . '") echo "GOOD:' . $point . '";';
// emulate patch point
$this->builder->setOption('with-added-patch', ['/tmp/patch-point.' . $point . '.php']);
FileSystem::writeFile('/tmp/patch-point.' . $point . '.php', $code);
$this->expectOutputString('GOOD:' . $point);
$this->builder->emitPatchPoint($point);
}
public function testEmitPatchPointNotExists()
{
$this->expectOutputRegex('/failed to run/');
$this->builder->setOption('with-added-patch', ['/tmp/patch-point.not_exsssists.php']);
$this->builder->emitPatchPoint('not-exists');
}
}

View File

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace SPC\Tests\builder\linux;
use PHPUnit\Framework\TestCase;
use SPC\builder\linux\SystemUtil;
/**
* @internal
*/
class SystemUtilTest extends TestCase
{
public static function setUpBeforeClass(): void
{
if (PHP_OS_FAMILY !== 'Linux') {
self::markTestIncomplete('This test is only for Linux');
}
}
public function testIsMuslDistAndGetOSRelease()
{
$release = SystemUtil::getOSRelease();
// we cannot ensure what is the current distro, just test the key exists
$this->assertArrayHasKey('dist', $release);
$this->assertArrayHasKey('ver', $release);
$this->assertTrue($release['dist'] === 'alpine' && SystemUtil::isMuslDist() || $release['dist'] !== 'alpine' && !SystemUtil::isMuslDist());
}
public function testFindStaticLib()
{
$this->assertIsArray(SystemUtil::findStaticLib('ld-linux-x86-64.so.2'));
}
public function testGetCpuCount()
{
$this->assertIsInt(SystemUtil::getCpuCount());
}
public function testFindHeader()
{
$this->assertIsArray(SystemUtil::findHeader('elf.h'));
}
public function testGetCrossCompilePrefix()
{
$this->assertIsString(SystemUtil::getCrossCompilePrefix('gcc', 'x86_64'));
}
public function testGetCCType()
{
$this->assertEquals('gcc', SystemUtil::getCCType('xjfoiewjfoewof-gcc'));
}
public function testGetSupportedDistros()
{
$this->assertIsArray(SystemUtil::getSupportedDistros());
}
public function testFindHeaders()
{
$this->assertIsArray(SystemUtil::findHeaders(['elf.h']));
}
public function testFindStaticLibs()
{
$this->assertIsArray(SystemUtil::findStaticLibs(['ld-linux-x86-64.so.2']));
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace SPC\Tests\builder\macos;
use PHPUnit\Framework\TestCase;
use SPC\builder\macos\SystemUtil;
/**
* @internal
*/
class SystemUtilTest extends TestCase
{
public static function setUpBeforeClass(): void
{
if (PHP_OS_FAMILY !== 'Darwin') {
self::markTestIncomplete('This test is only for macOS');
}
}
public function testGetCpuCount()
{
$this->assertIsInt(SystemUtil::getCpuCount());
}
public function testGetArchCFlags()
{
$this->assertEquals('--target=x86_64-apple-darwin', SystemUtil::getArchCFlags('x86_64'));
}
}

View File

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace SPC\Tests\builder\unix;
use PHPUnit\Framework\TestCase;
use SPC\builder\freebsd\SystemUtil as FreebsdSystemUtil;
use SPC\builder\linux\SystemUtil as LinuxSystemUtil;
use SPC\builder\macos\SystemUtil as MacosSystemUtil;
use SPC\exception\FileSystemException;
/**
* @internal
*/
class UnixSystemUtilTest extends TestCase
{
private FreebsdSystemUtil|LinuxSystemUtil|MacosSystemUtil $util;
public function setUp(): void
{
$util_class = match (PHP_OS_FAMILY) {
'Linux' => 'SPC\builder\linux\SystemUtil',
'Darwin' => 'SPC\builder\macos\SystemUtil',
'FreeBSD' => 'SPC\builder\freebsd\SystemUtil',
default => null,
};
if ($util_class === null) {
self::markTestIncomplete('This test is only for Unix');
}
$this->util = new $util_class();
}
/**
* @throws FileSystemException
*/
public function testMakeCmakeToolchainFile()
{
$str = $this->util->makeCmakeToolchainFile(PHP_OS_FAMILY, 'x86_64', '');
$this->assertIsString($str);
}
public function testFindCommand()
{
$this->assertIsString($this->util->findCommand('bash'));
}
public function testMakeEnvVarString()
{
$this->assertEquals("PATH='/usr/bin' PKG_CONFIG='/usr/bin/pkg-config'", $this->util->makeEnvVarString(['PATH' => '/usr/bin', 'PKG_CONFIG' => '/usr/bin/pkg-config']));
}
}

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace SPC\Tests\store;
use PHPUnit\Framework\TestCase;
use SPC\store\CurlHook;
/**
* @internal
*/
class CurlHookTest extends TestCase
{
public function testSetupGithubToken()
{
$header = [];
CurlHook::setupGithubToken('GET', 'https://example.com', $header);
$this->assertEmpty($header);
putenv('GITHUB_TOKEN=token');
CurlHook::setupGithubToken('GET', 'https://example.com', $header);
$this->assertEquals(['Authorization: Bearer token'], $header);
}
}

View File

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace SPC\Tests\store;
use PHPUnit\Framework\TestCase;
use SPC\store\Downloader;
/**
* @internal
* TODO: Test all methods
*/
class DownloaderTest extends TestCase
{
public function testGetLatestGithubTarball()
{
$this->assertEquals(
'https://api.github.com/repos/AOMediaCodec/libavif/tarball/v1.1.1',
Downloader::getLatestGithubTarball('libavif', [
'type' => 'ghtar',
'repo' => 'AOMediaCodec/libavif',
])[0]
);
}
public function testDownloadGit() {}
public function testDownloadFile() {}
public function testLockSource() {}
public function testGetLatestBitbucketTag() {}
public function testGetLatestGithubRelease() {}
public function testCurlExec() {}
public function testCurlDown() {}
public function testDownloadSource() {}
public function testGetFromFileList() {}
public function testDownloadPackage() {}
}

View File

@ -3,3 +3,4 @@
declare(strict_types=1);
require_once __DIR__ . '/../src/globals/internal-env.php';
require_once __DIR__ . '/mock/SPC_store.php';

24
tests/mock/SPC_store.php Normal file
View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
// mock global functions
namespace SPC\store;
function f_exec(string $command, mixed &$output, mixed &$result_code): bool
{
if (str_contains($command, 'https://api.github.com/repos/AOMediaCodec/libavif/releases')) {
$output = explode("\n", gzdecode(file_get_contents(__DIR__ . '/../assets/github_api_AOMediaCodec_libavif_releases.json.gz')));
$result_code = 0;
return true;
}
if (str_contains($command, 'https://api.github.com/repos/AOMediaCodec/libavif/tarball/v1.1.1')) {
$output = explode("\n", "HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=AOMediaCodec-libavif-v1.1.1-0-gbb24db0.tar.gz\r\n\r\n");
$result_code = 0;
return true;
}
$result_code = -2;
$output = null;
return false;
}