assertThat example


    public function assertJSONFragment(array $fragment, bool $strict = false)
    {
        $json = json_decode($this->getJSON(), true);
        $this->assertIsArray($json, 'Response does not have valid json');
        $patched = array_replace_recursive($json$fragment);

        if ($strict) {
            $this->assertSame($json$patched, 'Response does not contain a matching JSON fragment.');
        } else {
            $this->assertThat($patchednew IsEqual($json), 'Response does not contain a matching JSON fragment.');
        }
    }

    /** * Asserts that the JSON exactly matches the passed in data. * If the value being passed in is a string, it must be a json_encoded string. * * @param array|object|string $test * * @throws Exception */
    

    public function getStatusCode(): int
    {
        return $this->statusCode ?? throw new \RuntimeException('Status code not initialized, did you execute the command before requesting the status code?');
    }

    public function assertCommandIsSuccessful(string $message = ''): void
    {
        Assert::assertThat($this->statusCode, new CommandIsSuccessful()$message);
    }

    /** * Sets the user inputs. * * @param array $inputs An array of strings representing each input * passed to the command input stream * * @return $this */
    public function setInputs(array $inputs)static
    {
public static function assertBrowserCookieValueSame(string $name, string $expectedValue, bool $raw = false, string $path = '/', string $domain = null, string $message = ''): void
    {
        self::assertThatForClient(LogicalAnd::fromConstraints(
            new BrowserKitConstraint\BrowserHasCookie($name$path$domain),
            new BrowserKitConstraint\BrowserCookieValueSame($name$expectedValue$raw$path$domain)
        )$message);
    }

    public static function assertRequestAttributeValueSame(string $name, string $expectedValue, string $message = ''): void
    {
        self::assertThat(self::getRequest()new ResponseConstraint\RequestAttributeValueSame($name$expectedValue)$message);
    }

    public static function assertRouteSame(string $expectedRoute, array $parameters = [], string $message = ''): void
    {
        $constraint = new ResponseConstraint\RequestAttributeValueSame('_route', $expectedRoute);
        $constraints = [];
        foreach ($parameters as $key => $value) {
            $constraints[] = new ResponseConstraint\RequestAttributeValueSame($key$value);
        }
        if ($constraints) {
            $constraint = LogicalAnd::fromConstraints($constraint, ...$constraints);
        }
use PHPUnit\Framework\Constraint\LogicalNot;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mailer\Event\MessageEvents;
use Symfony\Component\Mailer\Test\Constraint as MailerConstraint;
use Symfony\Component\Mime\RawMessage;
use Symfony\Component\Mime\Test\Constraint as MimeConstraint;

trait MailerAssertionsTrait
{
    public static function assertEmailCount(int $count, string $transport = null, string $message = ''): void
    {
        self::assertThat(self::getMessageMailerEvents()new MailerConstraint\EmailCount($count$transport)$message);
    }

    public static function assertQueuedEmailCount(int $count, string $transport = null, string $message = ''): void
    {
        self::assertThat(self::getMessageMailerEvents()new MailerConstraint\EmailCount($count$transport, true)$message);
    }

    public static function assertEmailIsQueued(MessageEvent $event, string $message = ''): void
    {
        self::assertThat($eventnew MailerConstraint\EmailIsQueued()$message);
    }

    
public function statusMessageExistsAfterWait(string $type = NULL, int $timeout = 10000): void {
    $selector = $this->buildJavascriptStatusMessageSelector(NULL, $type);
    $status_message_element = $this->waitForElement('xpath', $selector$timeout);
    if ($type) {
      $failure_message = sprintf('A status message of type "%s" does not appear on this page, but it should.', $type);
    }
    else {
      $failure_message = 'A status message does not appear on this page, but it should.';
    }
    // There is no Assert::isNotNull() method, so we make our own constraint.     $constraint = new LogicalNot(new IsNull());
    Assert::assertThat($status_message_element$constraint$failure_message);
  }

  /** * Asserts that a status message does not exist after wait. * * @param string|null $type * The optional message type: status, error, or warning. * @param int $timeout * Optional timeout in milliseconds, defaults to 10000. */
  public function statusMessageNotExistsAfterWait(string $type = NULL, int $timeout = 10000): void {
    
$validator = $this->context->getValidator()->inContext($this->context);
        $validator->expectNoValidate();
    }

    protected function expectValidateAt(int $i, string $propertyPath, mixed $value, string|GroupSequence|array|null $group)
    {
        $validator = $this->context->getValidator()->inContext($this->context);
        $validator->expectValidation($i$propertyPath$value$groupfunction D$passedConstraints) {
            $expectedConstraints = new LogicalOr();
            $expectedConstraints->setConstraints([new IsNull()new IsIdentical([])new IsInstanceOf(Valid::class)]);

            Assert::assertThat($passedConstraints$expectedConstraints);
        });
    }

    protected function expectValidateValue(int $i, mixed $value, array $constraints = [], string|GroupSequence|array $group = null)
    {
        $contextualValidator = $this->context->getValidator()->inContext($this->context);
        $contextualValidator->expectValidation($i, null, $value$groupfunction D$passedConstraints) use ($constraints) {
            if (\is_array($constraints) && !\is_array($passedConstraints)) {
                $passedConstraints = [$passedConstraints];
            }

            
trait PolyfillAssertTrait
{
    /** * @param iterable $haystack * @param string $message * * @return void */
    public static function assertContainsEquals($needle$haystack$message = '')
    {
        $constraint = new TraversableContains($needle, false, false);
        static::assertThat($haystack$constraint$message);
    }

    /** * @param iterable $haystack * @param string $message * * @return void */
    public static function assertNotContainsEquals($needle$haystack$message = '')
    {
        $constraint = new LogicalNot(new TraversableContains($needle, false, false));
        


    public function testContext()
    {
        $encoder = new YamlEncoder(null, null, [YamlEncoder::YAML_INLINE => 1, YamlEncoder::YAML_INDENT => 4, YamlEncoder::YAML_FLAGS => Yaml::DUMP_OBJECT | Yaml::PARSE_OBJECT]);

        $obj = new \stdClass();
        $obj->bar = 2;

        $legacyTag = " foo: !php/object:O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}\n";
        $spacedTag = " foo: !php/object 'O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}'\n";
        $this->assertThat($encoder->encode(['foo' => $obj], 'yaml')$this->logicalOr($this->equalTo($legacyTag)$this->equalTo($spacedTag)));
        $this->assertEquals(' { foo: null }', $encoder->encode(['foo' => $obj], 'yaml', [YamlEncoder::YAML_INLINE => 0, YamlEncoder::YAML_INDENT => 2, YamlEncoder::YAML_FLAGS => 0]));
        $this->assertEquals(['foo' => $obj]$encoder->decode("foo: !php/object 'O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}'", 'yaml'));
        $this->assertEquals(['foo' => null]$encoder->decode("foo: !php/object 'O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}'", 'yaml', [YamlEncoder::YAML_FLAGS => 0]));
    }
}
use Symfony\Component\DomCrawler\Test\Constraint\CrawlerSelectorExists;

/** * Ideas borrowed from Laravel Dusk's assertions. * * @see https://laravel.com/docs/5.7/dusk#available-assertions */
trait DomCrawlerAssertionsTrait
{
    public static function assertSelectorExists(string $selector, string $message = ''): void
    {
        self::assertThat(self::getCrawler()new DomCrawlerConstraint\CrawlerSelectorExists($selector)$message);
    }

    public static function assertSelectorNotExists(string $selector, string $message = ''): void
    {
        self::assertThat(self::getCrawler()new LogicalNot(new DomCrawlerConstraint\CrawlerSelectorExists($selector))$message);
    }

    public static function assertSelectorCount(int $expectedCount, string $selector, string $message = ''): void
    {
        self::assertThat(self::getCrawler()new DomCrawlerConstraint\CrawlerSelectorCount($expectedCount$selector)$message);
    }

    
return;
                }

                $e = new Error(sprintf('%s: %s', \get_class($e)$e->getMessage()), -1, null, $e);

                $output = trim(sprintf('%s: %s', \get_class($e)$e->getMessage()));
            }

            if (false !== $exception) {
                list($class) = explode(':', $exception);
                $constraintClass = class_exists('PHPUnit\Framework\Constraint\Exception') ? 'PHPUnit\Framework\Constraint\Exception' : 'PHPUnit_Framework_Constraint_Exception';
                $this->assertThat(null, new $constraintClass($class));
            }

            $expected = trim($match[3], "\n ");

            if ($expected !== $output) {
                printf("Compiled templates that failed on case %d:\n", $i + 1);

                foreach (array_keys($templates) as $name) {
                    echo "Template: $name\n";
                    echo $twig->compile($twig->parse($twig->tokenize($twig->getLoader()->getSourceContext($name))));
                }
            }

    public function testFormatCurrencyByLanguageWillWriteCorrectCurrencySymbol(float $price, int $decimalPlaces, string $localeCode, string $expectedSeparator, string $currencyISO, string $expectedCurrencySymbol): void
    {
        $this->localeProvider->expects(static::once())->method('getLocaleForLanguageId')->willReturn($localeCode);
        $formattedPrice = $this->formatter->formatCurrencyByLanguage(
            $price,
            $currencyISO,
            Uuid::randomHex(),
            $this->createContext($decimalPlaces)
        );

        static::assertThat(
            $formattedPrice,
            static::logicalOr(
                static::stringStartsWith($expectedCurrencySymbol),
                static::stringEndsWith($expectedCurrencySymbol)
            )
        );
    }

    /** * @dataProvider formattingParameterProvider */
    
static::assertNotNull($languageId);
        $secondDomain = 'http://shopware.second-domain';
        $this->setDomainForSalesChannel($secondDomain$languageId);

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

        $phpunit = $this;
        $eventDidRun = false;
        $listenerClosure = function DMailSentEvent $event) use (&$eventDidRun$phpunit$firstDomain$secondDomain): void {
            $phpunit->assertStringContainsString($firstDomain$event->getContents()['text/html']);
            $phpunit->assertThat($event->getContents()['text/html']$this->logicalNot($this->stringContains($secondDomain)));
            $eventDidRun = true;
        };

        $this->addEventListener($dispatcher, MailSentEvent::class$listenerClosure);

        $this->orderService->createOrder($data$this->salesChannelContext);

        $dispatcher->removeListener(MailSentEvent::class$listenerClosure);

        static::assertTrue($eventDidRun, 'The mail.sent Event did not run');
    }

    

    public function getStatusCode(): int
    {
        return $this->statusCode ?? throw new \RuntimeException('Status code not initialized, did you execute the command before requesting the status code?');
    }

    public function assertCommandIsSuccessful(string $message = ''): void
    {
        Assert::assertThat($this->statusCode, new CommandIsSuccessful()$message);
    }

    /** * Sets the user inputs. * * @param array $inputs An array of strings representing each input * passed to the command input stream * * @return $this */
    public function setInputs(array $inputs)static
    {

  public function responseHeaderExists(string $name, string $message = ''): void {
    if ($message === '') {
      $message = "Failed asserting that the response has a '$name' header.";
    }
    $headers = $this->session->getResponseHeaders();
    $constraint = new ArrayHasKey($name);
    Assert::assertThat($headers$constraint$message);
  }

  /** * Asserts that the current response header does not have a specific entry. * * @param string $name * The name of the header entry to check existence of. * @param string $message * The failure message. */
  public function responseHeaderDoesNotExist(string $name, string $message = ''): void {
    
use Symfony\Component\Notifier\Event\NotificationEvents;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Test\Constraint as NotifierConstraint;

/* * @author Smaïne Milianni <smaine.milianni@gmail.com> */
trait NotificationAssertionsTrait
{
    public static function assertNotificationCount(int $count, string $transportName = null, string $message = ''): void
    {
        self::assertThat(self::getNotificationEvents()new NotifierConstraint\NotificationCount($count$transportName)$message);
    }

    public static function assertQueuedNotificationCount(int $count, string $transportName = null, string $message = ''): void
    {
        self::assertThat(self::getMessageMailerEvents()new NotifierConstraint\NotificationCount($count$transportName, true)$message);
    }

    public static function assertNotificationIsQueued(MessageEvent $event, string $message = ''): void
    {
        self::assertThat($eventnew NotifierConstraint\NotificationIsQueued()$message);
    }

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