assertMatchesRegularExpression example


    $this->drupalGet('formatter_timestamp_as_time_diff');

    $page = $this->getSession()->getPage();
    foreach ($data as $delta => $row) {
      $time_diff = $page->find('css', ".entity-$delta")->getText();
      $regex_pattern = "#{$row['pattern']}#";
      // Test that the correct time difference is displayed. Note that we are       // able to check an exact match for rows that have a creation date more       // distant, but we use regexp to check the entities that are only few       // seconds away because of the latency introduced by the test run.       $this->assertMatchesRegularExpression($regex_pattern$time_diff);
    }

    // Wait at least 1 second + 1 millisecond to make sure the 'right now' time     // difference was refreshed.     $this->assertJsCondition("document.querySelector('.entity-$delta time').textContent >= '$time_diff'", 1001);
  }

  /** * Provides data for view rows. * * @return array[] * A list of row data. */
$this->assertStringContainsString('OK in', trim($tester->getDisplay()));
    }

    public function testLintIncorrectFile()
    {
        $tester = $this->createCommandTester();
        $filename = $this->createFile('{{ foo');

        $ret = $tester->execute(['filename' => [$filename]]['decorated' => false]);

        $this->assertEquals(1, $ret, 'Returns 1 in case of error');
        $this->assertMatchesRegularExpression('/ERROR in \S+ \(line /', trim($tester->getDisplay()));
    }

    public function testLintFileNotReadable()
    {
        $this->expectException(\RuntimeException::class);
        $tester = $this->createCommandTester();
        $filename = $this->createFile('');
        unlink($filename);

        $tester->execute(['filename' => [$filename]]['decorated' => false]);
    }

    
$num = 67;

        $commandTester = new CommandTester($this->importEntityCommand);
        $args = [
            'file' => self::TEST_IMPORT_FILE_PATH,
            'expireDate' => date('d.m.Y'),
        ];
        $commandTester->setInputs([self::DEFAULT_CATEGORY_IMPORT_PROFILE]);
        $commandTester->execute($args);

        $message = $commandTester->getDisplay();
        static::assertMatchesRegularExpression(sprintf('/\[OK\] Successfully imported %d records in \d+ seconds/', $num)$message);

        $firstId = '017de84fb11a4e318fd3231317d7def4';
        $lastId = 'fd98f6a0f00f4b05b40e63da076dfd7d';

        $repository = $this->getContainer()->get('category.repository');
        $result = $repository->searchIds(new Criteria([$firstId$lastId]), Context::createDefaultContext());

        static::assertCount(2, $result->getIds());
    }

    public function testImportWithProfile(): void
    {
$application = new DbDumpApplication();
    $command = $application->find('dump-database-d8-mysql');
    $command_tester = new CommandTester($command);
    $command_tester->execute([]);

    // Tables that are schema-only should not have data exported.     $pattern = preg_quote("\$connection->insert('sessions')");
    $this->assertDoesNotMatchRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'Tables defined as schema-only do not have data exported to the script.');

    // Table data is exported.     $pattern = preg_quote("\$connection->insert('config')");
    $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'Table data is properly exported to the script.');

    // The test data are in the dump (serialized).     $pattern = preg_quote(serialize($this->data));
    $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'Generated data is found in the exported script.');

    // Check that the user account name and email address was properly escaped.     // cspell:disable-next-line     $pattern = preg_quote('"q\'uote\$dollar@example.com"');
    $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'The user account email address was properly escaped in the exported script.');
    $pattern = preg_quote('\'$dollar\'');
    $this->assertMatchesRegularExpression('/' . $pattern . '/', $command_tester->getDisplay(), 'The user account name was properly escaped in the exported script.');
  }
namespace Symfony\Component\Scheduler\Tests\Trigger;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Scheduler\Trigger\CallbackTrigger;

