You are here

public function HttpStatusCodeTest::testHttpStatusCodeNegate in Context 8.4

Tests the http status code condition that is negated.

File

tests/src/Kernel/HttpStatusCodeTest.php, line 121

Class

HttpStatusCodeTest
Tests the http status code condition plugin.

Namespace

Drupal\Tests\context\Kernel

Code

public function testHttpStatusCodeNegate() {

  // Get the http status code condition and configure it to check against
  // different code statuses with the negate option enabled.
  $statusCodes = [
    200 => '200',
    403 => '403',
  ];
  $request = Request::create('/my/status/page');
  $request->attributes
    ->set('exception', new HttpException(403));
  $request->attributes
    ->set('exception', new HttpException(200));
  $this->requestStack
    ->push($request);

  /** @var \Drupal\system\Plugin\Condition\RequestPath $condition * */
  $condition = $this->pluginManager
    ->createInstance('http_status_code');
  $condition
    ->setConfig('status_codes', $statusCodes);
  $condition
    ->setConfig('negate', 1);
  $this->aliasManager
    ->addAlias('/my/status/page', '/my/status/page');
  $this
    ->assertFalse($condition
    ->execute(), 'Status codes are not matching');
  $this
    ->assertEquals('The http status code is not 200 or 403', $condition
    ->summary(), 'The http status codes do not match');
  $request->attributes
    ->set('exception', new HttpException(403));
  $this->requestStack
    ->push($request);
  $condition
    ->setConfig('status_codes', [
    403 => '403',
  ]);
  $this
    ->assertFalse($condition
    ->execute(), 'Status code is not 403');
  $this
    ->assertEquals('The http status code is not 403', $condition
    ->summary(), 'The http status code does not match');
  $request->attributes
    ->set('exception', new HttpException(200));
  $this->requestStack
    ->push($request);
  $condition
    ->setConfig('status_codes', [
    200 => '200',
  ]);
  $this
    ->assertFalse($condition
    ->execute(), 'Status code is not 200');
  $this
    ->assertEquals('The http status code is not 200', $condition
    ->summary(), 'The http status code does not match');

  // Exception is empty, so default status code should be 200.
  $this->requestStack
    ->push($request);
  $this
    ->assertFalse($condition
    ->execute(), 'Status code is not 200');

  // Exception is not a HttpException, so default status code should be 200.
  $request->attributes
    ->set('exception', new \Exception(403));
  $this->requestStack
    ->push($request);
  $condition
    ->setConfig('status_codes', [
    403 => '403',
  ]);
  $this
    ->assertTrue($condition
    ->execute(), 'Status code is 403');
}