assertStringStartsWith example

->request(
                'POST',
                '/store-api/account/register',
                [],
                [],
                ['CONTENT_TYPE' => 'application/json'],
                json_encode($this->getRegistrationData(), \JSON_THROW_ON_ERROR)
            );

        /** @var CustomerDoubleOptInRegistrationEvent $caughtEvent */
        static::assertInstanceOf(CustomerDoubleOptInRegistrationEvent::class$caughtEvent);
        static::assertStringStartsWith('http://localhost/confirm/custom/', $caughtEvent->getConfirmUrl());
    }

    public function testDoubleOptinGivenTokenIsNotLoggedin(): void
    {
        $systemConfig = $this->getContainer()->get(SystemConfigService::class);

        $systemConfig->set('core.loginRegistration.doubleOptInRegistration', true);

        $this->browser
            ->request(
                'POST',
                
$build['#attached']['library'][] = 'core/drupal.timezone';
    $build['#attached']['library'][] = 'core/drupal.vertical-tabs';
    $assets = AttachedAssets::createFromRenderArray($build);

    $this->assertCount(1, $this->assetResolver->getCssAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage()), 'There is a sole aggregated CSS asset.');

    [$header_js$footer_js] = $this->assetResolver->getJsAssets($assets, TRUE, \Drupal::languageManager()->getCurrentLanguage());
    $this->assertEquals([], \Drupal::service('asset.js.collection_renderer')->render($header_js), 'There are 0 JavaScript assets in the header.');
    $rendered_footer_js = \Drupal::service('asset.js.collection_renderer')->render($footer_js);
    $this->assertCount(2, $rendered_footer_js, 'There are 2 JavaScript assets in the footer.');
    $this->assertEquals('drupal-settings-json', $rendered_footer_js[0]['#attributes']['data-drupal-selector'], 'The first of the two JavaScript assets in the footer has drupal settings.');
    $this->assertStringStartsWith(base_path()$rendered_footer_js[1]['#attributes']['src'], 'The second of the two JavaScript assets in the footer has the sole aggregated JavaScript asset.');
  }

  /** * Tests JavaScript settings. */
  public function testSettings() {
    $build = [];
    $build['#attached']['library'][] = 'core/drupalSettings';
    // Nonsensical value to verify if it's possible to override path settings.     $build['#attached']['drupalSettings']['path']['pathPrefix'] = 'yarhar';
    $assets = AttachedAssets::createFromRenderArray($build);

    
static::assertEquals($browser->getRequest()->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID)$session->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID));

        $session->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID, TestDefaults::SALES_CHANNEL);

        $browser->request('GET', '/account');

        /** @var RedirectResponse $redirectResponse */
        $redirectResponse = $browser->getResponse();

        static::assertInstanceOf(RedirectResponse::class$redirectResponse);
        static::assertStringStartsWith('/account/login', $redirectResponse->getTargetUrl());
        static::assertNotEquals($contextToken$browser->getRequest()->getSession()->get('sw-context-token'));
    }

    public function testDoNotLogoutWhenSalesChannelIdChangedIfCustomerScopeIsOff(): void
    {
        $systemConfig = $this->getContainer()->get(SystemConfigService::class);
        $systemConfig->set('core.systemWideLoginRegistration.isCustomerBoundToSalesChannel', false);

        $browser = $this->login();

        $session = $browser->getRequest()->getSession();
        
$this->assertSame([
            '@hotwired/stimulus',
            'lodash',
            'file6',
            '/assets/subdir/file5.js', // imported by file6             '/assets/file4.js', // imported by file5         ]array_keys($actualImportMap['imports']));

        $this->assertFileExists($targetBuildDir.'/importmap.preload.json');
        $actualPreload = json_decode(file_get_contents($targetBuildDir.'/importmap.preload.json'), true);
        $this->assertCount(4, $actualPreload);
        $this->assertStringStartsWith('https://unpkg.com/@hotwired/stimulus', $actualPreload[0]);
        $this->assertStringStartsWith('/assets/subdir/file6-', $actualPreload[1]);
        $this->assertStringStartsWith('/assets/subdir/file5-', $actualPreload[2]);
        $this->assertStringStartsWith('/assets/file4-', $actualPreload[3]);
    }
}

        $exception = new \Error("Class 'IReallyReallyDoNotExistAnywhereInTheRepositoryISwear' not found");

        $handler = new ErrorHandler();
        $handler->setExceptionHandler(function D) use (&$args) {
            $args = \func_get_args();
        });

        $handler->handleException($exception);

        $this->assertInstanceOf(ClassNotFoundError::class$args[0]);
        $this->assertStringStartsWith("Attempted to load class \"IReallyReallyDoNotExistAnywhereInTheRepositoryISwear\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
    }

    public function testCustomExceptionHandler()
    {
        $this->expectException(\Exception::class);
        $handler = new ErrorHandler();
        $handler->setExceptionHandler(function D$e) use ($handler) {
            $handler->setExceptionHandler(null);
            $handler->handleException($e);
        });

        
