Browse Source

add more tests

crazywhalecc 1 year ago
parent
commit
05c6dc6dab

+ 2 - 2
src/SPC/store/FileSystem.php

@@ -14,13 +14,13 @@ class FileSystem
     /**
      * @throws FileSystemException
      */
-    public static function loadConfigArray(string $config): array
+    public static function loadConfigArray(string $config, ?string $config_dir = null): array
     {
         $whitelist = ['ext', 'lib', 'source'];
         if (!in_array($config, $whitelist)) {
             throw new FileSystemException('Reading ' . $config . '.json is not allowed');
         }
-        $tries = [
+        $tries = $config_dir !== null ? [FileSystem::convertPath($config_dir . '/' . $config . '.json')] : [
             WORKING_DIR . '/config/' . $config . '.json',
             ROOT_DIR . '/config/' . $config . '.json',
         ];

+ 1 - 1
src/globals/test-extensions.php

@@ -27,7 +27,7 @@ $with_libs = match (PHP_OS_FAMILY) {
 // You can use `common`, `bulk`, `minimal` or `none`.
 // note: combination is only available for *nix platform. Windows must use `none` combination
 $base_combination = match (PHP_OS_FAMILY) {
-    'Linux', 'Darwin' => 'bulk',
+    'Linux', 'Darwin' => 'minimal',
     'Windows' => 'none',
 };
 

+ 101 - 0
tests/SPC/globals/GlobalFunctionsTest.php

@@ -0,0 +1,101 @@
+<?php
+
+declare(strict_types=1);
+
+namespace SPC\Tests\globals;
+
+use PHPUnit\Framework\TestCase;
+use Psr\Log\LogLevel;
+use SPC\exception\RuntimeException;
+use SPC\exception\WrongUsageException;
+use ZM\Logger\ConsoleLogger;
+
+/**
+ * @internal
+ */
+class GlobalFunctionsTest extends TestCase
+{
+    private static $logger_cache;
+
+    public static function setUpBeforeClass(): void
+    {
+        global $ob_logger;
+        self::$logger_cache = $ob_logger;
+        $ob_logger = new ConsoleLogger(LogLevel::ALERT);
+    }
+
+    public static function tearDownAfterClass(): void
+    {
+        global $ob_logger;
+        $ob_logger = self::$logger_cache;
+    }
+
+    public function testIsAssocArray(): void
+    {
+        $this->assertTrue(is_assoc_array(['a' => 1, 'b' => 2]));
+        $this->assertFalse(is_assoc_array([1, 2, 3]));
+    }
+
+    public function testLogger(): void
+    {
+        $this->assertInstanceOf('Psr\Log\LoggerInterface', logger());
+    }
+
+    /**
+     * @throws WrongUsageException
+     */
+    public function testArch2Gnu(): void
+    {
+        $this->assertEquals('x86_64', arch2gnu('x86_64'));
+        $this->assertEquals('x86_64', arch2gnu('x64'));
+        $this->assertEquals('x86_64', arch2gnu('amd64'));
+        $this->assertEquals('aarch64', arch2gnu('arm64'));
+        $this->assertEquals('aarch64', arch2gnu('aarch64'));
+        $this->expectException('SPC\exception\WrongUsageException');
+        arch2gnu('armv7');
+    }
+
+    public function testQuote(): void
+    {
+        $this->assertEquals('"hello"', quote('hello'));
+        $this->assertEquals("'hello'", quote('hello', "'"));
+    }
+
+    /**
+     * @throws RuntimeException
+     */
+    public function testFPassthru(): void
+    {
+        if (PHP_OS_FAMILY === 'Windows') {
+            $this->markTestSkipped('Windows not support f_passthru');
+        }
+        $this->assertEquals(null, f_passthru('echo ""'));
+        $this->expectException('SPC\exception\RuntimeException');
+        f_passthru('false');
+    }
+
+    public function testFPutenv(): void
+    {
+        $this->assertTrue(f_putenv('SPC_TEST_ENV=1'));
+        $this->assertEquals('1', getenv('SPC_TEST_ENV'));
+    }
+
+    public function testShell(): void
+    {
+        if (PHP_OS_FAMILY === 'Windows') {
+            $this->markTestSkipped('Windows not support shell');
+        }
+        $shell = shell();
+        $this->assertInstanceOf('SPC\util\UnixShell', $shell);
+        $this->assertInstanceOf('SPC\util\UnixShell', $shell->cd('/'));
+        $this->assertInstanceOf('SPC\util\UnixShell', $shell->exec('echo ""'));
+        $this->assertInstanceOf('SPC\util\UnixShell', $shell->setEnv(['SPC_TEST_ENV' => '1']));
+
+        [$code, $out] = $shell->execWithResult('echo "_"');
+        $this->assertEquals(0, $code);
+        $this->assertEquals('_', implode('', $out));
+
+        $this->expectException('SPC\exception\RuntimeException');
+        $shell->exec('false');
+    }
+}

+ 96 - 0
tests/SPC/store/ConfigTest.php

@@ -0,0 +1,96 @@
+<?php
+
+declare(strict_types=1);
+
+namespace SPC\Tests\store;
+
+use PHPUnit\Framework\TestCase;
+use SPC\exception\FileSystemException;
+use SPC\exception\WrongUsageException;
+use SPC\store\Config;
+use SPC\store\FileSystem;
+
+/**
+ * @internal
+ */
+class ConfigTest extends TestCase
+{
+    /**
+     * @throws FileSystemException
+     */
+    public static function setUpBeforeClass(): void
+    {
+        $testdir = WORKING_DIR . '/.configtest';
+        FileSystem::createDir($testdir);
+        FileSystem::writeFile($testdir . '/lib.json', file_get_contents(ROOT_DIR . '/config/lib.json'));
+        FileSystem::writeFile($testdir . '/ext.json', file_get_contents(ROOT_DIR . '/config/ext.json'));
+        FileSystem::writeFile($testdir . '/source.json', file_get_contents(ROOT_DIR . '/config/source.json'));
+        FileSystem::loadConfigArray('lib', $testdir);
+        FileSystem::loadConfigArray('ext', $testdir);
+        FileSystem::loadConfigArray('source', $testdir);
+    }
+
+    /**
+     * @throws FileSystemException
+     */
+    public static function tearDownAfterClass(): void
+    {
+        FileSystem::removeDir(WORKING_DIR . '/.configtest');
+    }
+
+    /**
+     * @throws FileSystemException
+     */
+    public function testGetExts()
+    {
+        $this->assertTrue(is_assoc_array(Config::getExts()));
+    }
+
+    /**
+     * @throws FileSystemException
+     * @throws WrongUsageException
+     */
+    public function testGetLib()
+    {
+        $this->assertIsArray(Config::getLib('zlib'));
+        match (PHP_OS_FAMILY) {
+            'FreeBSD', 'Darwin', 'Linux' => $this->assertStringEndsWith('.a', Config::getLib('zlib', 'static-libs', [])[0]),
+            'Windows' => $this->assertStringEndsWith('.lib', Config::getLib('zlib', 'static-libs', [])[0]),
+            default => null,
+        };
+    }
+
+    /**
+     * @throws WrongUsageException
+     * @throws FileSystemException
+     */
+    public function testGetExt()
+    {
+        $this->assertIsArray(Config::getExt('bcmath'));
+        $this->assertEquals('builtin', Config::getExt('bcmath', 'type'));
+    }
+
+    /**
+     * @throws FileSystemException
+     */
+    public function testGetSources()
+    {
+        $this->assertTrue(is_assoc_array(Config::getSources()));
+    }
+
+    /**
+     * @throws FileSystemException
+     */
+    public function testGetSource()
+    {
+        $this->assertIsArray(Config::getSource('php-src'));
+    }
+
+    /**
+     * @throws FileSystemException
+     */
+    public function testGetLibs()
+    {
+        $this->assertTrue(is_assoc_array(Config::getLibs()));
+    }
+}

+ 172 - 0
tests/SPC/util/ConfigValidatorTest.php

@@ -0,0 +1,172 @@
+<?php
+
+declare(strict_types=1);
+
+namespace SPC\Tests\util;
+
+use PHPUnit\Framework\TestCase;
+use SPC\exception\ValidationException;
+use SPC\util\ConfigValidator;
+
+/**
+ * @internal
+ */
+class ConfigValidatorTest extends TestCase
+{
+    public function testValidateSourceGood(): void
+    {
+        $good_source = [
+            'source1' => [
+                'type' => 'filelist',
+                'url' => 'https://example.com',
+                'regex' => '.*',
+            ],
+            'source2' => [
+                'type' => 'git',
+                'url' => 'https://example.com',
+                'rev' => 'master',
+            ],
+            'source3' => [
+                'type' => 'ghtagtar',
+                'repo' => 'aaaa/bbbb',
+            ],
+            'source4' => [
+                'type' => 'ghtar',
+                'repo' => 'aaa/bbb',
+                'path' => 'path/to/dir',
+            ],
+            'source5' => [
+                'type' => 'ghrel',
+                'repo' => 'aaa/bbb',
+                'match' => '.*',
+            ],
+            'source6' => [
+                'type' => 'url',
+                'url' => 'https://example.com',
+            ],
+        ];
+        try {
+            ConfigValidator::validateSource($good_source);
+            $this->assertTrue(true);
+        } catch (ValidationException $e) {
+            $this->fail($e->getMessage());
+        }
+    }
+
+    public function testValidateSourceBad(): void
+    {
+        $bad_source = [
+            'source1' => [
+                'type' => 'filelist',
+                'url' => 'https://example.com',
+                // no regex
+            ],
+            'source2' => [
+                'type' => 'git',
+                'url' => true, // not string
+                'rev' => 'master',
+            ],
+            'source3' => [
+                'type' => 'ghtagtar',
+                'url' => 'aaaa/bbbb', // not repo
+            ],
+            'source4' => [
+                'type' => 'ghtar',
+                'repo' => 'aaa/bbb',
+                'path' => true, // not string
+            ],
+            'source5' => [
+                'type' => 'ghrel',
+                'repo' => 'aaa/bbb',
+                'match' => 1, // not string
+            ],
+            'source6' => [
+                'type' => 'url', // no url
+            ],
+        ];
+        foreach ($bad_source as $name => $src) {
+            try {
+                ConfigValidator::validateSource([$name => $src]);
+                $this->fail("should throw ValidationException for source {$name}");
+            } catch (ValidationException) {
+                $this->assertTrue(true);
+            }
+        }
+    }
+
+    public function testValidateLibsGood(): void
+    {
+        $good_libs = [
+            'lib1' => [
+                'source' => 'source1',
+            ],
+            'lib2' => [
+                'source' => 'source2',
+                'lib-depends' => [
+                    'lib1',
+                ],
+            ],
+            'lib3' => [
+                'source' => 'source3',
+                'lib-suggests' => [
+                    'lib1',
+                ],
+            ],
+        ];
+        try {
+            ConfigValidator::validateLibs($good_libs, ['source1' => [], 'source2' => [], 'source3' => []]);
+            $this->assertTrue(true);
+        } catch (ValidationException $e) {
+            $this->fail($e->getMessage());
+        }
+    }
+
+    public function testValidateLibsBad(): void
+    {
+        // lib.json is broken
+        try {
+            ConfigValidator::validateLibs('not array');
+            $this->fail('should throw ValidationException');
+        } catch (ValidationException) {
+            $this->assertTrue(true);
+        }
+        // lib source not exists
+        try {
+            ConfigValidator::validateLibs(['lib1' => ['source' => 'source3']], ['source1' => [], 'source2' => []]);
+            $this->fail('should throw ValidationException');
+        } catch (ValidationException) {
+            $this->assertTrue(true);
+        }
+        // source must be string
+        try {
+            ConfigValidator::validateLibs(['lib1' => ['source' => true]], ['source1' => [], 'source2' => []]);
+            $this->fail('should throw ValidationException');
+        } catch (ValidationException) {
+            $this->assertTrue(true);
+        }
+        // lib-depends must be list
+        try {
+            ConfigValidator::validateLibs(['lib1' => ['source' => 'source1', 'lib-depends' => ['a' => 'not list']]], ['source1' => [], 'source2' => []]);
+            $this->fail('should throw ValidationException');
+        } catch (ValidationException) {
+            $this->assertTrue(true);
+        }
+        // lib-suggests must be list
+        try {
+            ConfigValidator::validateLibs(['lib1' => ['source' => 'source1', 'lib-suggests' => ['a' => 'not list']]], ['source1' => [], 'source2' => []]);
+            $this->fail('should throw ValidationException');
+        } catch (ValidationException) {
+            $this->assertTrue(true);
+        }
+    }
+
+    /**
+     * @throws ValidationException
+     */
+    public function testValidateExts(): void
+    {
+        ConfigValidator::validateExts([]);
+        $this->expectException(ValidationException::class);
+        ConfigValidator::validateExts(null);
+    }
+}

+ 7 - 1
tests/SPC/util/LicenseDumperTest.php

@@ -13,7 +13,13 @@ use SPC\util\LicenseDumper;
  */
 final class LicenseDumperTest extends TestCase
 {
-    private const DIRECTORY = '../../var/license-dump';
+    private const DIRECTORY = __DIR__ . '/../../var/license-dump';
+
+    public static function tearDownAfterClass(): void
+    {
+        @rmdir(self::DIRECTORY);
+        @rmdir(dirname(self::DIRECTORY));
+    }
 
     protected function setUp(): void
     {