first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

View File

@@ -0,0 +1,602 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Command;
use Drupal\BuildTests\QuickStart\QuickStartTestBase;
use Drupal\Core\Command\GenerateTheme;
use Drupal\Core\Serialization\Yaml;
use Drupal\sqlite\Driver\Database\sqlite\Install\Tasks;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Console\Tester\Constraint\CommandIsSuccessful;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
/**
* Tests the generate-theme commands.
*
* @requires extension pdo_sqlite
*
* @group Command
*/
class GenerateThemeTest extends QuickStartTestBase {
/**
* The PHP executable path.
*
* @var string
*/
protected $php;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
$sqlite = (new \PDO('sqlite::memory:'))->query('select sqlite_version()')->fetch()[0];
if (version_compare($sqlite, Tasks::SQLITE_MINIMUM_VERSION) < 0) {
$this->markTestSkipped();
}
parent::setUp();
$php_executable_finder = new PhpExecutableFinder();
$this->php = $php_executable_finder->find();
$this->copyCodebase();
$this->executeCommand('COMPOSER_DISCARD_CHANGES=true composer install --no-dev --no-interaction');
chdir($this->getWorkingPath());
}
/**
* Generates PHP process to generate a theme from core's starterkit theme.
*
* @return \Symfony\Component\Process\Process
* The PHP process
*/
private function generateThemeFromStarterkit($env = NULL) : Process {
$install_command = [
$this->php,
'core/scripts/drupal',
'generate-theme',
'test_custom_theme',
'--name="Test custom starterkit theme"',
'--description="Custom theme generated from a starterkit theme"',
];
$process = new Process($install_command, NULL, $env);
$process->setTimeout(60);
return $process;
}
/**
* Asserts the theme exists. Returns the parsed *.info.yml file.
*
* @param string $theme_path_relative
* The core-relative path to the theme.
*
* @return array
* The parsed *.info.yml file.
*/
private function assertThemeExists(string $theme_path_relative): array {
$theme_path_absolute = $this->getWorkspaceDirectory() . "/$theme_path_relative";
$theme_name = basename($theme_path_relative);
$info_yml_filename = "$theme_name.info.yml";
$this->assertFileExists($theme_path_absolute . '/' . $info_yml_filename);
$info = Yaml::decode(file_get_contents($theme_path_absolute . '/' . $info_yml_filename));
return $info;
}
/**
* Tests the generate-theme command.
*/
public function test(): void {
// Do not rely on \Drupal::VERSION: change the version to a concrete version
// number, to simulate using a tagged core release.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
$info['version'] = '9.4.0';
file_put_contents($starterkit_info_yml, Yaml::encode($info));
$process = $this->generateThemeFromStarterkit();
$result = $process->run();
$this->assertStringContainsString('Theme generated successfully to themes/test_custom_theme', trim($process->getOutput()), $process->getErrorOutput());
$this->assertSame(0, $result);
$theme_path_relative = 'themes/test_custom_theme';
$info = $this->assertThemeExists($theme_path_relative);
self::assertArrayNotHasKey('hidden', $info);
self::assertArrayHasKey('generator', $info);
self::assertEquals('starterkit_theme:9.4.0', $info['generator']);
// Confirm readme is rewritten.
$readme_file = $this->getWorkspaceDirectory() . "/$theme_path_relative/README.md";
$this->assertSame('"Test custom starterkit theme" theme, generated from starterkit_theme. Additional information on generating themes can be found in the [Starterkit documentation](https://www.drupal.org/docs/core-modules-and-themes/core-themes/starterkit-theme).', file_get_contents($readme_file));
// Ensure that the generated theme can be installed.
$this->installQuickStart('minimal');
$this->formLogin($this->adminUsername, $this->adminPassword);
$this->visit('/admin/appearance');
$this->getMink()->assertSession()->pageTextContains('Test custom starterkit');
$this->getMink()->assertSession()->pageTextContains('Custom theme generated from a starterkit theme');
$this->getMink()->getSession()->getPage()->clickLink('Install "Test custom starterkit theme" theme');
$this->getMink()->assertSession()->pageTextContains('The "Test custom starterkit theme" theme has been installed.');
// Ensure that a new theme cannot be generated when the destination
// directory already exists.
$theme_path_absolute = $this->getWorkspaceDirectory() . "/$theme_path_relative";
$this->assertFileExists($theme_path_absolute . '/test_custom_theme.theme');
unlink($theme_path_absolute . '/test_custom_theme.theme');
$process = $this->generateThemeFromStarterkit();
$result = $process->run();
$this->assertStringContainsString('Theme could not be generated because the destination directory', $process->getErrorOutput());
$this->assertStringContainsString($theme_path_relative, $process->getErrorOutput());
$this->assertSame(1, $result);
$this->assertFileDoesNotExist($theme_path_absolute . '/test_custom_theme.theme');
}
/**
* Tests generating a theme from another Starterkit enabled theme.
*/
public function testGeneratingFromAnotherTheme(): void {
// Do not rely on \Drupal::VERSION: change the version to a concrete version
// number, to simulate using a tagged core release.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
$info['version'] = '9.4.0';
file_put_contents($starterkit_info_yml, Yaml::encode($info));
$process = $this->generateThemeFromStarterkit();
$exit_code = $process->run();
$this->assertStringContainsString('Theme generated successfully to themes/test_custom_theme', trim($process->getOutput()), $process->getErrorOutput());
$this->assertSame(0, $exit_code);
file_put_contents($this->getWorkspaceDirectory() . '/themes/test_custom_theme/test_custom_theme.starterkit.yml', <<<YAML
delete: []
no_edit: []
no_rename: []
info:
version: 1.0.0
YAML
);
$install_command = [
$this->php,
'core/scripts/drupal',
'generate-theme',
'generated_from_another_theme',
'--name="Generated from another theme"',
'--description="Custom theme generated from a theme other than starterkit_theme"',
'--starterkit=test_custom_theme',
];
$process = new Process($install_command);
$exit_code = $process->run();
$this->assertStringContainsString('Theme generated successfully to themes/generated_from_another_theme', trim($process->getOutput()), $process->getErrorOutput());
$this->assertSame(0, $exit_code);
// Confirm new .theme file.
$dot_theme_file = $this->getWorkspaceDirectory() . '/themes/generated_from_another_theme/generated_from_another_theme.theme';
$this->assertStringContainsString('function generated_from_another_theme_preprocess_image_widget(array &$variables) {', file_get_contents($dot_theme_file));
}
/**
* Tests the generate-theme command on a dev snapshot of Drupal core.
*/
public function testDevSnapshot(): void {
// Do not rely on \Drupal::VERSION: change the version to a development
// snapshot version number, to simulate using a branch snapshot of core.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
$info['version'] = '9.4.0-dev';
file_put_contents($starterkit_info_yml, Yaml::encode($info));
$process = $this->generateThemeFromStarterkit();
$result = $process->run();
$this->assertStringContainsString('Theme generated successfully to themes/test_custom_theme', trim($process->getOutput()), $process->getErrorOutput());
$this->assertSame(0, $result);
$theme_path_relative = 'themes/test_custom_theme';
$info = $this->assertThemeExists($theme_path_relative);
self::assertArrayNotHasKey('hidden', $info);
self::assertArrayHasKey('generator', $info);
self::assertMatchesRegularExpression('/^starterkit_theme\:9.4.0-dev#[0-9a-f]+$/', $info['generator']);
}
/**
* Tests the generate-theme command on a theme with a release version number.
*/
public function testContribStarterkit(): void {
// Change the version to a concrete version number, to simulate using a
// contrib theme as the starterkit.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
$info['version'] = '1.20';
file_put_contents($starterkit_info_yml, Yaml::encode($info));
$process = $this->generateThemeFromStarterkit();
$result = $process->run();
$this->assertStringContainsString('Theme generated successfully to themes/test_custom_theme', trim($process->getOutput()), $process->getErrorOutput());
$this->assertSame(0, $result);
$info = $this->assertThemeExists('themes/test_custom_theme');
self::assertArrayNotHasKey('hidden', $info);
self::assertArrayHasKey('generator', $info);
self::assertEquals('starterkit_theme:1.20', $info['generator']);
}
/**
* Tests the generate-theme command on a theme with a dev version number.
*/
public function testContribStarterkitDevSnapshot(): void {
// Change the version to a development snapshot version number, to simulate
// using a contrib theme as the starterkit.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
$info['core_version_requirement'] = '*';
$info['version'] = '7.x-dev';
file_put_contents($starterkit_info_yml, Yaml::encode($info));
// Avoid the core git commit from being considered the source theme's: move
// it out of core.
Process::fromShellCommandline('mv core/themes/starterkit_theme themes/', $this->getWorkspaceDirectory())->run();
$process = $this->generateThemeFromStarterkit();
$result = $process->run();
$this->assertStringContainsString("The source theme starterkit_theme has a development version number (7.x-dev). Because it is not a git checkout, a specific commit could not be identified. This makes tracking changes in the source theme difficult. Are you sure you want to continue? (yes/no) [yes]:\n > Theme generated successfully to themes/test_custom_theme", trim($process->getOutput()), $process->getErrorOutput());
$this->assertSame(0, $result);
$info = $this->assertThemeExists('themes/test_custom_theme');
self::assertArrayNotHasKey('hidden', $info);
self::assertArrayHasKey('generator', $info);
self::assertEquals('starterkit_theme:7.x-dev#unknown-commit', $info['generator']);
}
/**
* Tests the generate-theme command on a theme with a dev version without git.
*/
public function testContribStarterkitDevSnapshotWithGitNotInstalled(): void {
// Change the version to a development snapshot version number, to simulate
// using a contrib theme as the starterkit.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
$info['core_version_requirement'] = '*';
$info['version'] = '7.x-dev';
file_put_contents($starterkit_info_yml, Yaml::encode($info));
// Avoid the core git commit from being considered the source theme's: move
// it out of core.
Process::fromShellCommandline('mv core/themes/starterkit_theme themes/', $this->getWorkspaceDirectory())->run();
// Confirm that 'git' is available.
$output = [];
exec('git --help', $output, $status);
$this->assertEquals(0, $status);
// Modify our $PATH so that it begins with a path that contains an
// executable script named 'git' that always exits with 127, as if git were
// not found. Note that we run our tests using process isolation, so we do
// not need to restore the PATH when we are done.
$unavailableGitPath = $this->getWorkspaceDirectory() . '/bin';
mkdir($unavailableGitPath);
$bash = <<<SH
#!/bin/bash
exit 127
SH;
file_put_contents($unavailableGitPath . '/git', $bash);
chmod($unavailableGitPath . '/git', 0755);
// Confirm that 'git' is no longer available.
$env = [
'PATH' => $unavailableGitPath . ':' . getenv('PATH'),
'COLUMNS' => 80,
];
$process = new Process([
'git',
'--help',
], NULL, $env);
$process->run();
$this->assertEquals(127, $process->getExitCode(), 'Fake git used by process.');
$process = $this->generateThemeFromStarterkit($env);
$result = $process->run();
$this->assertEquals("[ERROR] The source theme starterkit_theme has a development version number \n (7.x-dev). Determining a specific commit is not possible because git is\n not installed. Either install git or use a tagged release to generate a\n theme.", trim($process->getErrorOutput()), $process->getErrorOutput());
$this->assertSame(1, $result);
$this->assertFileDoesNotExist($this->getWorkspaceDirectory() . "/themes/test_custom_theme");
}
/**
* Tests the generate-theme command on a theme without a version number.
*/
public function testCustomStarterkit(): void {
// Omit the version, to simulate using a custom theme as the starterkit.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
unset($info['version']);
file_put_contents($starterkit_info_yml, Yaml::encode($info));
$process = $this->generateThemeFromStarterkit();
$result = $process->run();
$this->assertStringContainsString("The source theme starterkit_theme does not have a version specified. This makes tracking changes in the source theme difficult. Are you sure you want to continue? (yes/no) [yes]:\n > Theme generated successfully to themes/test_custom_theme", trim($process->getOutput()), $process->getErrorOutput());
$this->assertSame(0, $result);
$info = $this->assertThemeExists('themes/test_custom_theme');
self::assertArrayNotHasKey('hidden', $info);
self::assertArrayHasKey('generator', $info);
self::assertEquals('starterkit_theme:unknown-version', $info['generator']);
}
/**
* Tests themes that do not exist return an error.
*/
public function testThemeDoesNotExist(): void {
$install_command = [
$this->php,
'core/scripts/drupal',
'generate-theme',
'test_custom_theme',
'--name="Test custom starterkit theme"',
'--description="Custom theme generated from a starterkit theme"',
'--starterkit',
'foobar',
];
$process = new Process($install_command, NULL);
$process->setTimeout(60);
$result = $process->run();
$this->assertStringContainsString('Theme source theme foobar cannot be found.', trim($process->getErrorOutput()));
$this->assertSame(1, $result);
}
/**
* Tests that only themes with `starterkit` flag can be used.
*/
public function testStarterKitFlag(): void {
// Explicitly not a starter theme.
$install_command = [
$this->php,
'core/scripts/drupal',
'generate-theme',
'test_custom_theme',
'--name="Test custom starterkit theme"',
'--description="Custom theme generated from a starterkit theme"',
'--starterkit',
'stark',
];
$process = new Process($install_command, NULL);
$process->setTimeout(60);
$result = $process->run();
$this->assertStringContainsString('Theme source theme stark is not a valid starter kit.', trim($process->getErrorOutput()));
$this->assertSame(1, $result);
// Has not defined `starterkit`.
$install_command = [
$this->php,
'core/scripts/drupal',
'generate-theme',
'test_custom_theme',
'--name="Test custom starterkit theme"',
'--description="Custom theme generated from a starterkit theme"',
'--starterkit',
'olivero',
];
$process = new Process($install_command, NULL);
$process->setTimeout(60);
$result = $process->run();
$this->assertStringContainsString('Theme source theme olivero is not a valid starter kit.', trim($process->getErrorOutput()));
$this->assertSame(1, $result);
}
public function testDeleteDirectory(): void {
$this->writeStarterkitConfig([
'ignore' => [
'/src/*',
'/starterkit_theme.starterkit.yml',
],
]);
$tester = $this->runCommand(
[
'machine-name' => 'test_custom_theme',
'--name' => 'Test custom starterkit theme',
'--description' => 'Custom theme generated from a starterkit theme',
]
);
$tester->assertCommandIsSuccessful($tester->getErrorOutput());
$this->assertThemeExists('themes/test_custom_theme');
$theme_path_absolute = $this->getWorkspaceDirectory() . '/themes/test_custom_theme';
self::assertDirectoryExists($theme_path_absolute);
self::assertFileDoesNotExist($theme_path_absolute . '/src/StarterKit.php');
self::assertDirectoryDoesNotExist($theme_path_absolute . '/src');
}
public function testNoEditMissingFilesWarning(): void {
$this->writeStarterkitConfig([
'no_edit' => [
'/js/starterkit_theme.js',
],
]);
$tester = $this->runCommand(
[
'machine-name' => 'test_custom_theme',
'--name' => 'Test custom starterkit theme',
'--description' => 'Custom theme generated from a starterkit theme',
]
);
self::assertThat($tester->getStatusCode(), self::logicalNot(new CommandIsSuccessful()), trim($tester->getDisplay()));
self::assertEquals('[ERROR] Paths were defined `no_edit` but no files found.', trim($tester->getErrorOutput()));
$theme_path_absolute = $this->getWorkspaceDirectory() . '/themes/test_custom_theme';
self::assertDirectoryDoesNotExist($theme_path_absolute);
}
public function testNoRenameMissingFilesWarning(): void {
$this->writeStarterkitConfig([
'no_rename' => [
'/js/starterkit_theme.js',
],
]);
$tester = $this->runCommand(
[
'machine-name' => 'test_custom_theme',
'--name' => 'Test custom starterkit theme',
'--description' => 'Custom theme generated from a starterkit theme',
]
);
self::assertThat($tester->getStatusCode(), self::logicalNot(new CommandIsSuccessful()), trim($tester->getDisplay()));
self::assertEquals('[ERROR] Paths were defined `no_rename` but no files found.', trim($tester->getErrorOutput()));
$theme_path_absolute = $this->getWorkspaceDirectory() . '/themes/test_custom_theme';
self::assertDirectoryDoesNotExist($theme_path_absolute);
}
public function testNoRename(): void {
$this->writeStarterkitConfig([
'no_rename' => [
'js/starterkit_theme.js',
'**/js/*.js',
'js/**/*.js',
],
]);
mkdir($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/js');
mkdir($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/js/baz');
file_put_contents($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/js/starterkit_theme.js', '');
file_put_contents($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/js/starterkit_theme.foo.js', '');
file_put_contents($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/js/baz/starterkit_theme.bar.js', '');
$tester = $this->runCommand(
[
'machine-name' => 'test_custom_theme',
'--name' => 'Test custom starterkit theme',
'--description' => 'Custom theme generated from a starterkit theme',
]
);
$tester->assertCommandIsSuccessful($tester->getErrorOutput());
$this->assertThemeExists('themes/test_custom_theme');
$theme_path_absolute = $this->getWorkspaceDirectory() . '/themes/test_custom_theme';
self::assertFileExists($theme_path_absolute . '/js/starterkit_theme.js');
self::assertFileExists($theme_path_absolute . '/js/starterkit_theme.foo.js');
self::assertFileExists($theme_path_absolute . '/js/baz/starterkit_theme.bar.js');
}
public function testNoEdit(): void {
$this->writeStarterkitConfig([
'no_edit' => [
'*no_edit_*',
],
]);
$fixture = <<<FIXTURE
# machine_name
starterkit_theme
# label
Starterkit theme
# machine_class_name
StarterkitTheme
# label_class_name
StarterkitTheme
FIXTURE;
file_put_contents($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/edit_fixture.txt', $fixture);
file_put_contents($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/no_edit_fixture.txt', $fixture);
file_put_contents($this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/src/StarterkitThemePreRender.php', <<<PHP
<?php
namespace Drupal\starterkit_theme;
use Drupal\Core\Security\TrustedCallbackInterface;
/**
* Implements trusted prerender callbacks for the Starterkit theme.
*
* @internal
*/
class StarterkitThemePreRender implements TrustedCallbackInterface {
}
PHP);
$tester = $this->runCommand(
[
'machine-name' => 'test_custom_theme',
'--name' => 'Test custom starterkit theme',
'--description' => 'Custom theme generated from a starterkit theme',
]
);
$tester->assertCommandIsSuccessful($tester->getErrorOutput());
$this->assertThemeExists('themes/test_custom_theme');
$theme_path_absolute = $this->getWorkspaceDirectory() . '/themes/test_custom_theme';
self::assertFileExists($theme_path_absolute . '/no_edit_fixture.txt');
self::assertEquals($fixture, file_get_contents($theme_path_absolute . '/no_edit_fixture.txt'));
self::assertFileExists($theme_path_absolute . '/edit_fixture.txt');
self::assertEquals(<<<EDITED
# machine_name
test_custom_theme
# label
Test custom starterkit theme
# machine_class_name
TestCustomTheme
# label_class_name
TestCustomTheme
EDITED, file_get_contents($theme_path_absolute . '/edit_fixture.txt'));
self::assertEquals(<<<EDITED
<?php
namespace Drupal\\test_custom_theme;
use Drupal\Core\Security\TrustedCallbackInterface;
/**
* Implements trusted prerender callbacks for the Test custom starterkit theme.
*
* @internal
*/
class TestCustomThemePreRender implements TrustedCallbackInterface {
}
EDITED, file_get_contents($theme_path_absolute . '/src/TestCustomThemePreRender.php'));
}
public function testInfoOverrides(): void {
// Force `base theme` to be `false.
$starterkit_info_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.info.yml';
$info = Yaml::decode(file_get_contents($starterkit_info_yml));
$info['base theme'] = FALSE;
file_put_contents($starterkit_info_yml, Yaml::encode($info));
$this->writeStarterkitConfig([
'info' => [
'libraries' => [
'core/jquery',
],
],
]);
$tester = $this->runCommand(
[
'machine-name' => 'test_custom_theme',
'--name' => 'Test custom starterkit theme',
'--description' => 'Custom theme generated from a starterkit theme',
]
);
$tester->assertCommandIsSuccessful($tester->getErrorOutput());
$info = $this->assertThemeExists('themes/test_custom_theme');
self::assertArrayHasKey('base theme', $info);
self::assertFalse($info['base theme']);
self::assertArrayHasKey('libraries', $info);
self::assertEquals(['core/jquery'], $info['libraries']);
}
private function writeStarterkitConfig(array $config): void {
$starterkit_yml = $this->getWorkspaceDirectory() . '/core/themes/starterkit_theme/starterkit_theme.starterkit.yml';
$starterkit_config = Yaml::decode(file_get_contents($starterkit_yml));
$starterkit_config = array_replace_recursive($starterkit_config, $config);
file_put_contents($starterkit_yml, Yaml::encode($starterkit_config));
}
private function runCommand(array $input): CommandTester {
$tester = new CommandTester(new GenerateTheme(NULL, $this->getWorkspaceDirectory()));
$tester->execute($input, [
'capture_stderr_separately' => TRUE,
]);
return $tester;
}
}

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Composer\Component;
use Drupal\BuildTests\Composer\ComposerBuildTestBase;
use Drupal\Composer\Composer;
use Symfony\Component\Finder\Finder;
/**
* Try to install dependencies per component, using Composer.
*
* @group #slow
* @group Composer
* @group Component
*
* @coversNothing
*/
class ComponentsIsolatedBuildTest extends ComposerBuildTestBase {
/**
* Provides an array with relative paths to the component paths.
*
* @return array
* An array with relative paths to the component paths.
*/
public static function provideComponentPaths(): array {
$data = [];
// During the dataProvider phase, there is not a workspace directory yet.
// So we will find relative paths and assemble them with the workspace
// path later.
$drupal_root = self::getDrupalRootStatic();
$composer_json_finder = self::getComponentPathsFinder($drupal_root);
/** @var \Symfony\Component\Finder\SplFileInfo $path */
foreach ($composer_json_finder->getIterator() as $path) {
$data[$path->getRelativePath()] = ['/' . $path->getRelativePath()];
}
return $data;
}
/**
* Test whether components' composer.json can be installed in isolation.
*
* @dataProvider provideComponentPaths
*/
public function testComponentComposerJson(string $component_path): void {
// Only copy the components. Copy all of them because some of them depend on
// each other.
$finder = new Finder();
$finder->files()
->ignoreUnreadableDirs()
->in($this->getDrupalRoot() . static::$componentsPath)
->ignoreDotFiles(FALSE)
->ignoreVCS(FALSE);
$this->copyCodebase($finder->getIterator());
$working_dir = $this->getWorkingPath() . static::$componentsPath . $component_path;
// We add path repositories so we can wire internal dependencies together.
$this->addExpectedRepositories($working_dir);
// Perform the installation.
$this->executeCommand("composer install --working-dir=$working_dir --no-interaction --no-progress");
$this->assertCommandSuccessful();
}
/**
* Adds expected repositories as path repositories to package under test.
*
* @param string $working_dir
* The working directory.
*/
protected function addExpectedRepositories(string $working_dir): void {
foreach ($this->provideComponentPaths() as $path) {
$path = $path[0];
$package_name = 'drupal/core' . strtolower(preg_replace('/[A-Z]/', '-$0', substr($path, 1)));
$path_repo = $this->getWorkingPath() . static::$componentsPath . $path;
$repo_name = strtolower($path);
// Add path repositories with the current version number to the current
// package under test.
$drupal_version = Composer::drupalVersionBranch();
$this->executeCommand("composer config repositories.$repo_name " .
"'{\"type\": \"path\",\"url\": \"$path_repo\",\"options\": {\"versions\": {\"$package_name\": \"$drupal_version\"}}}' --working-dir=$working_dir");
}
}
}

View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Composer\Component;
use Drupal\BuildTests\Composer\ComposerBuildTestBase;
use Drupal\Composer\Composer;
/**
* Demonstrate that the Component generator responds to release tagging.
*
* @group #slow
* @group Composer
* @group Component
*
* @coversNothing
*/
class ComponentsTaggedReleaseTest extends ComposerBuildTestBase {
/**
* Highly arbitrary version and constraint expectations.
*
* @return array
* - First element is the tag that should be applied to \Drupal::version.
* - Second element is the resulting constraint which should be present in
* the component core dependencies.
*/
public static function providerVersionConstraint(): array {
return [
// [Tag, constraint]
'1.0.x-dev' => ['1.0.x-dev', '1.0.x-dev'],
'1.0.0-beta1' => ['1.0.0-beta1', '1.0.0-beta1'],
'1.0.0-rc1' => ['1.0.0-rc1', '1.0.0-rc1'],
'1.0.0' => ['1.0.0', '^1.0'],
];
}
/**
* Validate release tagging and regeneration of dependencies.
*
* @dataProvider providerVersionConstraint
*/
public function testReleaseTagging(string $tag, string $constraint): void {
$this->copyCodebase();
$drupal_root = $this->getWorkspaceDirectory();
// Set the core version.
Composer::setDrupalVersion($drupal_root, $tag);
$this->assertDrupalVersion($tag, $drupal_root);
// Emulate the release script.
// @see https://github.com/xjm/drupal_core_release/blob/main/tag.sh
$this->executeCommand("COMPOSER_ROOT_VERSION=\"$tag\" composer update drupal/core*");
$this->assertCommandSuccessful();
$this->assertErrorOutputContains('generateComponentPackages');
// Find all the components.
$component_finder = $this->getComponentPathsFinder($drupal_root);
// Loop through all the component packages.
/** @var \Symfony\Component\Finder\SplFileInfo $composer_json */
foreach ($component_finder->getIterator() as $composer_json) {
$composer_json_data = json_decode(file_get_contents($composer_json->getPathname()), TRUE);
$requires = array_merge(
$composer_json_data['require'] ?? [],
$composer_json_data['require-dev'] ?? []
);
// Required packages from drupal/core-* should have our constraint.
foreach ($requires as $package => $req_constraint) {
if (str_contains($package, 'drupal/core-')) {
$this->assertEquals($constraint, $req_constraint);
}
}
}
}
}

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Composer;
use Drupal\BuildTests\Framework\BuildTestBase;
use Symfony\Component\Finder\Finder;
/**
* Base class for Composer build tests.
*
* @coversNothing
*/
abstract class ComposerBuildTestBase extends BuildTestBase {
/**
* Relative path from Drupal root to the Components directory.
*
* @var string
*/
protected static $componentsPath = '/core/lib/Drupal/Component';
/**
* Assert that the VERSION constant in Drupal.php is the expected value.
*
* @param string $expectedVersion
* The expected version.
* @param string $dir
* The path to the site root.
*
* @internal
*/
protected function assertDrupalVersion(string $expectedVersion, string $dir): void {
$drupal_php_path = $dir . '/core/lib/Drupal.php';
$this->assertFileExists($drupal_php_path);
// Read back the Drupal version that was set and assert it matches
// expectations
$this->executeCommand("php -r 'include \"$drupal_php_path\"; print \Drupal::VERSION;'");
$this->assertCommandSuccessful();
$this->assertCommandOutputContains($expectedVersion);
}
/**
* Find all the composer.json files for components.
*
* @param string $drupal_root
* The Drupal root directory.
*
* @return \Symfony\Component\Finder\Finder
* A Finder object with all the composer.json files for components.
*/
protected static function getComponentPathsFinder(string $drupal_root): Finder {
$finder = new Finder();
$finder->name('composer.json')
->in($drupal_root . static::$componentsPath)
->ignoreUnreadableDirs()
->depth(1);
return $finder;
}
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Composer;
use Drupal\BuildTests\Framework\BuildTestBase;
use Drupal\Tests\Composer\ComposerIntegrationTrait;
/**
* @group Composer
*/
class ComposerValidateTest extends BuildTestBase {
use ComposerIntegrationTrait;
public static function provideComposerJson() {
$data = [];
$composer_json_finder = self::getComposerJsonFinder(self::getDrupalRootStatic());
foreach ($composer_json_finder->getIterator() as $composer_json) {
$data[] = [$composer_json->getPathname()];
}
return $data;
}
/**
* @dataProvider provideComposerJson
*/
public function testValidateComposer($path): void {
$this->executeCommand('composer validate --strict --no-check-all ' . $path);
$this->assertCommandSuccessful();
}
}

View File

@@ -0,0 +1,460 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Composer\Template;
use Composer\Json\JsonFile;
use Composer\Semver\VersionParser;
use Drupal\BuildTests\Composer\ComposerBuildTestBase;
use Drupal\Composer\Composer;
/**
* Demonstrate that Composer project templates can be built as patched.
*
* We have to use the packages.json fixture so that Composer will use the
* in-codebase version of the project template.
*
* We also have to add path repositories to the in-codebase project template or
* else Composer will try to use packagist to resolve dependencies we'd prefer
* it to find locally.
*
* This is because Composer only uses the packages.json file to resolve the
* project template and not any other dependencies.
*
* @group #slow
* @group Template
*/
class ComposerProjectTemplatesTest extends ComposerBuildTestBase {
/**
* The minimum stability requirement for dependencies.
*
* @see https://getcomposer.org/doc/04-schema.md#minimum-stability
*/
protected const MINIMUM_STABILITY = 'stable';
/**
* The order of stability strings from least stable to most stable.
*
* This only includes normalized stability strings: i.e., ones that are
* returned by \Composer\Semver\VersionParser::parseStability().
*/
protected const STABILITY_ORDER = ['dev', 'alpha', 'beta', 'RC', 'stable'];
/**
* Get Composer items that we want to be path repos, from within a directory.
*
* @param string $workspace_directory
* The full path to the workspace directory.
* @param string $subdir
* The subdirectory to search under composer/.
*
* @return string[]
* Array of paths, indexed by package name.
*/
public function getPathReposForType($workspace_directory, $subdir) {
// Find the Composer items that we want to be path repos.
/** @var \SplFileInfo[] $path_repos */
$path_repos = Composer::composerSubprojectPaths($workspace_directory, $subdir);
$data = [];
foreach ($path_repos as $path_repo) {
$json_file = new JsonFile($path_repo->getPathname());
$json = $json_file->read();
$data[$json['name']] = $path_repo->getPath();
}
return $data;
}
public static function provideTemplateCreateProject() {
return [
'recommended-project' => [
'drupal/recommended-project',
'composer/Template/RecommendedProject',
'/web',
],
'legacy-project' => [
'drupal/legacy-project',
'composer/Template/LegacyProject',
'',
],
];
}
/**
* Make sure that static::MINIMUM_STABILITY is sufficiently strict.
*/
public function testMinimumStabilityStrictness(): void {
// Ensure that static::MINIMUM_STABILITY is not less stable than the
// current core stability. For example, if we've already released a beta on
// the branch, ensure that we no longer allow alpha dependencies.
$this->assertGreaterThanOrEqual(array_search($this->getCoreStability(), static::STABILITY_ORDER), array_search(static::MINIMUM_STABILITY, static::STABILITY_ORDER));
// Ensure that static::MINIMUM_STABILITY is the same as the least stable
// dependency.
// - We can't set it stricter than our least stable dependency.
// - We don't want to set it looser than we need to, because we don't want
// to in the future accidentally commit a dependency that regresses our
// actual stability requirement without us explicitly changing this
// constant.
$root = $this->getDrupalRoot();
$process = $this->executeCommand("composer --working-dir=$root info --format=json");
$this->assertCommandSuccessful();
$installed = json_decode($process->getOutput(), TRUE);
// A lookup of the numerical position of each of the stability terms.
$stability_order_indexes = array_flip(static::STABILITY_ORDER);
$minimum_stability_order_index = $stability_order_indexes[static::MINIMUM_STABILITY];
$exclude = [
'drupal/core',
'drupal/core-project-message',
'drupal/core-vendor-hardening',
];
foreach ($installed['installed'] as $project) {
// Exclude dependencies that are required with "self.version", since
// those stabilities will automatically match the corresponding Drupal
// release.
if (in_array($project['name'], $exclude, TRUE)) {
continue;
}
// VersionParser::parseStability doesn't play nice with (mostly dev-)
// versions ending with the first seven characters of the commit ID as
// returned by "composer info". Let's strip those suffixes here.
$version = preg_replace('/ [0-9a-f]{7}$/i', '', $project['version']);
$project_stability = VersionParser::parseStability($version);
$project_stability_order_index = $stability_order_indexes[$project_stability];
$project_stabilities[$project['name']] = $project_stability;
$this->assertGreaterThanOrEqual($minimum_stability_order_index, $project_stability_order_index, sprintf(
"Dependency %s with stability %s does not meet minimum stability %s.",
$project['name'],
$project_stability,
static::MINIMUM_STABILITY,
));
}
// At least one project should be at the minimum stability.
$this->assertContains(static::MINIMUM_STABILITY, $project_stabilities);
}
/**
* Make sure we've accounted for all the templates.
*/
public function testVerifyTemplateTestProviderIsAccurate(): void {
$root = $this->getDrupalRoot();
$data = $this->provideTemplateCreateProject();
// Find all the templates.
$template_files = Composer::composerSubprojectPaths($root, 'Template');
$this->assertSameSize($template_files, $data);
// We could have the same number of templates but different names.
$template_data = [];
foreach ($data as $data_name => $data_value) {
$template_data[$data_value[0]] = $data_name;
}
/** @var \SplFileInfo $file */
foreach ($template_files as $file) {
$json_file = new JsonFile($file->getPathname());
$json = $json_file->read();
$this->assertArrayHasKey('name', $json);
// Assert that the template name is in the project created
// from the template.
$this->assertArrayHasKey($json['name'], $template_data);
}
}
/**
* @dataProvider provideTemplateCreateProject
*/
public function testTemplateCreateProject($project, $package_dir, $docroot_dir): void {
// Make a working COMPOSER_HOME directory for setting global composer config
$composer_home = $this->getWorkspaceDirectory() . '/composer-home';
mkdir($composer_home);
// Create an empty global composer.json file, just to avoid warnings.
file_put_contents("$composer_home/composer.json", '{}');
// Disable packagist globally (but only in our own custom COMPOSER_HOME).
// It is necessary to do this globally rather than in our SUT composer.json
// in order to ensure that Packagist is disabled during the
// `composer create-project` command.
$this->executeCommand("COMPOSER_HOME=$composer_home composer config --no-interaction --global repo.packagist false");
$this->assertCommandSuccessful();
// Create a "Composer"-type repository containing one entry for every
// package in the vendor directory.
$vendor_packages_path = $this->getWorkspaceDirectory() . '/vendor_packages/packages.json';
$this->makeVendorPackage($vendor_packages_path);
// Make a copy of the code to alter in the workspace directory.
$this->copyCodebase();
// Tests are typically run on "-dev" versions, but we want to simulate
// running them on a tagged release at the same stability as specified in
// static::MINIMUM_STABILITY, in order to verify that everything will work
// if/when we make such a release.
$simulated_core_version = \Drupal::VERSION;
$simulated_core_version_suffix = (static::MINIMUM_STABILITY === 'stable' ? '' : '-' . static::MINIMUM_STABILITY . '99');
$simulated_core_version = str_replace('-dev', $simulated_core_version_suffix, $simulated_core_version);
Composer::setDrupalVersion($this->getWorkspaceDirectory(), $simulated_core_version);
$this->assertDrupalVersion($simulated_core_version, $this->getWorkspaceDirectory());
// Remove the packages.drupal.org entry (and any other custom repository)
// from the SUT's repositories section. There is no way to do this via
// `composer config --unset`, so we read and rewrite composer.json.
$composer_json_path = $this->getWorkspaceDirectory() . "/$package_dir/composer.json";
$composer_json = json_decode(file_get_contents($composer_json_path), TRUE);
unset($composer_json['repositories']);
$json = json_encode($composer_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents($composer_json_path, $json);
// Set up the template to use our path repos. Inclusion of metapackages is
// reported differently, so we load up a separate set for them.
$metapackage_path_repos = $this->getPathReposForType($this->getWorkspaceDirectory(), 'Metapackage');
$this->assertArrayHasKey('drupal/core-recommended', $metapackage_path_repos);
$path_repos = array_merge($metapackage_path_repos, $this->getPathReposForType($this->getWorkspaceDirectory(), 'Plugin'));
// Always add drupal/core as a path repo.
$path_repos['drupal/core'] = $this->getWorkspaceDirectory() . '/core';
foreach ($path_repos as $name => $path) {
$this->executeCommand("composer config --no-interaction repositories.$name path $path", $package_dir);
$this->assertCommandSuccessful();
}
// Change drupal/core-recommended to require the simulated version of
// drupal/core.
$core_recommended_dir = 'composer/Metapackage/CoreRecommended';
$this->executeCommand("composer remove --no-interaction drupal/core --no-update", $core_recommended_dir);
$this->assertCommandSuccessful();
$this->executeCommand("composer require --no-interaction drupal/core:^$simulated_core_version --no-update", $core_recommended_dir);
$this->assertCommandSuccessful();
// Add our vendor package repository to our SUT's repositories section.
// Call it "local" (although the name does not matter).
$this->executeCommand("composer config --no-interaction repositories.local composer file://" . $vendor_packages_path, $package_dir);
$this->assertCommandSuccessful();
$repository_path = $this->getWorkspaceDirectory() . '/test_repository/packages.json';
$this->makeTestPackage($repository_path, $simulated_core_version);
$installed_composer_json = $this->getWorkspaceDirectory() . '/test_project/composer.json';
$autoloader = $this->getWorkspaceDirectory() . '/test_project' . $docroot_dir . '/autoload.php';
$this->assertFileDoesNotExist($autoloader);
$this->executeCommand("COMPOSER_HOME=$composer_home COMPOSER_ROOT_VERSION=$simulated_core_version composer create-project --no-ansi $project test_project $simulated_core_version -vvv --repository $repository_path");
$this->assertCommandSuccessful();
// Check the output of the project creation for the absence of warnings
// about any non-allowed composer plugins.
// Note: There are different warnings for disallowed composer plugins
// depending on running in non-interactive mode or not. It seems the Drupal
// CI environment always forces composer commands to run in the
// non-interactive mode. The only thing these messages have in common is the
// following string.
$this->assertErrorOutputNotContains('See https://getcomposer.org/allow-plugins');
// Ensure we used the project from our codebase.
$this->assertErrorOutputContains("Installing $project ($simulated_core_version): Symlinking from $package_dir");
// Ensure that we used drupal/core from our codebase. This probably means
// that drupal/core-recommended was added successfully by the project.
$this->assertErrorOutputContains("Installing drupal/core ($simulated_core_version): Symlinking from");
// Verify that there is an autoloader. This is written by the scaffold
// plugin, so its existence assures us that scaffolding happened.
$this->assertFileExists($autoloader);
// Verify that the minimum stability in the installed composer.json file
// matches the stability of the simulated core version.
$this->assertFileExists($installed_composer_json);
$composer_json_contents = file_get_contents($installed_composer_json);
$this->assertStringContainsString('"minimum-stability": "' . static::MINIMUM_STABILITY . '"', $composer_json_contents);
// In order to verify that Composer used the path repos for our project, we
// have to get the requirements from the project composer.json so we can
// reconcile our expectations.
$template_json_file = $this->getWorkspaceDirectory() . '/' . $package_dir . '/composer.json';
$this->assertFileExists($template_json_file);
$json_file = new JsonFile($template_json_file);
$template_json = $json_file->read();
// Get the require and require-dev information, and ensure that our
// requirements are not erroneously empty.
$this->assertNotEmpty(
$require = array_merge($template_json['require'] ?? [], $template_json['require-dev'] ?? [])
);
// Verify that path repo packages were installed.
$path_repos = array_keys($path_repos);
foreach (array_keys($require) as $package_name) {
if (in_array($package_name, $path_repos)) {
// Metapackages do not report that they were installed as symlinks, but
// we still must check that their installed version matches
// COMPOSER_CORE_VERSION.
if (array_key_exists($package_name, $metapackage_path_repos)) {
$this->assertErrorOutputContains("Installing $package_name ($simulated_core_version)");
}
else {
$this->assertErrorOutputContains("Installing $package_name ($simulated_core_version): Symlinking from");
}
}
}
}
/**
* Creates a test package that points to the templates.
*
* @param string $repository_path
* The path where to create the test package.
* @param string $version
* The version under test.
*/
protected function makeTestPackage($repository_path, $version) {
$json = <<<JSON
{
"packages": {
"drupal/recommended-project": {
"$version": {
"name": "drupal/recommended-project",
"dist": {
"type": "path",
"url": "composer/Template/RecommendedProject"
},
"type": "project",
"version": "$version"
}
},
"drupal/legacy-project": {
"$version": {
"name": "drupal/legacy-project",
"dist": {
"type": "path",
"url": "composer/Template/LegacyProject"
},
"type": "project",
"version": "$version"
}
}
}
}
JSON;
mkdir(dirname($repository_path));
file_put_contents($repository_path, $json);
}
/**
* Creates a test package that points to all the projects in vendor.
*
* @param string $repository_path
* The path where to create the test package.
*/
protected function makeVendorPackage($repository_path) {
$root = $this->getDrupalRoot();
$process = $this->executeCommand("composer --working-dir=$root info --format=json");
$this->assertCommandSuccessful();
$installed = json_decode($process->getOutput(), TRUE);
// Build out package definitions for everything installed in
// the vendor directory.
$packages = [];
foreach ($installed['installed'] as $project) {
$name = $project['name'];
$version = $project['version'];
$path = "vendor/$name";
$full_path = "$root/$path";
// We are building a set of path repositories to projects in the vendor
// directory, so we will skip any project that does not exist in vendor.
// Also skip the projects that are symlinked in vendor. These are in our
// metapackage. They will be represented as path repositories in the test
// project's composer.json.
if (is_dir($full_path) && !is_link($full_path)) {
$packages['packages'][$name] = [
$version => [
"name" => $name,
"dist" => [
"type" => "path",
"url" => $full_path,
],
"version" => $version,
],
];
// Ensure composer plugins are registered correctly.
$package_json = json_decode(file_get_contents($full_path . '/composer.json'), TRUE);
if (isset($package_json['type']) && $package_json['type'] === 'composer-plugin') {
$packages['packages'][$name][$version]['type'] = $package_json['type'];
$packages['packages'][$name][$version]['require'] = $package_json['require'];
$packages['packages'][$name][$version]['extra'] = $package_json['extra'];
if (isset($package_json['autoload'])) {
$packages['packages'][$name][$version]['autoload'] = $package_json['autoload'];
}
}
}
}
$json = json_encode($packages, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
mkdir(dirname($repository_path));
file_put_contents($repository_path, $json);
}
/**
* Returns the stability of the current core version.
*
* If the current core version is a tagged release (not a "-dev" version),
* this returns the stability of that version.
*
* If the current core version is a "-dev" version, but not a "x.y.0-dev"
* version, this returns "stable", because it means that the corresponding
* "x.y.0" has already been released, and only stable changes are now
* permitted on the branch.
*
* If the current core version is a "x.y.0-dev" version, then this returns
* the stability of the latest tag that matches "x.y.0-*". For example, if
* we've already released "x.y.0-alpha1" but have not yet released
* "x.y.0-beta1", then the current stability is "alpha". If there aren't any
* matching tags, this returns "dev", because it means that an "alpha1" has
* not yet been released.
*
* @return string
* One of: "dev", "alpha", "beta", "RC", "stable".
*/
protected function getCoreStability() {
$version = \Drupal::VERSION;
$stability = VersionParser::parseStability($version);
if ($stability === 'dev') {
// Strip off "-dev";
$version_towards = substr($version, 0, -4);
if (!str_ends_with($version_towards, '.0')) {
// If the current version is developing towards an x.y.z release where
// z is not 0, it means that the x.y.0 has already been released, and
// only stable changes are permitted on the branch.
$stability = 'stable';
}
else {
// If the current version is developing towards an x.y.0 release, there
// might be tagged pre-releases. "git describe" identifies the latest
// one.
$root = $this->getDrupalRoot();
$process = $this->executeCommand("git -C \"$root\" describe --abbrev=0 --match=\"$version_towards-*\"");
// If there aren't any tagged pre-releases for this version yet, return
// 'dev'. Ensure that any other error from "git describe" causes a test
// failure.
if (!$process->isSuccessful()) {
$this->assertErrorOutputContains('No names found, cannot describe anything.');
return 'dev';
}
// We expect a pre-release, because:
// - A tag should not be of "dev" stability.
// - After a "stable" release is made, \Drupal::VERSION is incremented,
// so there should not be a stable release on that new version.
$stability = VersionParser::parseStability(trim($process->getOutput()));
$this->assertContains($stability, ['alpha', 'beta', 'RC']);
}
}
return $stability;
}
}

View File

@@ -0,0 +1,661 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Framework;
use Behat\Mink\Driver\BrowserKitDriver;
use Behat\Mink\Mink;
use Behat\Mink\Session;
use Composer\InstalledVersions;
use Drupal\Component\FileSystem\FileSystem as DrupalFilesystem;
use Drupal\Tests\DrupalTestBrowser;
use Drupal\Tests\PhpUnitCompatibilityTrait;
use Drupal\Tests\Traits\PhpUnitWarnings;
use Drupal\TestTools\Extension\RequiresComposerTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
/**
* Provides a workspace to test build processes.
*
* If you need to build a file system and then run a command from the command
* line then this is the test framework for you.
*
* Tests using this interface run in separate processes.
*
* Tests can perform HTTP requests against the assembled codebase.
*
* The results of these HTTP requests can be asserted using Mink.
*
* This framework does not use the same Mink extensions as BrowserTestBase.
*
* Features:
* - Provide complete isolation between the test runner and the site under test.
* - Provide a workspace where filesystem build processes can be performed.
* - Allow for the use of PHP's build-in HTTP server to send requests to the
* site built using the filesystem.
* - Allow for commands and HTTP requests to be made to different subdirectories
* of the workspace filesystem, to facilitate comparison between different
* build results, and to support Composer builds which have an alternate
* docroot.
* - Provide as little framework as possible. Convenience methods should be
* built into the test, or abstract base classes.
* - Allow parallel testing, using random/unique port numbers for different HTTP
* servers.
*
* We don't use UiHelperInterface because it is too tightly integrated to
* Drupal.
*/
abstract class BuildTestBase extends TestCase {
use RequiresComposerTrait;
use PhpUnitWarnings;
use PhpUnitCompatibilityTrait;
/**
* The working directory where this test will manipulate files.
*
* Use getWorkspaceDirectory() to access this information.
*
* @var string
*
* @see self::getWorkspaceDirectory()
*/
private $workspaceDir;
/**
* The process that's running the HTTP server.
*
* @var \Symfony\Component\Process\Process
*
* @see self::standUpServer()
* @see self::stopServer()
*/
private $serverProcess = NULL;
/**
* Default to destroying build artifacts after a test finishes.
*
* Mainly useful for debugging.
*
* @var bool
*/
protected $destroyBuild = TRUE;
/**
* The docroot for the server process.
*
* This stores the last docroot directory used to start the server process. We
* keep this information so we can restart the server if the desired docroot
* changes.
*
* @var string
*/
private $serverDocroot = NULL;
/**
* Our native host name, used by PHP when it starts up the server.
*
* Requests should always be made to 'localhost', and not this IP address.
*
* @var string
*/
private static $hostName = '127.0.0.1';
/**
* Port that will be tested.
*
* Generated internally. Use getPortNumber().
*
* @var int
*/
private $hostPort;
/**
* A list of ports used by the test.
*
* Prevent the same process finding the same port by storing a list of ports
* already discovered. This also stores locks so they are not released until
* the test class is torn down.
*
* @var \Symfony\Component\Lock\LockInterface[]
*/
private $portLocks = [];
/**
* The Mink session manager.
*
* @var \Behat\Mink\Mink
*/
private $mink;
/**
* The most recent command process.
*
* @var \Symfony\Component\Process\Process
*
* @see ::executeCommand()
*/
private $commandProcess;
/**
* The PHP executable finder.
*
* @var \Symfony\Component\Process\PhpExecutableFinder
*/
private PhpExecutableFinder $phpFinder;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->phpFinder = new PhpExecutableFinder();
// Set up the workspace directory.
// @todo Glean working directory from env vars, etc.
$fs = new SymfonyFilesystem();
$this->workspaceDir = $fs->tempnam(DrupalFilesystem::getOsTemporaryDirectory(), '/build_workspace_' . md5($this->name() . microtime(TRUE)));
$fs->remove($this->workspaceDir);
$fs->mkdir($this->workspaceDir);
$this->initMink();
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void {
parent::tearDown();
$this->stopServer();
foreach ($this->portLocks as $lock) {
$lock->release();
}
$ws = $this->getWorkspaceDirectory();
$fs = new SymfonyFilesystem();
if ($this->destroyBuild && $fs->exists($ws)) {
// Filter out symlinks as chmod cannot alter them.
$finder = new Finder();
$finder->in($ws)
->directories()
->ignoreVCS(FALSE)
->ignoreDotFiles(FALSE)
// composer script is a symlink and fails chmod. Ignore it.
->notPath('/^vendor\/bin\/composer$/');
$fs->chmod($finder->getIterator(), 0775, 0000);
$fs->remove($ws);
}
}
/**
* Get the working directory within the workspace, creating if necessary.
*
* @param string $working_dir
* The path within the workspace directory.
*
* @return string
* The full path to the working directory within the workspace directory.
*/
protected function getWorkingPath($working_dir = NULL) {
$full_path = $this->getWorkspaceDirectory();
if ($working_dir) {
$full_path .= '/' . $working_dir;
}
if (!file_exists($full_path)) {
$fs = new SymfonyFilesystem();
$fs->mkdir($full_path);
}
return $full_path;
}
/**
* Set up the Mink session manager.
*
* @return \Behat\Mink\Session
*/
protected function initMink() {
$client = new DrupalTestBrowser();
$client->followMetaRefresh(TRUE);
$driver = new BrowserKitDriver($client);
$session = new Session($driver);
$this->mink = new Mink();
$this->mink->registerSession('default', $session);
$this->mink->setDefaultSessionName('default');
$session->start();
return $session;
}
/**
* Get the Mink instance.
*
* Use the Mink object to perform assertions against the content returned by a
* request.
*
* @return \Behat\Mink\Mink
* The Mink object.
*/
public function getMink() {
return $this->mink;
}
/**
* Full path to the workspace where this test can build.
*
* This is often a directory within the system's temporary directory.
*
* @return string
* Full path to the workspace where this test can build.
*/
public function getWorkspaceDirectory() {
return $this->workspaceDir;
}
/**
* Assert that text is present in the error output of the most recent command.
*
* @param string $expected
* Text we expect to find in the error output of the command.
*/
public function assertErrorOutputContains($expected) {
$this->assertStringContainsString($expected, $this->commandProcess->getErrorOutput());
}
/**
* Assert text is not present in the error output of the most recent command.
*
* @param string $expected
* Text we expect not to find in the error output of the command.
*/
public function assertErrorOutputNotContains($expected) {
$this->assertStringNotContainsString($expected, $this->commandProcess->getErrorOutput());
}
/**
* Assert that text is present in the output of the most recent command.
*
* @param string $expected
* Text we expect to find in the output of the command.
*/
public function assertCommandOutputContains($expected) {
$this->assertStringContainsString($expected, $this->commandProcess->getOutput());
}
/**
* Asserts that the last command ran without error.
*
* This assertion checks whether the last command returned an exit code of 0.
*
* If you need to assert a different exit code, then you can use
* executeCommand() and perform a different assertion on the process object.
*/
public function assertCommandSuccessful() {
return $this->assertCommandExitCode(0);
}
/**
* Asserts that the last command returned the specified exit code.
*
* @param int $expected_code
* The expected process exit code.
*/
public function assertCommandExitCode($expected_code) {
$this->assertEquals($expected_code, $this->commandProcess->getExitCode(),
'COMMAND: ' . $this->commandProcess->getCommandLine() . "\n" .
'OUTPUT: ' . $this->commandProcess->getOutput() . "\n" .
'ERROR: ' . $this->commandProcess->getErrorOutput() . "\n"
);
}
/**
* Run a command.
*
* @param string $command_line
* A command line to run in an isolated process.
* @param string $working_dir
* (optional) A working directory relative to the workspace, within which to
* execute the command. Defaults to the workspace directory.
*
* @return \Symfony\Component\Process\Process
*/
public function executeCommand($command_line, $working_dir = NULL) {
$this->commandProcess = Process::fromShellCommandline($command_line);
$this->commandProcess->setWorkingDirectory($this->getWorkingPath($working_dir))
->setTimeout(300)
->setIdleTimeout(300);
$this->commandProcess->run();
return $this->commandProcess;
}
/**
* Helper function to assert that the last visit was a Drupal site.
*
* This method asserts that the X-Generator header shows that the site is a
* Drupal site.
*/
public function assertDrupalVisit() {
$this->getMink()->assertSession()->responseHeaderMatches('X-Generator', '/Drupal \d+ \(https:\/\/www.drupal.org\)/');
}
/**
* Visit a URI on the HTTP server.
*
* The concept here is that there could be multiple potential docroots in the
* workspace, so you can use whichever ones you want.
*
* @param string $request_uri
* (optional) The non-host part of the URL. Example: /some/path?foo=bar.
* Defaults to visiting the homepage.
* @param string $working_dir
* (optional) Relative path within the test workspace file system that will
* be the docroot for the request. Defaults to the workspace directory.
*
* @return \Behat\Mink\Mink
* The Mink object. Perform assertions against this.
*
* @throws \InvalidArgumentException
* Thrown when $request_uri does not start with a slash.
*/
public function visit($request_uri = '/', $working_dir = NULL) {
if ($request_uri[0] !== '/') {
throw new \InvalidArgumentException('URI: ' . $request_uri . ' must be relative. Example: /some/path?foo=bar');
}
// Try to make a server.
$this->standUpServer($working_dir);
$request = 'http://localhost:' . $this->getPortNumber() . $request_uri;
$this->mink->getSession()->visit($request);
return $this->mink;
}
/**
* Makes a local test server using PHP's internal HTTP server.
*
* Test authors should call visit() or assertVisit() instead.
*
* @param string|null $working_dir
* (optional) Server docroot relative to the workspace file system. Defaults
* to the workspace directory.
*/
protected function standUpServer($working_dir = NULL) {
// If the user wants to test a new docroot, we have to shut down the old
// server process and generate a new port number.
if ($working_dir !== $this->serverDocroot && !empty($this->serverProcess)) {
$this->stopServer();
}
// If there's not a server at this point, make one.
if (!$this->serverProcess || $this->serverProcess->isTerminated()) {
$this->serverProcess = $this->instantiateServer($this->getPortNumber(), $working_dir);
if ($this->serverProcess) {
$this->serverDocroot = $working_dir;
}
}
}
/**
* Do the work of making a server process.
*
* Test authors should call visit() or assertVisit() instead.
*
* When initializing the server, if '.ht.router.php' exists in the root, it is
* leveraged. If testing with a version of Drupal before 8.5.x., this file
* does not exist.
*
* @param int $port
* The port number for the server.
* @param string|null $working_dir
* (optional) Server docroot relative to the workspace filesystem. Defaults
* to the workspace directory.
*
* @return \Symfony\Component\Process\Process
* The server process.
*
* @throws \RuntimeException
* Thrown if we were unable to start a web server.
*/
protected function instantiateServer($port, $working_dir = NULL) {
$finder = new PhpExecutableFinder();
$working_path = $this->getWorkingPath($working_dir);
$server = [
$finder->find(),
'-S',
self::$hostName . ':' . $port,
'-t',
$working_path,
];
if (file_exists($working_path . DIRECTORY_SEPARATOR . '.ht.router.php')) {
$server[] = $working_path . DIRECTORY_SEPARATOR . '.ht.router.php';
}
$ps = new Process($server, $working_path);
$ps->setIdleTimeout(30)
->setTimeout(30)
->start();
// Wait until the web server has started. It is started if the port is no
// longer available.
for ($i = 0; $i < 50; $i++) {
usleep(100000);
if (!$this->checkPortIsAvailable($port)) {
return $ps;
}
}
throw new \RuntimeException(sprintf("Unable to start the web server.\nCMD: %s \nCODE: %d\nSTATUS: %s\nOUTPUT:\n%s\n\nERROR OUTPUT:\n%s", $ps->getCommandLine(), $ps->getExitCode(), $ps->getStatus(), $ps->getOutput(), $ps->getErrorOutput()));
}
/**
* Stop the HTTP server, zero out all necessary variables.
*/
protected function stopServer() {
if (!empty($this->serverProcess)) {
$this->serverProcess->stop();
}
$this->serverProcess = NULL;
$this->serverDocroot = NULL;
$this->hostPort = NULL;
$this->initMink();
}
/**
* Discover an available port number.
*
* @return int
* The available port number that we discovered.
*
* @throws \RuntimeException
* Thrown when there are no available ports within the range.
*/
protected function findAvailablePort() {
$store = new FlockStore(DrupalFilesystem::getOsTemporaryDirectory());
$lock_factory = new LockFactory($store);
$counter = 100;
while ($counter--) {
// Limit to 9999 as higher ports cause random fails on DrupalCI.
$port = random_int(1024, 9999);
if (isset($this->portLocks[$port])) {
continue;
}
// Take a lock so that no other process can use the same port number even
// if the server is yet to start.
$lock = $lock_factory->createLock('drupal-build-test-port-' . $port);
if ($lock->acquire()) {
if ($this->checkPortIsAvailable($port)) {
$this->portLocks[$port] = $lock;
return $port;
}
else {
$lock->release();
}
}
}
throw new \RuntimeException('Unable to find a port available to run the web server.');
}
/**
* Checks whether a port is available.
*
* @param $port
* A number between 1024 and 65536.
*
* @return bool
*/
protected function checkPortIsAvailable($port) {
$fp = @fsockopen(self::$hostName, $port, $errno, $errstr, 1);
// If fsockopen() fails to connect, probably nothing is listening.
// It could be a firewall but that's impossible to detect, so as a
// best guess let's return it as available.
if ($fp === FALSE) {
return TRUE;
}
else {
fclose($fp);
}
return FALSE;
}
/**
* Get the port number for requests.
*
* Test should never call this. Used by standUpServer().
*
* @return int
*/
protected function getPortNumber() {
if (empty($this->hostPort)) {
$this->hostPort = $this->findAvailablePort();
}
return $this->hostPort;
}
/**
* Copy the current working codebase into a workspace.
*
* Use this method to copy the current codebase, including any patched
* changes, into the workspace.
*
* By default, the copy will exclude site-specific and build-related files and
* directories. Use the $iterator parameter to override this behavior.
*
* @param \Iterator|null $iterator
* (optional) An iterator of all the files to copy. Default behavior is to
* exclude site-specific directories and files.
* @param string|null $working_dir
* (optional) Relative path within the test workspace file system that will
* contain the copy of the codebase. Defaults to the workspace directory.
*/
public function copyCodebase(?\Iterator $iterator = NULL, $working_dir = NULL) {
$working_path = $this->getWorkingPath($working_dir);
if ($iterator === NULL) {
$iterator = $this->getCodebaseFinder()->getIterator();
}
$fs = new SymfonyFilesystem();
$options = ['override' => TRUE, 'delete' => FALSE];
$fs->mirror($this->getComposerRoot(), $working_path, $iterator, $options);
}
/**
* Get a default Finder object for a Drupal codebase.
*
* This method can be used two ways:
* - Override this method and provide your own default Finder object for
* copyCodebase().
* - Call the method to get a default Finder object which can then be
* modified for other purposes.
*
* Note that the vendor directory is deliberately not included in the
* directory exclusions here, so that packages are copied and composer does
* not attempt to download them from packagist/github during test runs.
*
* @return \Symfony\Component\Finder\Finder
* A Finder object ready to iterate over core codebase.
*/
public function getCodebaseFinder() {
$drupal_root = $this->getWorkingPathDrupalRoot() ?? '';
$finder = new Finder();
$finder->files()
->followLinks()
->ignoreUnreadableDirs()
->in($this->getComposerRoot())
->notPath("#^{$drupal_root}sites/default/files#")
->notPath("#^{$drupal_root}sites/simpletest#")
->notPath("#^{$drupal_root}core/node_modules#")
->notPath("#^{$drupal_root}sites/default/settings\..*php#")
->ignoreDotFiles(FALSE)
->ignoreVCS(FALSE);
return $finder;
}
/**
* Get the root path of this Drupal codebase.
*
* @return string
* The full path to the root of this Drupal codebase.
*/
public function getDrupalRoot() {
return self::getDrupalRootStatic();
}
/**
* Get the root path of this Drupal codebase.
*
* @return string
* The full path to the root of this Drupal codebase.
*/
public static function getDrupalRootStatic() {
// Given this code is in the drupal/core package, $core cannot be NULL.
/** @var string $core */
$core = InstalledVersions::getInstallPath('drupal/core');
return realpath(dirname($core));
}
/**
* Gets the path to the Composer root directory.
*
* @return string
* The absolute path to the Composer root directory.
*/
public function getComposerRoot(): string {
$root = InstalledVersions::getRootPackage();
return realpath($root['install_path']);
}
/**
* Gets the path to Drupal root in the workspace directory.
*
* @return string
* The absolute path to the Drupal root directory in the workspace.
*/
public function getWorkspaceDrupalRoot(): string {
$dir = $this->getWorkspaceDirectory();
$drupal_root = $this->getWorkingPathDrupalRoot();
if ($drupal_root !== NULL) {
$dir = $dir . DIRECTORY_SEPARATOR . $drupal_root;
}
return $dir;
}
/**
* Gets the working path for Drupal core.
*
* @return string|null
* The relative path to Drupal's root directory or NULL if it is the same
* as the composer root directory.
*/
public function getWorkingPathDrupalRoot(): ?string {
$composer_root = $this->getComposerRoot();
$drupal_root = $this->getDrupalRoot();
if ($composer_root === $drupal_root) {
return NULL;
}
return (new SymfonyFilesystem())->makePathRelative($drupal_root, $composer_root);
}
}

View File

@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Framework;
use PHPUnit\Framework\SkippedTestError;
use PHPUnit\Util\Test;
use Symfony\Component\Process\ExecutableFinder;
/**
* Allows test classes to require external command line applications.
*
* Use annotation such as '(at)requires externalCommand git'.
*
* @deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use
* Drupal\\TestTools\\Extension\\RequiresComposerTrait instead.
*
* @see https://www.drupal.org/node/3362239
*/
trait ExternalCommandRequirementsTrait {
/**
* A list of existing external commands we've already discovered.
*
* @var string[]
*/
private static $existingCommands = [];
/**
* Checks whether required external commands are available per test class.
*
* @throws \PHPUnit\Framework\SkippedTestError
* Thrown when the requirements are not met, and this test should be
* skipped. Callers should not catch this exception.
*/
private static function checkClassCommandRequirements() {
@trigger_error(__METHOD__ . "() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239", E_USER_DEPRECATED);
$annotations = Test::parseTestMethodAnnotations(static::class);
if (!empty($annotations['class']['requires'])) {
static::checkExternalCommandRequirements($annotations['class']['requires']);
}
}
/**
* Checks whether required external commands are available per method.
*
* @throws \PHPUnit\Framework\SkippedTestError
* Thrown when the requirements are not met, and this test should be
* skipped. Callers should not catch this exception.
*/
private static function checkMethodCommandRequirements($name) {
@trigger_error(__METHOD__ . "() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239", E_USER_DEPRECATED);
$annotations = Test::parseTestMethodAnnotations(static::class, $name);
if (!empty($annotations['method']['requires'])) {
static::checkExternalCommandRequirements($annotations['method']['requires']);
}
}
/**
* Checks missing external command requirements.
*
* @param string[] $annotations
* A list of requires annotations from either a method or class annotation.
*
* @throws \PHPUnit\Framework\SkippedTestError
* Thrown when the requirements are not met, and this test should be
* skipped. Callers should not catch this exception.
*/
private static function checkExternalCommandRequirements(array $annotations) {
@trigger_error(__METHOD__ . "() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239", E_USER_DEPRECATED);
// Make a list of required commands.
$required_commands = [];
foreach ($annotations as $requirement) {
if (str_starts_with($requirement, 'externalCommand ')) {
@trigger_error("The '@require externalCommand' annotation for tests is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239", E_USER_DEPRECATED);
$command = trim(str_replace('externalCommand ', '', $requirement));
// Use named keys to avoid duplicates.
$required_commands[$command] = $command;
}
}
// Figure out which commands are not available.
$unavailable = [];
foreach ($required_commands as $required_command) {
if (!in_array($required_command, self::$existingCommands)) {
if (static::externalCommandIsAvailable($required_command)) {
// Cache existing commands so we don't have to ask again.
self::$existingCommands[] = $required_command;
}
else {
$unavailable[] = $required_command;
}
}
}
// Skip the test if there were some we couldn't find.
if (!empty($unavailable)) {
throw new SkippedTestError('Required external commands: ' . implode(', ', $unavailable));
}
}
/**
* Determine if an external command is available.
*
* @param $command
* The external command.
*
* @return bool
* TRUE if external command is available, else FALSE.
*/
private static function externalCommandIsAvailable($command) {
$finder = new ExecutableFinder();
return (bool) $finder->find($command);
}
}

View File

@@ -0,0 +1,264 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Framework\Tests;
use Drupal\BuildTests\Framework\BuildTestBase;
use org\bovigo\vfs\vfsStream;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
/**
* @coversDefaultClass \Drupal\BuildTests\Framework\BuildTestBase
* @group Build
*/
class BuildTestTest extends BuildTestBase {
/**
* Ensure that workspaces work.
*/
public function testWorkspace(): void {
$test_directory = 'test_directory';
// Execute an empty command through the shell to build out a working
// directory.
$process = $this->executeCommand('', $test_directory);
$this->assertCommandSuccessful();
// Assert that our working directory exists and is in use by the process.
$workspace = $this->getWorkspaceDirectory();
$working_path = $workspace . '/' . $test_directory;
$this->assertDirectoryExists($working_path);
$this->assertEquals($working_path, $process->getWorkingDirectory());
}
/**
* @covers ::copyCodebase
*/
public function testCopyCodebase(): void {
$test_directory = 'copied_codebase';
$this->copyCodebase(NULL, $test_directory);
$full_path = $this->getWorkspaceDirectory() . '/' . $test_directory;
$files = [
'autoload.php',
'composer.json',
'index.php',
'README.md',
'.git',
'.ht.router.php',
];
foreach ($files as $file) {
$this->assertFileExists($full_path . '/' . $file);
}
}
/**
* Ensure we're not copying directories we wish to exclude.
*
* @covers ::copyCodebase
*/
public function testCopyCodebaseExclude(): void {
// Create a virtual file system containing items that should be
// excluded. Exception being modules directory.
vfsStream::setup('drupal', NULL, [
'sites' => [
'default' => [
'files' => [
'a_file.txt' => 'some file.',
],
'settings.php' => '<?php $settings = stuff;',
'settings.local.php' => '<?php $settings = override;',
],
'simpletest' => [
'simpletest_hash' => [
'some_results.xml' => '<xml/>',
],
],
],
'modules' => [
'my_module' => [
'vendor' => [
'my_vendor' => [
'composer.json' => "{\n}",
],
],
],
],
]);
// Mock BuildTestBase so that it thinks our VFS is the Composer and Drupal
// roots.
/** @var \PHPUnit\Framework\MockObject\MockBuilder|\Drupal\BuildTests\Framework\BuildTestBase $base */
$base = $this->getMockBuilder(BuildTestBase::class)
->onlyMethods(['getDrupalRoot', 'getComposerRoot'])
->getMockForAbstractClass();
$base->expects($this->exactly(1))
->method('getDrupalRoot')
->willReturn(vfsStream::url('drupal'));
$base->expects($this->exactly(3))
->method('getComposerRoot')
->willReturn(vfsStream::url('drupal'));
$base->setUp();
// Perform the copy.
$test_directory = 'copied_codebase';
$base->copyCodebase(NULL, $test_directory);
$full_path = $base->getWorkspaceDirectory() . '/' . $test_directory;
$this->assertDirectoryExists($full_path);
// Verify nested vendor directory was not excluded. Then remove it for next
// validation.
$this->assertFileExists($full_path . DIRECTORY_SEPARATOR . 'modules/my_module/vendor/my_vendor/composer.json');
$file_system = new Filesystem();
$file_system->remove($full_path . DIRECTORY_SEPARATOR . 'modules');
// Use scandir() to determine if our target directory is empty. It should
// only contain the system dot directories.
$this->assertTrue(
($files = @scandir($full_path)) && count($files) <= 2,
'Directory is not empty: ' . implode(', ', $files)
);
$base->tearDown();
}
/**
* Tests copying codebase when Drupal and Composer roots are different.
*
* @covers ::copyCodebase
*/
public function testCopyCodebaseDocRoot(): void {
// Create a virtual file system containing items that should be
// excluded. Exception being modules directory.
vfsStream::setup('drupal', NULL, [
'docroot' => [
'sites' => [
'default' => [
'files' => [
'a_file.txt' => 'some file.',
],
'settings.php' => '<?php $settings = "stuff";',
'settings.local.php' => '<?php $settings = "override";',
'default.settings.php' => '<?php $settings = "default";',
],
'simpletest' => [
'simpletest_hash' => [
'some_results.xml' => '<xml/>',
],
],
],
'modules' => [
'my_module' => [
'vendor' => [
'my_vendor' => [
'composer.json' => "{\n}",
],
],
],
],
],
'vendor' => [
'test.txt' => 'File exists',
],
]);
// Mock BuildTestBase so that it thinks our VFS is the Composer and Drupal
// roots.
/** @var \PHPUnit\Framework\MockObject\MockBuilder|\Drupal\BuildTests\Framework\BuildTestBase $base */
$base = $this->getMockBuilder(BuildTestBase::class)
->onlyMethods(['getDrupalRoot', 'getComposerRoot'])
->getMockForAbstractClass();
$base->expects($this->exactly(3))
->method('getDrupalRoot')
->willReturn(vfsStream::url('drupal/docroot'));
$base->expects($this->exactly(5))
->method('getComposerRoot')
->willReturn(vfsStream::url('drupal'));
$base->setUp();
// Perform the copy.
$base->copyCodebase();
$full_path = $base->getWorkspaceDirectory();
$this->assertDirectoryExists($full_path . '/docroot');
// Verify expected files exist.
$this->assertFileExists($full_path . DIRECTORY_SEPARATOR . 'docroot/modules/my_module/vendor/my_vendor/composer.json');
$this->assertFileExists($full_path . DIRECTORY_SEPARATOR . 'docroot/sites/default/default.settings.php');
$this->assertFileExists($full_path . DIRECTORY_SEPARATOR . 'vendor');
// Verify expected files do not exist
$this->assertFileDoesNotExist($full_path . DIRECTORY_SEPARATOR . 'docroot/sites/default/settings.php');
$this->assertFileDoesNotExist($full_path . DIRECTORY_SEPARATOR . 'docroot/sites/default/settings.local.php');
$this->assertFileDoesNotExist($full_path . DIRECTORY_SEPARATOR . 'docroot/sites/default/files');
// Ensure that the workspace Drupal root is calculated correctly.
$this->assertSame($full_path . '/docroot/', $base->getWorkspaceDrupalRoot());
$this->assertSame('docroot/', $base->getWorkingPathDrupalRoot());
$base->tearDown();
}
/**
* @covers ::findAvailablePort
*/
public function testPortMany(): void {
$iterator = (new Finder())->in($this->getDrupalRoot())
->ignoreDotFiles(FALSE)
->exclude(['sites/simpletest'])
->path('/^.ht.router.php$/')
->getIterator();
$this->copyCodebase($iterator);
/** @var \Symfony\Component\Process\Process[] $processes */
$processes = [];
$count = 15;
for ($i = 0; $i <= $count; $i++) {
$port = $this->findAvailablePort();
$this->assertArrayNotHasKey($port, $processes, 'Port ' . $port . ' was already in use by a process.');
$processes[$port] = $this->instantiateServer($port);
$this->assertNotEmpty($processes[$port]);
$this->assertTrue($processes[$port]->isRunning(), 'Process on port ' . $port . ' is not still running.');
$this->assertFalse($this->checkPortIsAvailable($port));
}
// Clean up after ourselves.
foreach ($processes as $process) {
$process->stop();
}
}
/**
* @covers ::standUpServer
*/
public function testStandUpServer(): void {
// Stand up a server with working directory 'first'.
$this->standUpServer('first');
// Get the process object for the server.
$ref_process = new \ReflectionProperty(parent::class, 'serverProcess');
$first_process = $ref_process->getValue($this);
// Standing up the server again should not change the server process.
$this->standUpServer('first');
$this->assertSame($first_process, $ref_process->getValue($this));
// Standing up the server with working directory 'second' should give us a
// new server process.
$this->standUpServer('second');
$this->assertNotSame(
$first_process,
$second_process = $ref_process->getValue($this)
);
// And even with the original working directory name, we should get a new
// server process.
$this->standUpServer('first');
$this->assertNotSame($first_process, $ref_process->getValue($this));
$this->assertNotSame($second_process, $ref_process->getValue($this));
}
}

View File

@@ -0,0 +1,190 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Framework\Tests;
use Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait;
use PHPUnit\Framework\SkippedTestError;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
/**
* @coversDefaultClass \Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait
* @group Build
* @group legacy
*/
class ExternalCommandRequirementTest extends TestCase {
use ExpectDeprecationTrait;
/**
* @covers ::checkExternalCommandRequirements
*/
public function testCheckExternalCommandRequirementsNotAvailable(): void {
$this->expectDeprecation('Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait::checkExternalCommandRequirements() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$this->expectDeprecation('The \'@require externalCommand\' annotation for tests is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$requires = new UsesCommandRequirements();
$ref_check_requirements = new \ReflectionMethod($requires, 'checkExternalCommandRequirements');
// Use a try/catch block because otherwise PHPUnit might think this test is
// legitimately skipped.
try {
$ref_check_requirements->invokeArgs($requires, [
['externalCommand not_available', 'externalCommand available_command'],
]);
$this->fail('Unavailable external command requirement should throw a skipped test error exception.');
}
catch (SkippedTestError $exception) {
$this->assertEquals('Required external commands: not_available', $exception->getMessage());
}
}
/**
* @covers ::checkExternalCommandRequirements
*/
public function testCheckExternalCommandRequirementsAvailable(): void {
$this->expectDeprecation('Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait::checkExternalCommandRequirements() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$this->expectDeprecation('The \'@require externalCommand\' annotation for tests is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$requires = new UsesCommandRequirements();
$ref_check_requirements = new \ReflectionMethod($requires, 'checkExternalCommandRequirements');
// Use a try/catch block because otherwise PHPUnit might think this test is
// legitimately skipped.
try {
$this->assertNull(
$ref_check_requirements->invokeArgs($requires, [['externalCommand available_command']])
);
}
catch (SkippedTestError $exception) {
$this->fail(sprintf('The external command should be available: %s', $exception->getMessage()));
}
}
/**
* @covers ::checkClassCommandRequirements
*/
public function testClassRequiresAvailable(): void {
$this->expectDeprecation('Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait::checkClassCommandRequirements() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$requires = new ClassRequiresAvailable();
$ref_check = new \ReflectionMethod($requires, 'checkClassCommandRequirements');
// Use a try/catch block because otherwise PHPUnit might think this test is
// legitimately skipped.
try {
$this->assertNull($ref_check->invoke($requires));
}
catch (SkippedTestError $exception) {
$this->fail(sprintf('The external command should be available: %s', $exception->getMessage()));
}
}
/**
* @covers ::checkClassCommandRequirements
*/
public function testClassRequiresUnavailable(): void {
$this->expectDeprecation('Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait::checkClassCommandRequirements() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$requires = new ClassRequiresUnavailable();
$ref_check = new \ReflectionMethod($requires, 'checkClassCommandRequirements');
// Use a try/catch block because otherwise PHPUnit might think this test is
// legitimately skipped.
try {
$this->assertNull($ref_check->invoke($requires));
$this->fail('Unavailable external command requirement should throw a skipped test error exception.');
}
catch (SkippedTestError $exception) {
$this->assertEquals('Required external commands: unavailable_command', $exception->getMessage());
}
}
/**
* @covers ::checkMethodCommandRequirements
*/
public function testMethodRequiresAvailable(): void {
$this->expectDeprecation('Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait::checkMethodCommandRequirements() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$requires = new MethodRequires();
$ref_check = new \ReflectionMethod($requires, 'checkMethodCommandRequirements');
// Use a try/catch block because otherwise PHPUnit might think this test is
// legitimately skipped.
try {
$this->assertNull($ref_check->invoke($requires, 'testRequiresAvailable'));
}
catch (SkippedTestError $exception) {
$this->fail(sprintf('The external command should be available: %s', $exception->getMessage()));
}
}
/**
* @covers ::checkMethodCommandRequirements
*/
public function testMethodRequiresUnavailable(): void {
$this->expectDeprecation('Drupal\BuildTests\Framework\ExternalCommandRequirementsTrait::checkMethodCommandRequirements() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use Drupal\\TestTools\\Extension\\RequiresComposerTrait instead. See https://www.drupal.org/node/3362239');
$requires = new MethodRequires();
$ref_check = new \ReflectionMethod($requires, 'checkMethodCommandRequirements');
// Use a try/catch block because otherwise PHPUnit might think this test is
// legitimately skipped.
try {
$this->assertNull($ref_check->invoke($requires, 'testRequiresUnavailable'));
$this->fail('Unavailable external command requirement should throw a skipped test error exception.');
}
catch (SkippedTestError $exception) {
$this->assertEquals('Required external commands: unavailable_command', $exception->getMessage());
}
}
}
class UsesCommandRequirements {
use ExternalCommandRequirementsTrait;
protected static function externalCommandIsAvailable($command) {
return in_array($command, ['available_command']);
}
}
/**
* @requires externalCommand available_command
*/
class ClassRequiresAvailable {
use ExternalCommandRequirementsTrait;
protected static function externalCommandIsAvailable($command) {
return in_array($command, ['available_command']);
}
}
/**
* @requires externalCommand unavailable_command
*/
class ClassRequiresUnavailable {
use ExternalCommandRequirementsTrait;
}
class MethodRequires {
use ExternalCommandRequirementsTrait;
/**
* @requires externalCommand available_command
*/
public function testRequiresAvailable() {
}
/**
* @requires externalCommand unavailable_command
*/
public function testRequiresUnavailable() {
}
protected static function externalCommandIsAvailable($command) {
return in_array($command, ['available_command']);
}
}

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\Framework\Tests;
use Drupal\BuildTests\QuickStart\QuickStartTestBase;
use Drupal\sqlite\Driver\Database\sqlite\Install\Tasks;
/**
* @coversDefaultClass \Drupal\BuildTests\Framework\BuildTestBase
* @group Build
* @requires extension pdo_sqlite
*/
class HtRouterTest extends QuickStartTestBase {
/**
* @covers ::instantiateServer
*/
public function testHtRouter(): void {
$sqlite = (new \PDO('sqlite::memory:'))->query('select sqlite_version()')->fetch()[0];
if (version_compare($sqlite, Tasks::SQLITE_MINIMUM_VERSION) < 0) {
$this->markTestSkipped();
}
$this->copyCodebase();
$this->executeCommand('COMPOSER_DISCARD_CHANGES=true composer install --no-dev --no-interaction');
$this->assertErrorOutputContains('Generating autoload files');
$this->installQuickStart('minimal');
$this->formLogin($this->adminUsername, $this->adminPassword);
$this->visit('/.well-known/change-password');
$this->assertDrupalVisit();
$url = $this->getMink()->getSession()->getCurrentUrl();
$this->assertEquals('http://localhost:' . $this->getPortNumber() . '/user/1/edit', $url);
}
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\QuickStart;
use Drupal\BuildTests\Framework\BuildTestBase;
use Symfony\Component\Process\PhpExecutableFinder;
/**
* Helper methods for using the quickstart feature of Drupal.
*/
abstract class QuickStartTestBase extends BuildTestBase {
/**
* User name of the admin account generated during install.
*
* @var string
*/
protected $adminUsername;
/**
* Password of the admin account generated during install.
*
* @var string
*/
protected $adminPassword;
/**
* Install a Drupal site using the quick start feature.
*
* @param string $profile
* Drupal profile to install.
* @param string $working_dir
* (optional) A working directory relative to the workspace, within which to
* execute the command. Defaults to the workspace directory.
*/
public function installQuickStart($profile, $working_dir = NULL) {
$php_finder = new PhpExecutableFinder();
$install_process = $this->executeCommand($php_finder->find() . ' ./core/scripts/drupal install ' . $profile, $working_dir);
$this->assertCommandOutputContains('Username:');
preg_match('/Username: (.+)\vPassword: (.+)/', $install_process->getOutput(), $matches);
$this->assertNotEmpty($this->adminUsername = $matches[1]);
$this->assertNotEmpty($this->adminPassword = $matches[2]);
}
/**
* Helper that uses Drupal's user/login form to log in.
*
* @param string $username
* Username.
* @param string $password
* Password.
* @param string $working_dir
* (optional) A working directory within which to login. Defaults to the
* workspace directory.
*/
public function formLogin($username, $password, $working_dir = NULL) {
$this->visit('/user/login', $working_dir);
$assert = $this->getMink()->assertSession();
$assert->statusCodeEquals(200);
$assert->fieldExists('edit-name')->setValue($username);
$assert->fieldExists('edit-pass')->setValue($password);
$session = $this->getMink()->getSession();
$session->getPage()->findButton('Log in')->submit();
}
}

View File

@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Drupal\BuildTests\TestSiteApplication;
use Drupal\BuildTests\Framework\BuildTestBase;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\PhpExecutableFinder;
/**
* @group Build
* @group TestSiteApplication
*/
class InstallTest extends BuildTestBase {
public function testInstall(): void {
$this->copyCodebase();
$fs = new Filesystem();
$fs->chmod($this->getWorkspaceDirectory() . '/sites/default', 0700, 0000);
// Composer tells you stuff in error output.
$this->executeCommand('COMPOSER_DISCARD_CHANGES=true composer install --no-interaction');
$this->assertErrorOutputContains('Generating autoload files');
// We have to stand up the server first so we can know the port number to
// pass along to the install command.
$this->standUpServer();
$php_finder = new PhpExecutableFinder();
$install_command = [
$php_finder->find(),
'./core/scripts/test-site.php',
'install',
'--base-url=http://localhost:' . $this->getPortNumber(),
'--db-url=sqlite://localhost/foo.sqlite',
'--install-profile=minimal',
'--json',
];
$this->assertNotEmpty($output_json = $this->executeCommand(implode(' ', $install_command))->getOutput());
$this->assertCommandSuccessful();
$connection_details = json_decode($output_json, TRUE);
foreach (['db_prefix', 'user_agent', 'site_path'] as $key) {
$this->assertArrayHasKey($key, $connection_details);
}
// Visit paths with expectations.
$this->visit();
$this->assertDrupalVisit();
}
}