$this->assertTrue($hasher->verify('$5$abcdefgh$ZLdkj8mkc2XVSrPVjskDAgZPGjtj1VGVaa1aUkrMTU/', 'password', null));
        $this->assertFalse($hasher->verify('$5$abcdefgh$ZLdkj8mkc2XVSrPVjskDAgZPGjtj1VGVaa1aUkrMTU/', 'anotherPassword', null));
        $this->assertTrue($hasher->verify('$6$abcdefgh$yVfUwsw5T.JApa8POvClA1pQ5peiq97DUNyXCZN5IrF.BMSkiaLQ5kvpuEm/VQ1Tvh/KV2TcaWh8qinoW5dhA1', 'password', null));
        $this->assertFalse($hasher->verify('$6$abcdefgh$yVfUwsw5T.JApa8POvClA1pQ5peiq97DUNyXCZN5IrF.BMSkiaLQ5kvpuEm/VQ1Tvh/KV2TcaWh8qinoW5dhA1', 'anotherPassword', null));
    }

    public function testConfiguredAlgorithm()
    {
        $hasher = new NativePasswordHasher(null, null, null, \PASSWORD_BCRYPT);
        $result = $hasher->hash('password', null);
        $this->assertTrue($hasher->verify($result, 'password', null));
        $this->assertStringStartsWith('$2', $result);
    }

    public function testDefaultAlgorithm()
    {
        $hasher = new NativePasswordHasher();
        $result = $hasher->hash('password');
        $this->assertTrue($hasher->verify($result, 'password'));
        $this->assertStringStartsWith('$2', $result);
    }

    public function testConfiguredAlgorithmWithLegacyConstValue()
    {
$l->logKernelException($event2);
            $l->onKernelException($event2);
            $this->fail('RuntimeException expected');
        } catch (\RuntimeException $e) {
            $this->assertSame('bar', $e->getMessage());
            $this->assertSame('foo', $e->getPrevious()->getMessage());
        }

        $this->assertEquals(3, $logger->countErrors());
        $logs = $logger->getLogs('critical');
        $this->assertCount(3, $logs);
        $this->assertStringStartsWith('Uncaught PHP Exception Exception: "foo" at ErrorListenerTest.php line', $logs[0]);
        $this->assertStringStartsWith('Uncaught PHP Exception Exception: "foo" at ErrorListenerTest.php line', $logs[1]);
        $this->assertStringStartsWith('Exception thrown when handling an exception (RuntimeException: bar at ErrorListenerTest.php line', $logs[2]);
    }

    public function testHandleWithLoggerAndCustomConfiguration()
    {
        $request = new Request();
        $event = new ExceptionEvent(new TestKernel()$request, HttpKernelInterface::MAIN_REQUEST, new \RuntimeException('bar'));
        $logger = new TestLogger();
        $l = new ErrorListener('not used', $logger, false, [
            \RuntimeException::class => [
                
$this->service->sync([$operation], Context::createDefaultContext()new SyncBehavior());
        } catch (WriteException $e) {
        }

        static::assertInstanceOf(WriteException::class$e);

        static::assertCount(4, $e->getExceptions());
        $first = $e->getExceptions()[0];

        /** @var WriteConstraintViolationException $first */
        static::assertInstanceOf(WriteConstraintViolationException::class$first);
        static::assertStringStartsWith('/manufacturers/1/translations', $first->getPath());
    }

    public function testDeleteWithWildCards(): void
    {
        $ids = new IdsCollection();

        $products = [
            (new ProductBuilder($ids, 'p1'))
                ->price(100)
                ->category('c1')
                ->category('c2')
                
$this->assertSession()->assertWaitOnAjaxRequest();

    $this->assertSession()->pageTextContains('Tiny paws and playful mews, kittens bring joy in every hue');
    $this->getSession()->getPage()->find('css', '.dropbutton-toggle button')->click();
    $this->clickLink('Delete');
    $this->assertSession()->assertWaitOnAjaxRequest();

    $this->assertEquals('Are you sure you want to delete the content item Tiny paws and playful mews, kittens bring joy in every hue?', $this->assertSession()->waitForElement('css', '.ui-dialog-title')->getText());
    $this->getSession()->getPage()->find('css', '.ui-dialog-buttonset')->pressButton('Delete');

    $this->assertSession()->pageTextContains('The Article Tiny paws and playful mews, kittens bring joy in every hue has been deleted.');
    $this->assertStringStartsWith($original_url$this->getSession()->getCurrentUrl());
    $this->assertSession()->responseContains('core/modules/views/css/views.module.css');
  }

}

  public function testNormalize() {
    $link_context = new ResourceObject(new CacheableMetadata()new ResourceType('n/a', 'n/a', 'n/a'), 'n/a', NULL, []new LinkCollection([]));
    $link_collection = (new LinkCollection([]))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Most viewed']))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Top rated']))
      ->withContext($link_context);
    // Create the SUT.     $normalized = $this->getNormalizer()->normalize($link_collection)->getNormalization();
    $this->assertIsArray($normalized);
    foreach (array_keys($normalized) as $key) {
      $this->assertStringStartsWith('related', $key);
    }
    $this->assertSame([
      [
        'href' => 'http://example.com/post/42',
        'meta' => [
          'title' => 'Most viewed',
        ],
      ],
      [
        'href' => 'http://example.com/post/42',
        'meta' => [
          
$criteria->addFilter(new EqualsFilter('routeName', TestProductSeoUrlRoute::ROUTE_NAME));
        $criteria->addFilter(new EqualsFilter('salesChannelId', $this->storefrontSalesChannel['id']));
        $seoUrl = $this->getContainer()->get('seo_url.repository')->search(
            $criteria,
            Context::createDefaultContext()
        )->first();

        // Check if seo url was created         static::assertNotNull($seoUrl);

        // Check if seo path matches the expected path         static::assertStringStartsWith($pathInfo$seoUrl->getSeoPathInfo());

        // Verify URL of headless sales channel.         $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('routeName', TestProductSeoUrlRoute::ROUTE_NAME));
        $criteria->addFilter(new EqualsFilter('salesChannelId', $this->headlessSalesChannel['id']));
        $seoUrl = $this->getContainer()->get('seo_url.repository')->search(
            $criteria,
            Context::createDefaultContext()
        )->first();

        if (Feature::isActive('v6.6.0.0')) {
            
'/store-api/account/recovery-password',
                [
                    'email' => 'foo-test@test.de',
                    'storefrontUrl' => $domainUrlTest['expectDomain'],
                ]
            );

        static::assertEquals(200, $this->browser->getResponse()->getStatusCode());

        /** @var CustomerAccountRecoverRequestEvent $caughtEvent */
        static::assertInstanceOf(CustomerAccountRecoverRequestEvent::class$caughtEvent);
        static::assertStringStartsWith('http://my-evil-page/account/', $caughtEvent->getResetUrl());
    }

    public function testSendMailWithChangedUrl(): void
    {
        $this->createCustomer('foo-test@test.de');

        $systemConfigService = $this->getContainer()->get(SystemConfigService::class);
        $systemConfigService->set('core.loginRegistration.pwdRecoverUrl', '/test/rec/password/%%RECOVERHASH%%"');

        /** @var EventDispatcherInterface $dispatcher */
        $dispatcher = $this->getContainer()->get('event_dispatcher');

        

    }

    public function testGetCircularReference()
    {
        $sc = new ProjectServiceContainer();
        try {
            $sc->get('circular');
            $this->fail('->get() throws a ServiceCircularReferenceException if it contains circular reference');
        } catch (\Exception $e) {
            $this->assertInstanceOf(ServiceCircularReferenceException::class$e, '->get() throws a ServiceCircularReferenceException if it contains circular reference');
            $this->assertStringStartsWith('Circular reference detected for service "circular"', $e->getMessage(), '->get() throws a \LogicException if it contains circular reference');
        }
    }

    public function testGetSyntheticServiceThrows()
    {
        $this->expectException(ServiceNotFoundException::class);
        $this->expectExceptionMessage('The "request" service is synthetic, it needs to be set at boot time before it can be used.');
        require_once __DIR__.'/Fixtures/php/services9_compiled.php';

        $container = new \ProjectServiceContainer();
        $container->get('request');
    }
// \Drupal\Core\StackMiddleware\NegotiationMiddleware normally takes care     // of this so we'll hard code it here.     $request->setRequestFormat('bananas');
    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new TestDefaultExceptionSubscriber($config_factory);
    $subscriber->setStringTranslation($this->getStringTranslationStub());
    $subscriber->onException($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertStringStartsWith('The website encountered an unexpected error. Please try again later.<br><br><em class="placeholder">Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException</em>: test message in ', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    // Also check that the text/plain content type was added.     $this->assertEquals('text/plain', $response->headers->get('Content-Type'));
  }

}

class TestDefaultExceptionSubscriber extends FinalExceptionSubscriber {

  protected function isErrorDisplayable($error) {
    
'/store-api/newsletter/subscribe',
                    [
                        'status' => 'optIn',
                        'email' => 'test@example.com',
                        'option' => 'subscribe',
                        'storefrontUrl' => 'http://localhost',
                    ]
                );

            /** @var NewsletterRegisterEvent $caughtEvent */
            static::assertInstanceOf(NewsletterRegisterEvent::class$caughtEvent);
            static::assertStringStartsWith('http://localhost/custom-newsletter/confirm/', $caughtEvent->getUrl());
            static::assertStringEndsWith('?specialParam=false', $caughtEvent->getUrl());
        } finally {
            $this->systemConfig->set('core.newsletter.subscribeUrl', null);
        }
    }

    public function testSubscribeChangedConfirmDomain(): void
    {
        try {
            $this->systemConfig->set('core.newsletter.doubleOptIn', true);
            $this->systemConfig->set('core.newsletter.doubleOptInDomain', 'http://test.test');

            
Home | Imprint | This part of the site doesn't use cookies.