Как я могу обнаружить ошибки 404 для ресурсов страницы?

Я только начал с Behat и Mink. Я использую MinkExtension с Goutte и Selenium, а также DrupalExtension.

Все идет нормально. Я могу загрузить страницу, искать различные элементы, тестировать ссылки и т.д.

Но я не вижу, как проверить наличие ошибок 404 в различных ресурсах, особенно в изображениях, а также в файлах css и js.

Любые советы или примеры будут высоко оценены.


person joe casey    schedule 29.05.2014    source источник


Ответы (4)


При использовании поискового робота Goutte вы можете сделать следующее:

$crawler = $client->request('GET', 'http://your-url.here');
$status_code = $client->getResponse()->getStatus();
if($status_code==404){
  // Do something
}
person henrik    schedule 29.10.2014

Вы можете попробовать следующие методы:

<?php

use Behat\Behat\Context\Context;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class FeatureContext extends WebTestCase implements Context {

  /**
   * @var Client
   */
  private $client;

  /**
   * @When /^I send a "([^"]*)" request to "([^"]*)"$/
   *
   * @param $arg1
   * @param $arg2
   */
  public function iSendARequestTo($arg1, $arg2) {
    $this->client = static::createClient();
    $this->client->request($arg1, $arg2);
  }

  /**
   * @Then /^the output should contain: "([^"]*)"$/
   *
   * @param $arg1
   */
  public function theOutputShouldContain($arg1) {
    $this->assertContains($arg1, $this->client->getResponse()->getContent());
  }

  /**
   * @Then /^the status code should be "([^"]*)"$/
   *
   * @param $arg1
   */
  public function theStatusCodeShouldBe($arg1) {
    $this->assertEquals($arg1, $this->client->getResponse()->getStatusCode());
  }
}

Источник: FeatureContext.php на сайте jmquarck. /Кейт

person kenorb    schedule 26.07.2017

Пожалуйста, проверьте следующие методы из этого HelperContext.php (часть из CWTest_Behat):

  /**
   * @Given get the HTTP response code :url
   * Anonymous users ONLY.
   */
  public function getHTTPResponseCode($url) {
    $headers = get_headers($url, 1);
    return substr($headers[0], 9, 3);
  }

  /**
   * @Given I check the HTTP response code is :code for :url
   */
  public function iCheckTheHttpResponseCodeIsFor($expected_response, $url) {
    $path = $this->getMinkParameter('base_url') . $url;
    $actual_response = $this->getHTTPResponseCode($path);
    $this->verifyResponseForURL($actual_response, $expected_response, $url);
  }

  /**
   * Compare the actual and expected status responses for a URL.
   */
  function verifyResponseForURL($actual_response, $expected_response, $url) {
    if (intval($actual_response) !== intval($expected_response)) {
      throw new Exception("This '{$url}' asset returned a {$actual_response} response.");
    }
  }

  /**
   * @Given I should get the following HTTP status responses:
   */
  public function iShouldGetTheFollowingHTTPStatusResponses(TableNode $table) {
    foreach ($table->getRows() as $row) {
      $this->getSession()->visit($row[0]);
      $this->assertSession()->statusCodeEquals($row[1]);
    }
  }

Вот примеры сценариев, написанных на Behat, в которых используются описанные выше методы:

  @roles @api @regression
  Scenario: Verify Anonymous User access to /user/login
    Given I am not logged in
    Then I check the HTTP response code is 200 for '/user/login'

  @roles @api @regression
  Scenario: Verify Anonymous User access to /admin
    Given I am not logged in
    Then I check the HTTP response code is 403 for '/admin'

  @roles @api @regression
  Scenario: Verify Administrator access to /admin
    Given I am logged in as a user with the admin role
    And I am on "/admin"
    Then the response status code should be 200
person kenorb    schedule 26.07.2017

Можно использовать Restler, микро-фреймворк, который может помочь с RESTful API. тестирование в Бехате. Он поддерживает тестирование API на основе поведения с использованием Behat и Guzzle.

Посмотрите следующий пример:

  Scenario: Saying
    When I request "/examples/_001_helloworld/say"
    Then the response status code should be 404
    And the response is JSON
    And the type is "array"
person kenorb    schedule 27.07.2017