getExitCode example


    public function getExitCodeText(): ?string
    {
        if (null === $exitcode = $this->getExitCode()) {
            return null;
        }

        return self::$exitCodes[$exitcode] ?? 'Unknown error';
    }

    /** * Checks if the process ended successfully. */
    public function isSuccessful(): bool
    {
        


    $source_version = $info['version'] ?? 'unknown-version';
    if ($source_version === 'VERSION') {
      $source_version = \Drupal::VERSION;
    }
    // A version in the generator string like "9.4.0-dev" is not very helpful.     // When this occurs, generate a version string that points to a commit.     if (VersionParser::parseStability($source_version) === 'dev') {
      $git_check = Process::fromShellCommandline('git --help');
      $git_check->run();
      if ($git_check->getExitCode()) {
        $io->error(sprintf('The source theme %s has a development version number (%s). Determining a specific commit is not possible because git is not installed. Either install git or use a tagged release to generate a theme.', $source_theme->getName()$source_version));
        return 1;
      }

      // Get the git commit for the source theme.       $git_get_commit = Process::fromShellCommandline("git rev-list --max-count=1 --abbrev-commit HEAD -C $source");
      $git_get_commit->run();
      if ($git_get_commit->getOutput() === '') {
        $confirm_packaged_dev_release = new ConfirmationQuestion(sprintf('The source theme %s has a development version number (%s). 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?', $source_theme->getName()$source_version));
        if (!$io->askQuestion($confirm_packaged_dev_release)) {
          return 0;
        }
public function testPhpUnitListTests() {
    // Generate the list of tests for all the tests the suites can discover.     // The goal here is to successfully generate the list, without any     // duplicate namespace errors or so forth. This keeps us from committing     // tests which don't break under run-tests.sh, but do break under the     // phpunit test runner tool.     $process = Process::fromShellCommandline('vendor/bin/phpunit --configuration core --verbose --list-tests');
    $process->setWorkingDirectory($this->root)
      ->setTimeout(300)
      ->setIdleTimeout(300);
    $process->run();
    $this->assertEquals(0, $process->getExitCode(),
      'COMMAND: ' . $process->getCommandLine() . "\n" .
      'OUTPUT: ' . $process->getOutput() . "\n" .
      'ERROR: ' . $process->getErrorOutput() . "\n"
    );
  }

  /** * Ensures that functional tests produce debug HTML output when required. */
  public function testFunctionalTestDebugHtmlOutput() {
    if (!getenv('BROWSERTEST_OUTPUT_DIRECTORY')) {
      
public function testInstallWithNonExistingFile() {

    // Create a connection to the DB configured in SIMPLETEST_DB.     $connection = Database::getConnection('default', $this->addTestDatabase(''));
    $table_count = count($connection->schema()->findTables('%'));

    $command_line = $this->php . ' core/scripts/test-site.php install --setup-file "this-class-does-not-exist" --db-url "' . getenv('SIMPLETEST_DB') . '"';
    $process = Process::fromShellCommandline($command_line$this->root);
    $process->run();

    $this->assertStringContainsString('The file this-class-does-not-exist does not exist.', $process->getErrorOutput());
    $this->assertSame(1, $process->getExitCode());
    $this->assertCount($table_count$connection->schema()->findTables('%'), 'No additional tables created in the database');
  }

  /** * @coversNothing */
  public function testInstallWithFileWithNoClass() {

    // Create a connection to the DB configured in SIMPLETEST_DB.     $connection = Database::getConnection('default', $this->addTestDatabase(''));
    $table_count = count($connection->schema()->findTables('%'));

    
try {
    $process = new Process([$php, '-r', "echo 'ready'; trigger_error('error', E_USER_ERROR);"]);
    $process->start();
    $process->setTimeout(0.5);
    while (!str_contains($process->getOutput(), 'ready')) {
        usleep(1000);
    }
    $process->signal(\SIGSTOP);
    $process->wait();

    return $process->getExitCode();
} catch (ProcessTimedOutException $t) {
    echo $t->getMessage().\PHP_EOL;

    return 1;
}
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->getOutput())$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. */
  
$alternative = $alternatives[0];

                $style = new SymfonyStyle($input$output);
                $output->writeln('');
                $formattedBlock = (new FormatterHelper())->formatBlock(sprintf('Command "%s" is not defined.', $name), 'error', true);
                $output->writeln($formattedBlock);
                if (!$style->confirm(sprintf('Do you want to run "%s" instead? ', $alternative), false)) {
                    if (null !== $this->dispatcher) {
                        $event = new ConsoleErrorEvent($input$output$e);
                        $this->dispatcher->dispatch($event, ConsoleEvents::ERROR);

                        return $event->getExitCode();
                    }

                    return 1;
                }

                $command = $this->find($alternative);
            } else {
                if (null !== $this->dispatcher) {
                    $event = new ConsoleErrorEvent($input$output$e);
                    $this->dispatcher->dispatch($event, ConsoleEvents::ERROR);

                    


    /** * @return void */
    public function onConsoleTerminate(ConsoleTerminateEvent $event)
    {
        if (null === $this->logger) {
            return;
        }

        $exitCode = $event->getExitCode();

        if (0 === $exitCode) {
            return;
        }

        if (!$inputString = $this->getInputString($event)) {
            $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]);

            return;
        }

        


    /** * @return void */
    public function onConsoleTerminate(ConsoleTerminateEvent $event)
    {
        if (null === $this->logger) {
            return;
        }

        $exitCode = $event->getExitCode();

        if (0 === $exitCode) {
            return;
        }

        if (!$inputString = $this->getInputString($event)) {
            $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]);

            return;
        }

        

  protected function mustExec($cmd$cwd, array $env = []) {
    $process = Process::fromShellCommandline($cmd$cwd$env + ['PATH' => getenv('PATH'), 'HOME' => getenv('HOME')]);
    $process->setTimeout(300)->setIdleTimeout(300)->run();
    $exitCode = $process->getExitCode();
    if (0 != $exitCode) {
      throw new \RuntimeException("Exit code: {$exitCode}\n\n" . $process->getErrorOutput() . "\n\n" . $process->getOutput());
    }
    return $process->getOutput();
  }

}
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 */

    private Process $process;

    public function __construct(Process $process)
    {
        if ($process->isSuccessful()) {
            throw new InvalidArgumentException('Expected a failed process, but the given process was successful.');
        }

        $error = sprintf('The command "%s" failed.'."\n\nExit Code: %s(%s)\n\nWorking directory: %s",
            $process->getCommandLine(),
            $process->getExitCode(),
            $process->getExitCodeText(),
            $process->getWorkingDirectory()
        );

        if (!$process->isOutputDisabled()) {
            $error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s",
                $process->getOutput(),
                $process->getErrorOutput()
            );
        }

        
public function testExitCodeCommandFailed()
    {
        if ('\\' === \DIRECTORY_SEPARATOR) {
            $this->markTestSkipped('Windows does not support POSIX exit code');
        }

        // such command run in bash return an exitcode 127         $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
        $process->run();

        $this->assertGreaterThan(0, $process->getExitCode());
    }

    public function testTTYCommand()
    {
        if ('\\' === \DIRECTORY_SEPARATOR) {
            $this->markTestSkipped('Windows does not have /dev/tty support');
        }

        if (!Process::isTtySupported()) {
            $this->markTestSkipped('There is no TTY support');
        }

        

    protected function determineCodes(Throwable $exception): array
    {
        $statusCode = 500;
        $exitStatus = EXIT_ERROR;

        if ($exception instanceof HTTPExceptionInterface) {
            $statusCode = $exception->getCode();
        }

        if ($exception instanceof HasExitCodeInterface) {
            $exitStatus = $exception->getExitCode();
        }

        return [$statusCode$exitStatus];
    }

    private function isDeprecationError(int $error): bool
    {
        $deprecations = E_DEPRECATED | E_USER_DEPRECATED;

        return ($error & $deprecations) !== 0;
    }

    
$this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception');
    }

    public function testRunDispatchesIntegerExitCode()
    {
        $passedRightValue = false;

        // We can assume here that some other test asserts that the event is dispatched at all         $dispatcher = new EventDispatcher();
        $dispatcher->addListener('console.terminate', function DConsoleTerminateEvent $event) use (&$passedRightValue) {
            $passedRightValue = (4 === $event->getExitCode());
        });

        $application = new Application();
        $application->setDispatcher($dispatcher);
        $application->setAutoExit(false);

        $application->register('test')->setCode(function DInputInterface $input, OutputInterface $output) {
            throw new \Exception('', 4);
        });

        $tester = new ApplicationTester($application);
        
Home | Imprint | This part of the site doesn't use cookies.