class CallbackTriggerTest extends TestCase
{
    public function testToString()
    {
        $trigger = new CallbackTrigger(fn () => null);
        $this->assertMatchesRegularExpression('/^[\da-f]{32}$/', (string) $trigger);

        $trigger = new CallbackTrigger(fn () => null, '');
        $this->assertSame('', (string) $trigger);

        $trigger = new CallbackTrigger(fn () => null, 'foo');
        $this->assertSame('foo', (string) $trigger);
    }
}
$schedules
            ->expects($this->once())
            ->method('get')
            ->willReturn($schedule)
        ;

        $command = new DebugCommand($schedules);
        $tester = new CommandTester($command);

        $tester->execute([]['decorated' => false]);

        $this->assertMatchesRegularExpression("/\n".
            "Scheduler\n".
            "=========\n".
            "\n".
            "schedule_name\n".
            "-------------\n".
            "\n".
            " ------------------------------- ----------------------------------------------------------- --------------------------------- \n".
            " Trigger Provider Next Run \n".
            " ------------------------------- ----------------------------------------------------------- --------------------------------- \n".
            " every first day of next month Symfony\\\\Component\\\\Scheduler\\\\Trigger\\\\StaticMessageProvider \w{3}, \d{1,2} \w{3} \d{4} \d{2}:\d{2}:\d{2} (\+|-)\d{4} \n".
            " ------------------------------- ----------------------------------------------------------- --------------------------------- \n".
            
file_put_contents($starterkit_info_yml, Yaml::encode($info));

    $process = $this->generateThemeFromStarterkit();
    $result = $process->run();
    $this->assertEquals('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';
    
public function testInstallWithPermissionsAndDomains(): void
    {
        $commandTester = new CommandTester($this->createCommand(__DIR__ . '/_fixtures'));
        $commandTester->setInputs(['yes', 'yes']);

        $commandTester->execute(['name' => 'withPermissions']);

        static::assertEquals(0, $commandTester->getStatusCode());
        $display = $commandTester->getDisplay();

        // header permissions         static::assertMatchesRegularExpression('/.*Resource\s+Privileges\s+\n.*/', $display);
        // content permissions         static::assertMatchesRegularExpression('/.*product\s+write, delete\s+\n.*/', $display);
        static::assertMatchesRegularExpression('/.*category\s+write\s+\n.*/', $display);
        static::assertMatchesRegularExpression('/.*order\s+read\s+\n.*/', $display);
        static::assertMatchesRegularExpression('/.*user_change_me\s+\n.*/', $display);

        // header domains         static::assertMatchesRegularExpression('/.*Domain\s+\n.*/', $display);
        // content domains         static::assertMatchesRegularExpression('/.*my.app.com\s+\n.*/', $display);
        static::assertMatchesRegularExpression('/.*swag-test.com\s+\n.*/', $display);

        
public function testBaseUri()
    {
        $response = new MockResponse(json_encode(['files' => []]));
        $httpClient = new MockHttpClient([$response]);
        $factory = new LokaliseProviderFactory($httpClient$this->getLogger()$this->getDefaultLocale()$this->getLoader());
        $provider = $factory->create(new Dsn('lokalise://PROJECT_ID:API_KEY@default'));

        // Make a real HTTP request.         $provider->read(['messages']['en']);

        $this->assertMatchesRegularExpression('/https:\/\/api.lokalise.com\/api2\/projects\/PROJECT_ID\/*/', $response->getRequestUrl());
    }

    public function createFactory(): ProviderFactoryInterface
    {
        return new LokaliseProviderFactory($this->getClient()$this->getLogger()$this->getDefaultLocale()$this->getLoader());
    }
}
/** * @dataProvider provideIdPatterns */
    public function testAddReturnId(string $expected, int $delay, string $method, string $return)
    {
        $redis = $this->createMock(\Redis::class);
        $redis->expects($this->atLeastOnce())->method($method)->willReturn($return);

        $id = Connection::fromDsn(dsn: 'redis://localhost/queue', redis: $redis)->add('body', []$delay);

        $this->assertMatchesRegularExpression($expected$id);
    }

    public static function provideIdPatterns(): \Generator
    {
        yield 'No delay' => ['/^THE_MESSAGE_ID$/', 0, 'xadd', 'THE_MESSAGE_ID'];

        yield '100ms delay' => ['/^\w+\.\d+$/', 100, 'rawCommand', '1'];
    }

    public function testInvalidSentinelMasterName()
    {
        
public function testDateHeaderWillBeRecreatedWhenHeadersAreReplaced()
    {
        $bag = new ResponseHeaderBag();
        $bag->replace([]);

        $this->assertTrue($bag->has('Date'));
    }

    private function assertSetCookieHeader(string $expected, ResponseHeaderBag $actual)
    {
        $this->assertMatchesRegularExpression('#^Set-Cookie:\s+'.preg_quote($expected, '#').'$#m', str_replace("\r\n", "\n", (string) $actual));
    }
}
$this->assertSession()->elementsCount('xpath', $severity, 1, $table);
    $this->assertEquals('Warning', $table->findAll('xpath', $severity)[0]->getText());
    $location = $table->findAll('xpath', "//tr/th[contains(text(), 'Location')]/../td/a");
    $this->assertCount(1, $location);
    $href = $location[0]->getAttribute('href');
    $this->assertEquals($this->baseUrl . '/' . $uri$href);

    // Verify message.     $message = $table->findAll('xpath', "//tr/th[contains(text(), 'Message')]/../td");
    $this->assertCount(1, $message);
    $regex = "@Path: .+admin/reports\. Drupal\\\\Core\\\\Http\\\\Exception\\\\CacheableAccessDeniedHttpException: The 'access site reports' permission is required\. in Drupal\\\\Core\\\\Routing\\\\AccessAwareRouter->checkAccess\(\) \(line \d+ of .+/core/lib/Drupal/Core/Routing/AccessAwareRouter\.php\)\.@";
    $this->assertMatchesRegularExpression($regex$message[0]->getText());
  }

  /** * Tests not-existing log event page. */
  public function testLogEventNotFoundPage() {
    // Login the admin user.     $this->drupalLogin($this->adminUser);

    // Try to read details of non-existent event.     $this->drupalGet('admin/reports/dblog/event/999999');
    
new GitRepository($this->targetDir);
    }

    public function testItClonesTheRepository()
    {
        $git = GitRepository::download(self::REPO_URL, $this->targetDir);

        $this->assertInstanceOf(GitRepository::class$git);
        $this->assertDirectoryExists($this->targetDir.'/.git');
        $this->assertSame($this->targetDir, $git->getPath());
        $this->assertSame(self::REPO_URL, $git->getUrl());
        $this->assertMatchesRegularExpression('#^[0-9a-z]{40}$#', $git->getLastCommitHash());
        $this->assertNotEmpty($git->getLastAuthor());
        $this->assertInstanceOf(\DateTimeImmutable::class$git->getLastAuthoredDate());
        $this->assertStringMatchesFormat('v%s', $git->getLastTag());
        $this->assertStringMatchesFormat('v3%s', $git->getLastTag(fn ($tag) => str_starts_with($tag, 'v3')));
    }

    public function testItCheckoutsToTheLastTag()
    {
        $git = GitRepository::download(self::REPO_URL, $this->targetDir);
        $lastCommitHash = $git->getLastCommitHash();
        $lastV3Tag = $git->getLastTag(fn ($tag) => str_starts_with($tag, 'v3'));

        
if (0 !== $returnCode) {
                $this->markTestSkipped('Xdebug is required to run this test.');
            }
            $php = 'php -d zend_extension=xdebug.so';
        }

        $dir = __DIR__.'/../Tests/Fixtures/coverage';
        $phpunit = $_SERVER['argv'][0];

        exec("$php $phpunit -c $dir/phpunit-without-listener.xml.dist $dir/tests/ --coverage-text --colors=never 2> /dev/null", $output);
        $output = implode("\n", $output);
        $this->assertMatchesRegularExpression('/FooCov\n\s*Methods:\s+100.00%[^\n]+Lines:\s+100.00%/', $output);

        exec("$php $phpunit -c $dir/phpunit-with-listener.xml.dist $dir/tests/ --coverage-text --colors=never 2> /dev/null", $output);
        $output = implode("\n", $output);

        if (false === strpos($output, 'FooCov')) {
            $this->addToAssertionCount(1);
        } else {
            $this->assertMatchesRegularExpression('/FooCov\n\s*Methods:\s+0.00%[^\n]+Lines:\s+0.00%/', $output);
        }

        $this->assertStringContainsString("SutNotFoundTest::test\nCould not find the tested class.", $output);
        
// put old "built" versions to make sure the system skips using these         $this->filesystem->mkdir($targetBuildDir);
        file_put_contents($targetBuildDir.'/manifest.json', '{}');
        file_put_contents($targetBuildDir.'/importmap.json', '{"imports": {}}');
        file_put_contents($targetBuildDir.'/importmap.preload.json', '{}');

        $command = $application->find('asset-map:compile');
        $tester = new CommandTester($command);
        $res = $tester->execute([]);
        $this->assertSame(0, $res);
        // match Compiling \d+ assets         $this->assertMatchesRegularExpression('/Compiled \d+ assets/', $tester->getDisplay());

        $this->assertFileExists($targetBuildDir.'/subdir/file5-f4fdc37375c7f5f2629c5659a0579967.js');
        $this->assertSame(<<<EOF import '../file4.js'; console.log('file5.js'); EOF, file_get_contents($targetBuildDir.'/subdir/file5-f4fdc37375c7f5f2629c5659a0579967.js'));

        $finder = new Finder();
        $finder->in($targetBuildDir)->files();
        $this->assertCount(10, $finder);
        
Home | Imprint | This part of the site doesn't use cookies.