You are here

class ParserTest in Weather 8

Same name and namespace in other branches
  1. 2.0.x tests/src/Functional/ParserTest.php \Drupal\Tests\weather\Functional\ParserTest

Tests parsing of XML weather forecasts.

@group Weather

Hierarchy

Expanded class hierarchy of ParserTest

File

tests/src/Functional/ParserTest.php, line 14

Namespace

Drupal\Tests\weather\Functional
View source
class ParserTest extends BrowserTestBase {
  use WeatherCommonTestTrait;

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = [
    'weather',
  ];

  /**
   * The tests don't need markup, so use 'stark' as theme.
   *
   * @var string
   */
  protected $defaultTheme = 'stark';

  /**
   * Try to fetch forecasts from the database.
   *
   * @param string $geoid
   *   GeoID of the place for which the weather is desired.
   * @param string $utc_offset
   *   UTC offset of place in minutes.
   * @param int $days
   *   Return weather for specified number of days (0 = all available days).
   * @param bool $detailed
   *   Return detailed forecasts or just one forecast per day.
   * @param int $time
   *   Timestamp for which the weather should be returned. This is only
   *   needed to enable proper testing of the module.
   *
   * @return array
   *   Weather array with forecast information.
   */
  private function weatherGetForecastsFromDatabase($geoid, $utc_offset, $days, $detailed, $time) {

    // Fetch the first forecast. This must be done separately, because
    // sometimes the first forecast is already on the next day (this can
    // happen e.g. late in the evenings). Otherwise, the calculation of
    // 'tomorrow' would fail.
    $current_local_time = gmdate('Y-m-d H:i:s', $time + $utc_offset * 60);
    $connection = \Drupal::database();
    $query = $connection
      ->select('weather_forecast', 'wfi');
    $query
      ->condition('wfi.geoid', $geoid, '=');
    $query
      ->condition('wfi.time_to', $current_local_time, '>=');
    $query
      ->fields('wfi', [
      'geoid',
      'time_from',
      'time_to',
      'period',
      'symbol',
      'precipitation',
      'wind_direction',
      'wind_speed',
      'temperature',
      'pressure',
    ]);
    $query
      ->range(0, 50);
    $result = $query
      ->execute();
    $first_forecast = $result
      ->fetchAll();

    // If there are no forecasts available, return an empty array.
    if ($first_forecast === FALSE) {
      return [];
    }
    $weather = $this
      ->weatherCreateWeatherArray([
      $first_forecast,
    ]);

    // Calculate tomorrow based on result.
    $first_forecast_day = explode('-', key($weather));
    $tomorrow_local_time = gmdate('Y-m-d H:i:s', gmmktime(0, 0, 0, $first_forecast_day[1], $first_forecast_day[2] + 1, $first_forecast_day[0]));
    $forecasts_until_local_time = gmdate('Y-m-d 23:59:59', gmmktime(23, 59, 59, $first_forecast_day[1], $first_forecast_day[2] + $days - 1, $first_forecast_day[0]));
    if ($detailed) {

      // Fetch all available forecasts.
      if ($days > 0) {
        $query = $connection
          ->select('weather_forecast', 'wfi');
        $query
          ->condition('wfi.geoid', $geoid, '=');
        $query
          ->condition('wfi.time_to', $forecasts_until_local_time, '>=');
        $query
          ->fields('wfi', [
          'geoid',
          'time_from',
          'time_to',
          'period',
          'symbol',
          'precipitation',
          'wind_direction',
          'wind_speed',
          'temperature',
          'pressure',
        ]);
        $query
          ->range(0, 50);
        $result = $query
          ->execute();
        $forecasts = $result
          ->fetchAll();
      }
      else {
        $query = $connection
          ->select('weather_forecast', 'wfi');
        $query
          ->condition('wfi.geoid', $geoid, '=');
        $query
          ->condition('wfi.time_to', $current_local_time, '>=');
        $query
          ->fields('wfi', [
          'geoid',
          'time_from',
          'time_to',
          'period',
          'symbol',
          'precipitation',
          'wind_direction',
          'wind_speed',
          'temperature',
          'pressure',
        ]);
        $query
          ->range(0, 50);
        $result = $query
          ->execute();
        $forecasts = $result
          ->fetchAll();
      }
      $weather = $this
        ->weatherCreateWeatherArray($forecasts);
    }
    else {
      if ($days > 1) {
        $query = $connection
          ->select('weather_forecast', 'wfi');
        $query
          ->condition('wfi.geoid', $geoid, '=');
        $query
          ->condition('wfi.time_from', $tomorrow_local_time, '>=');
        $query
          ->condition('wfi.time_to', $forecasts_until_local_time, '>=');
        $query
          ->fields('wfi', [
          'geoid',
          'time_from',
          'time_to',
          'period',
          'symbol',
          'precipitation',
          'wind_direction',
          'wind_speed',
          'temperature',
          'pressure',
        ]);
        $query
          ->range(0, 50);
        $result = $query
          ->execute();
        $forecasts = $result
          ->fetchAll();
        $weather = array_merge($weather, $this
          ->weatherCreateWeatherArray($forecasts));
      }
      elseif ($days == 0) {
        $query = $connection
          ->select('weather_forecast', 'wfi');
        $query
          ->condition('wfi.geoid', $geoid, '=');
        $query
          ->condition('wfi.time_from', $tomorrow_local_time, '>=');
        $query
          ->fields('wfi', [
          'geoid',
          'time_from',
          'time_to',
          'period',
          'symbol',
          'precipitation',
          'wind_direction',
          'wind_speed',
          'temperature',
          'pressure',
        ]);
        $query
          ->range(0, 50);
        $result = $query
          ->execute();
        $forecasts = $result
          ->fetchAll();
        $weather = array_merge($weather, $this
          ->weatherCreateWeatherArray($forecasts));
      }
    }
    return $weather;
  }

  /**
   * Handle updates to the weather_places table.
   */
  public function weatherUpdatePlaces($fc) {

    // Extract GeoID and latitude/longitude of returned XML data.
    // This might differ from the data we have in the database. An example
    // was Heraklion (ID 261745), which got the forecast for
    // Nomós Irakleíou (ID 261741).
    // Data to extract are:
    // geoid, latitude, longitude, country, name.
    $place['geoid'] = $fc->location->location['geobase'] . "_" . $fc->location->location['geobaseid'];
    $place['latitude'] = (string) $fc->location->location['latitude'];
    $place['latitude'] = round($place['latitude'], 5);
    $place['longitude'] = (string) $fc->location->location['longitude'];
    $place['longitude'] = round($place['longitude'], 5);
    $place['country'] = (string) $fc->location->country;
    $place['name'] = (string) $fc->location->name;
    $url = (string) $fc->credit->link['url'];

    // Remove "http://www.yr.no/place/" from the URL.
    // fixme: not reliable in case we have https;//... at the beginning.
    $link = substr($url, 23);

    // Split by slashes and remove country (first item)
    // and "forecast.xml" (last item)
    $link_parts = explode('/', $link);

    // Remove country.
    array_shift($link_parts);

    // Remove "forecast.xml".
    array_pop($link_parts);
    $place['link'] = implode('/', $link_parts);

    // Fetch stored information about geoid.
    $info = $this
      ->weatherGetInformationAboutGeoid($place['geoid']);

    // If the geoid is not in the database, add it.
    if ($info === FALSE) {
      $place['status'] = 'added';

      // Insert the record to table.
      \Drupal::database()
        ->insert('weather_place')
        ->fields($place)
        ->execute();
    }
    else {

      // Compare the stored information with the downloaded information.
      // If they differ, update the database.
      $stored_info = (array) $info;
      unset($stored_info['status']);
      $diff = array_diff_assoc($stored_info, $place);
      if (!empty($diff)) {
        $place['status'] = WeatherPlaceInterface::STATUS_MODIFIED;
        \Drupal::database()
          ->update('weather_place')
          ->condition('geoid', $place['geoid'])
          ->updateFields($place)
          ->execute();
      }
    }
  }

  /**
   * Parses an XML forecast supplied by yr.no.
   *
   * @param string $xml
   *   XML to be parsed.
   * @param string $geoid
   *   The GeoID for which the forecasts should be parsed.
   *
   * @return bool
   *   TRUE on success, FALSE on failure.
   *
   * @throws \Exception
   */
  public function weatherParseForecast($xml, $geoid = '') {

    // In case the parsing fails, do not output all error messages.
    $use_errors = libxml_use_internal_errors(TRUE);
    $fc = simplexml_load_string($xml);

    // Restore previous setting of error handling.
    libxml_use_internal_errors($use_errors);
    if ($fc === FALSE) {
      return FALSE;
    }

    // Update weather_places table with downloaded information, if necessary.
    $this
      ->weatherUpdatePlaces($fc);

    // Extract meta information.
    // @TODO: Extract GeoID of returned XML data.
    // This might differ from the data we have in the database. An example
    // was Heraklion (ID 261745), which got the forecast for
    // Nomós Irakleíou (ID 261741).
    if ($geoid == '') {
      $geoid = $fc->location->location['geobase'] . "_" . $fc->location->location['geobaseid'];
    }
    $meta['geoid'] = $geoid;
    $meta['utc_offset'] = (int) $fc->location->timezone['utcoffsetMinutes'];

    // Calculate the UTC time.
    $utctime = strtotime((string) $fc->meta->lastupdate . ' UTC') - 60 * $meta['utc_offset'];
    $meta['last_update'] = gmdate('Y-m-d H:i:s', $utctime);

    // Calculate the UTC time.
    $utctime = strtotime((string) $fc->meta->nextupdate . ' UTC') - 60 * $meta['utc_offset'];
    $meta['next_update'] = gmdate('Y-m-d H:i:s', $utctime);
    $meta['next_download_attempt'] = $meta['next_update'];

    // Merge meta information for this location.
    // This prevents an integrity constraint violation, if multiple
    // calls to this function occur at the same time. See bug #1412352.
    //
    \Drupal::database()
      ->merge('weather_forecast_information')
      ->key([
      'geoid' => $meta['geoid'],
    ])
      ->insertFields($meta)
      ->updateFields($meta)
      ->execute();

    // Remove all forecasts for this location.
    \Drupal::database()
      ->delete('weather_forecast')
      ->condition('geoid', $meta['geoid'])
      ->execute();

    // Cycle through all forecasts and write them to the table.
    foreach ($fc->forecast->tabular->time as $time) {
      $forecast = [];
      $forecast['geoid'] = $meta['geoid'];
      $forecast['time_from'] = str_replace('T', ' ', (string) $time['from']);
      $forecast['time_to'] = str_replace('T', ' ', (string) $time['to']);
      $forecast['period'] = (string) $time['period'];
      $forecast['symbol'] = (string) $time->symbol['var'];

      // Remove moon phases, which are not supported.
      // This is in the format "mf/03n.56", where 56 would be the
      // percentage of the moon phase.
      if (strlen($forecast['symbol']) > 3) {
        $forecast['symbol'] = substr($forecast['symbol'], 3, 3);
      }
      $forecast['precipitation'] = (double) $time->precipitation['value'];
      $forecast['wind_direction'] = (int) $time->windDirection['deg'];
      $forecast['wind_speed'] = (double) $time->windSpeed['mps'];
      $forecast['temperature'] = (int) $time->temperature['value'];
      $forecast['pressure'] = (int) $time->pressure['value'];

      // Use db_merge to prevent integrity constraint violation, see above.
      \Drupal::database()
        ->merge('weather_forecast')
        ->key([
        'geoid' => $meta['geoid'],
        'time_from' => $forecast['time_from'],
      ])
        ->insertFields($forecast)
        ->updateFields($forecast)
        ->execute();
    }
    return TRUE;
  }

  /**
   * Downloads a new forecast from yr.no.
   *
   * @param string $geoid
   *   The GeoID for which the forecasts should be downloaded.
   *
   * @return bool
   *   TRUE on success, FALSE on failure.
   *
   * @throws \ReflectionException
   */
  private function weatherDownloadForecast($geoid) {

    // Do not download anything if the variable
    // 'weather_time_for_testing' is set.
    // In this case, we are in testing mode and only load defined
    // forecasts to get always the same results.
    $config = \Drupal::configFactory()
      ->getEditable('weather.settings');
    $time = $config
      ->get('weather_time_for_testing');
    if ($time !== \Drupal::time()
      ->getRequestTime()) {
      $path = dirname((new ReflectionClass(static::class))
        ->getFileName()) . '/data/' . $geoid . '.xml';
      if (is_readable($path)) {
        $xml = file_get_contents($path);
      }
      else {
        $xml = '';
      }
      return $this
        ->weatherParseForecast($xml, $geoid);
    }

    // Specify timeout in seconds.
    $timeout = 10;
    $url = $this
      ->weatherGetLinkForGeoId($geoid, 'yr');
    $response = $this
      ->drupalGet($url, [
      'timeout' => $timeout,
    ]);

    // Extract XML data from the received forecast.
    if (!isset($response->error)) {
      return $this
        ->weatherParseForecast($response->data, $geoid);
    }
    else {

      // Make an entry about this error into the watchdog table.
      \Drupal::logger('weather')
        ->error($response->error);

      // Get the current user.
      $user = \Drupal::currentUser();

      // Check for permission.
      $user
        ->hasPermission('administer site configuration');

      // Show a message to users with administration priviledges.
      if ($user
        ->hasPermission('administer custom weather block') or $user
        ->hasPermission('administer site configuration')) {
        \Drupal::messenger()
          ->addMessage(t('Download of forecast failed: @error', [
          '@error' => $response->error,
        ]), 'error');
      }
    }
  }

  /**
   * Returns a weather object for the specified GeoID.
   *
   * @param string $geoid
   *   GeoID of the place for which the weather is desired.
   * @param int $days
   *   Return weather for specified number of days (0 = all available days).
   * @param bool $detailed
   *   Return detailed forecasts or just one forecast per day.
   *
   * @return array
   *   Weather array with forecast information.
   *
   * @throws \Exception
   */
  private function weatherGetWeather($geoid, $days = 0, $detailed = TRUE) {

    // Support testing of module with fixed times instead of current time.
    $config = \Drupal::configFactory()
      ->getEditable('weather.settings');
    $time = $config
      ->get('weather_time_for_testing');

    // Get the scheduled time of next update. If there is no entry for
    // the specified GeoID, $meta will be FALSE.
    $query = \Drupal::database()
      ->select('weather_forecast_information', 'wfi');
    $query
      ->fields('wfi', [
      'geoid',
    ]);
    $query
      ->condition('wfi.geoid', $geoid, '=');
    $meta = $query
      ->execute();
    $meta = $meta
      ->fetchAssoc();
    $current_utc_time = gmdate('Y-m-d H:i:s', $time);

    // If the next scheduled download is due, try to get forecasts.
    if (!empty($meta)) {
      $meta['next_download_attempt'] = $time;
    }
    if ($meta === FALSE or $current_utc_time >= $meta['next_download_attempt']) {
      $result = $this
        ->weatherDownloadForecast($geoid);

      // If that worked, get the next scheduled update time.
      $query = \Drupal::database()
        ->select('weather_forecast_information', 'wfi');
      $query
        ->fields('wfi', [
        'geoid',
      ]);
      $query
        ->condition('wfi.geoid', $geoid, '=');
      $meta = $query
        ->execute();
      $meta = $meta
        ->fetchAssoc();

      // If there is no entry yet, set up initial values.
      if ($meta === FALSE) {
        $meta['geoid'] = $geoid;
        $meta['last_update'] = $current_utc_time;
        $meta['next_update'] = $current_utc_time;
        $meta['next_download_attempt'] = $current_utc_time;
        $meta['utc_offset'] = 120;
      }
      if (empty($meta['next_update'])) {
        $meta['next_update'] = $time;
      }

      // The second check is needed if the download did succeed, but
      // the returned forecast is old and the next update is overdue.
      // In that case, the download attempt needs to wait as well,
      // otherwise, a new download will occur on every page load.
      if ($result == FALSE || $current_utc_time >= $meta['next_update']) {

        // The download did not succeed. Set next download attempt accordingly.
        // Calculate the UTC timestamp.
        $next_update = strtotime($meta['next_update'] . ' UTC');

        // Initial retry after 675 seconds (11.25 minutes).
        // This way, the doubling on the first day leads to exactly 86400
        // seconds (one day) update interval.
        $seconds_to_retry = 675;
        while ($next_update + $seconds_to_retry <= $time) {
          if ($seconds_to_retry < 86400) {
            $seconds_to_retry = $seconds_to_retry * 2;
          }
          else {
            $seconds_to_retry = $seconds_to_retry + 86400;
          }
        }

        // Finally, calculate the UTC time of the next download attempt.
        $meta['next_download_attempt'] = gmdate('Y-m-d H:i:s', $next_update + $seconds_to_retry);
        \Drupal::database()
          ->delete('weather_forecast_information')
          ->condition('geoid', $meta['geoid'])
          ->execute();

        // Write new entry.
        \Drupal::database()
          ->insert('weather_forecast_information')
          ->fields($meta)
          ->execute();
      }
    }
    if (empty($meta['utc_offset'])) {
      $meta['utc_offset'] = 120;
    }
    $return_array['forecasts'] = $this
      ->weatherGetForecastsFromDatabase($geoid, $meta['utc_offset'], $days, $detailed, $time);
    $return_array['utc_offset'] = $meta['utc_offset'];
    return $return_array;
  }

  /**
   * Internal helper function for getting information about a forecast.
   */
  private function getInfoAboutForecast($time) {

    // Set the testing time.
    $config = \Drupal::configFactory()
      ->getEditable('weather.settings');
    $config
      ->set('weather_time_for_testing', $time)
      ->save();

    // Fetch weather forecasts for Hamburg.
    $this
      ->weatherGetWeather('geonames_2911298', 1, FALSE);

    // Return the parsed information.
    $connection = \Drupal::database();
    $query = $connection
      ->select('weather_forecast_information', 'wfi');
    $query
      ->condition('wfi.geoid', 'geonames_2911298', '=');
    $query
      ->fields('wfi', [
      'geoid',
      'last_update',
      'next_update',
      'next_download_attempt',
      'utc_offset',
    ]);
    $query
      ->range(0, 50);
    $result = $query
      ->execute();
    return $result
      ->fetchAll();
  }

  /**
   * Test parsing of information about a forecast.
   */
  public function testParsingOfInformation() {

    // 2013-10-07 20:00:00 UTC.
    $info = $this
      ->getInfoAboutForecast(1381176000);

    // Check that the information has been parsed correctly.
    $info = reset($info);
    $this
      ->assertEqual($info->geoid, 'geonames_2911298');
    $this
      ->assertEqual($info->last_update, '2013-10-07 15:30:00');
    $this
      ->assertEqual($info->next_update, '2013-10-08 04:00:00');
    $this
      ->assertEqual($info->next_download_attempt, '2013-10-08 04:00:00');
    $this
      ->assertEqual($info->utc_offset, 120);
  }

  /**
   * Test the parser with different days of forecast data.
   */
  public function testDifferentDaysOfForecasts() {

    // These are all days from the forecast.
    $days = [
      '2013-10-07',
      '2013-10-08',
      '2013-10-09',
      '2013-10-10',
      '2013-10-11',
      '2013-10-12',
      '2013-10-13',
      '2013-10-14',
      '2013-10-15',
      '2013-10-16',
      '2013-10-17',
    ];

    // Set a fixed time for testing to 2013-10-07 20:00:00 UTC.
    $config = \Drupal::configFactory()
      ->getEditable('weather.settings');
    $config
      ->set('weather_time_for_testing', 1381176000)
      ->save();

    // Fetch all weather forecasts for Hamburg
    // and check the correct days of forecasts.
    $weather = $this
      ->weatherGetWeather('geonames_2911298', 0, TRUE);
    $this
      ->assertIdentical(array_keys($weather['forecasts']), $days);

    // Go a few days forward ...
    // Set a fixed time for testing to 2013-10-12 10:00:00 UTC.
    $config = \Drupal::configFactory()
      ->getEditable('weather.settings');
    $config
      ->set('weather_time_for_testing', 1381572000)
      ->save();

    // Fetch all weather forecasts for Hamburg
    // and check the correct days of forecasts.
    $weather = $this
      ->weatherGetWeather('geonames_2911298', 0, TRUE);
    $this
      ->assertIdentical(array_keys($weather['forecasts']), array_slice($days, 5));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssertHelperTrait::castSafeStrings protected static function Casts MarkupInterface objects into strings.
AssertLegacyTrait::assert protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertTrue() instead.
AssertLegacyTrait::assertCacheTag protected function Asserts whether an expected cache tag was present in the last response.
AssertLegacyTrait::assertElementNotPresent protected function Asserts that the element with the given CSS selector is not present.
AssertLegacyTrait::assertElementPresent protected function Asserts that the element with the given CSS selector is present.
AssertLegacyTrait::assertEqual protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertEquals() instead.
AssertLegacyTrait::assertEscaped protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertLegacyTrait::assertField protected function Asserts that a field exists with the given name or ID.
AssertLegacyTrait::assertFieldById protected function Asserts that a field exists with the given ID and value.
AssertLegacyTrait::assertFieldByName protected function Asserts that a field exists with the given name and value.
AssertLegacyTrait::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
AssertLegacyTrait::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
AssertLegacyTrait::assertFieldsByValue protected function Asserts that a field exists in the current page with a given Xpath result.
AssertLegacyTrait::assertHeader protected function Checks that current response header equals value.
AssertLegacyTrait::assertIdentical protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertSame() instead.
AssertLegacyTrait::assertIdenticalObject protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertEquals() instead.
AssertLegacyTrait::assertLink protected function Passes if a link with the specified label is found.
AssertLegacyTrait::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
AssertLegacyTrait::assertNoCacheTag protected function Asserts whether an expected cache tag was absent in the last response.
AssertLegacyTrait::assertNoEscaped protected function Passes if the raw text is not found escaped on the loaded page.
AssertLegacyTrait::assertNoField protected function Asserts that a field does NOT exist with the given name or ID.
AssertLegacyTrait::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
AssertLegacyTrait::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
AssertLegacyTrait::assertNoFieldByXPath protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertLegacyTrait::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
AssertLegacyTrait::assertNoLink protected function Passes if a link with the specified label is not found.
AssertLegacyTrait::assertNoLinkByHref protected function Passes if a link containing a given href (part) is not found.
AssertLegacyTrait::assertNoOption protected function Asserts that a select option does NOT exist in the current page.
AssertLegacyTrait::assertNoPattern protected function Triggers a pass if the Perl regex pattern is not found in the raw content.
AssertLegacyTrait::assertNoRaw protected function Passes if the raw text IS not found on the loaded page, fail otherwise. 1
AssertLegacyTrait::assertNotEqual protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertNotEquals() instead.
AssertLegacyTrait::assertNoText protected function Passes if the page (with HTML stripped) does not contains the text. 1
AssertLegacyTrait::assertNotIdentical protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertNotSame() instead.
AssertLegacyTrait::assertNoUniqueText protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertLegacyTrait::assertOption protected function Asserts that a select option in the current page exists.
AssertLegacyTrait::assertOptionByText protected function Asserts that a select option with the visible text exists.
AssertLegacyTrait::assertOptionSelected protected function Asserts that a select option in the current page is checked.
AssertLegacyTrait::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertLegacyTrait::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise. 1
AssertLegacyTrait::assertResponse protected function Asserts the page responds with the specified response code. 1
AssertLegacyTrait::assertText protected function Passes if the page (with HTML stripped) contains the text. 1
AssertLegacyTrait::assertTextHelper protected function Helper for assertText and assertNoText.
AssertLegacyTrait::assertTitle protected function Pass if the page title is the given string.
AssertLegacyTrait::assertUniqueText protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertLegacyTrait::assertUrl protected function Passes if the internal browser's URL matches the given path.
AssertLegacyTrait::buildXPathQuery protected function Builds an XPath query.
AssertLegacyTrait::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertLegacyTrait::getAllOptions protected function Get all option elements, including nested options, in a select.
AssertLegacyTrait::getRawContent protected function Gets the current raw content.
AssertLegacyTrait::pass protected function Deprecated Scheduled for removal in Drupal 10.0.0. Use self::assertTrue() instead.
AssertLegacyTrait::verbose protected function
BlockCreationTrait::placeBlock protected function Creates a block instance based on default settings. Aliased as: drupalPlaceBlock
BrowserHtmlDebugTrait::$htmlOutputBaseUrl protected property The Base URI to use for links to the output files.
BrowserHtmlDebugTrait::$htmlOutputClassName protected property Class name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounter protected property Counter for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounterStorage protected property Counter storage for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputDirectory protected property Directory name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputEnabled protected property HTML output output enabled.
BrowserHtmlDebugTrait::$htmlOutputFile protected property The file name to write the list of URLs to.
BrowserHtmlDebugTrait::$htmlOutputTestId protected property HTML output test ID.
BrowserHtmlDebugTrait::formatHtmlOutputHeaders protected function Formats HTTP headers as string for HTML output logging.
BrowserHtmlDebugTrait::getHtmlOutputHeaders protected function Returns headers in HTML output format. 1
BrowserHtmlDebugTrait::htmlOutput protected function Logs a HTML output message in a text file.
BrowserHtmlDebugTrait::initBrowserOutputFile protected function Creates the directory to store browser output.
BrowserTestBase::$baseUrl protected property The base URL.
BrowserTestBase::$configImporter protected property The config importer that can be used in a test.
BrowserTestBase::$customTranslations protected property An array of custom translations suitable for drupal_rewrite_settings().
BrowserTestBase::$databasePrefix protected property The database prefix of this test run.
BrowserTestBase::$mink protected property Mink session manager.
BrowserTestBase::$minkDefaultDriverArgs protected property
BrowserTestBase::$minkDefaultDriverClass protected property 1
BrowserTestBase::$originalContainer protected property The original container.
BrowserTestBase::$originalShutdownCallbacks protected property The original array of shutdown function callbacks.
BrowserTestBase::$preserveGlobalState protected property
BrowserTestBase::$profile protected property The profile to install as a basis for testing. 39
BrowserTestBase::$root protected property The app root.
BrowserTestBase::$runTestInSeparateProcess protected property Browser tests are run in separate processes to prevent collisions between code that may be loaded by tests.
BrowserTestBase::$timeLimit protected property Time limit in seconds for the test.
BrowserTestBase::$translationFilesDirectory protected property The translation file directory for the test environment.
BrowserTestBase::cleanupEnvironment protected function Clean up the Simpletest environment.
BrowserTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
BrowserTestBase::cssSelectToXpath protected function Translates a CSS expression to its XPath equivalent.
BrowserTestBase::drupalGetHeader protected function Gets the value of an HTTP response header.
BrowserTestBase::drupalGetHeaders Deprecated protected function Returns all response headers.
BrowserTestBase::filePreDeleteCallback public static function Ensures test files are deletable.
BrowserTestBase::getDefaultDriverInstance protected function Gets an instance of the default Mink driver.
BrowserTestBase::getDrupalSettings protected function Gets the JavaScript drupalSettings variable for the currently-loaded page. 1
BrowserTestBase::getHttpClient protected function Obtain the HTTP client for the system under test.
BrowserTestBase::getMinkDriverArgs protected function Get the Mink driver args from an environment variable, if it is set. Can be overridden in a derived class so it is possible to use a different value for a subset of tests, e.g. the JavaScript tests. 1
BrowserTestBase::getOptions protected function Helper function to get the options of select field.
BrowserTestBase::getResponseLogHandler protected function Provides a Guzzle middleware handler to log every response received. Overrides BrowserHtmlDebugTrait::getResponseLogHandler
BrowserTestBase::getSession public function Returns Mink session.
BrowserTestBase::getSessionCookies protected function Get session cookies from current session.
BrowserTestBase::getTestMethodCaller protected function Retrieves the current calling line in the class under test. Overrides BrowserHtmlDebugTrait::getTestMethodCaller
BrowserTestBase::initFrontPage protected function Visits the front page when initializing Mink. 3
BrowserTestBase::initMink protected function Initializes Mink sessions. 1
BrowserTestBase::installDrupal public function Installs Drupal into the Simpletest site. 1
BrowserTestBase::registerSessions protected function Registers additional Mink sessions.
BrowserTestBase::setUp protected function 475
BrowserTestBase::tearDown protected function 3
BrowserTestBase::translatePostValues protected function Transforms a nested array into a flat array suitable for drupalPostForm().
BrowserTestBase::xpath protected function Performs an xpath search on the contents of the internal browser.
BrowserTestBase::__construct public function 1
BrowserTestBase::__sleep public function Prevents serializing any properties.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
ContentTypeCreationTrait::createContentType protected function Creates a custom content type based on default settings. Aliased as: drupalCreateContentType 1
FunctionalTestSetupTrait::$apcuEnsureUniquePrefix protected property The flag to set 'apcu_ensure_unique_prefix' setting. 1
FunctionalTestSetupTrait::$classLoader protected property The class loader to use for installation and initialization of setup.
FunctionalTestSetupTrait::$configDirectories Deprecated protected property The config directories used in this test.
FunctionalTestSetupTrait::$rootUser protected property The "#1" admin user.
FunctionalTestSetupTrait::doInstall protected function Execute the non-interactive installer. 1
FunctionalTestSetupTrait::getDatabaseTypes protected function Returns all supported database driver installer objects.
FunctionalTestSetupTrait::initConfig protected function Initialize various configurations post-installation. 2
FunctionalTestSetupTrait::initKernel protected function Initializes the kernel after installation.
FunctionalTestSetupTrait::initSettings protected function Initialize settings created during install.
FunctionalTestSetupTrait::initUserSession protected function Initializes user 1 for the site to be installed.
FunctionalTestSetupTrait::installDefaultThemeFromClassProperty protected function Installs the default theme defined by `static::$defaultTheme` when needed.
FunctionalTestSetupTrait::installModulesFromClassProperty protected function Install modules defined by `static::$modules`. 1
FunctionalTestSetupTrait::installParameters protected function Returns the parameters that will be used when Simpletest installs Drupal. 9
FunctionalTestSetupTrait::prepareEnvironment protected function Prepares the current environment for running the test. 23
FunctionalTestSetupTrait::prepareRequestForGenerator protected function Creates a mock request and sets it on the generator.
FunctionalTestSetupTrait::prepareSettings protected function Prepares site settings and services before installation. 2
FunctionalTestSetupTrait::rebuildAll protected function Resets and rebuilds the environment after setup.
FunctionalTestSetupTrait::rebuildContainer protected function Rebuilds \Drupal::getContainer().
FunctionalTestSetupTrait::resetAll protected function Resets all data structures after having enabled new modules.
FunctionalTestSetupTrait::setContainerParameter protected function Changes parameters in the services.yml file.
FunctionalTestSetupTrait::setupBaseUrl protected function Sets up the base URL based upon the environment variable.
FunctionalTestSetupTrait::writeSettings protected function Rewrites the settings.php file of the test site.
NodeCreationTrait::createNode protected function Creates a node based on default settings. Aliased as: drupalCreateNode
NodeCreationTrait::getNodeByTitle public function Get a node from the database based on its title. Aliased as: drupalGetNodeByTitle
ParserTest::$defaultTheme protected property The tests don't need markup, so use 'stark' as theme. Overrides BrowserTestBase::$defaultTheme
ParserTest::$modules public static property Modules to enable. Overrides BrowserTestBase::$modules
ParserTest::getInfoAboutForecast private function Internal helper function for getting information about a forecast.
ParserTest::testDifferentDaysOfForecasts public function Test the parser with different days of forecast data.
ParserTest::testParsingOfInformation public function Test parsing of information about a forecast.
ParserTest::weatherDownloadForecast private function Downloads a new forecast from yr.no.
ParserTest::weatherGetForecastsFromDatabase private function Try to fetch forecasts from the database.
ParserTest::weatherGetWeather private function Returns a weather object for the specified GeoID.
ParserTest::weatherParseForecast public function Parses an XML forecast supplied by yr.no.
ParserTest::weatherUpdatePlaces public function Handle updates to the weather_places table.
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
RandomGeneratorTrait::$randomGenerator protected property The random generator.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers. 1
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate public function Callback for random string validation.
RefreshVariablesTrait::refreshVariables protected function Refreshes in-memory configuration and state information. 3
SessionTestTrait::$sessionName protected property The name of the session cookie.
SessionTestTrait::generateSessionName protected function Generates a session cookie name.
SessionTestTrait::getSessionName protected function Returns the session name in use on the child site.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
TestRequirementsTrait::checkModuleRequirements private function Checks missing module requirements.
TestRequirementsTrait::checkRequirements protected function Check module requirements for the Drupal use case. 1
TestRequirementsTrait::getDrupalRoot protected static function Returns the Drupal root directory.
TestSetupTrait::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking.
TestSetupTrait::$container protected property The dependency injection container used in the test.
TestSetupTrait::$kernel protected property The DrupalKernel instance used in the test.
TestSetupTrait::$originalSite protected property The site directory of the original parent site.
TestSetupTrait::$privateFilesDirectory protected property The private file directory for the test environment.
TestSetupTrait::$publicFilesDirectory protected property The public file directory for the test environment.
TestSetupTrait::$siteDirectory protected property The site directory of this test run.
TestSetupTrait::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 2
TestSetupTrait::$tempFilesDirectory protected property The temporary file directory for the test environment.
TestSetupTrait::$testId protected property The test run ID.
TestSetupTrait::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
TestSetupTrait::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
TestSetupTrait::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
TestSetupTrait::prepareDatabasePrefix protected function Generates a database prefix for running tests. 2
UiHelperTrait::$loggedInUser protected property The current user logged in using the Mink controlled browser.
UiHelperTrait::$maximumMetaRefreshCount protected property The number of meta refresh redirects to follow, or NULL if unlimited.
UiHelperTrait::$metaRefreshCount protected property The number of meta refresh redirects followed during ::drupalGet().
UiHelperTrait::assertSession public function Returns WebAssert object. 1
UiHelperTrait::buildUrl protected function Builds an a absolute URL from a system path or a URL object.
UiHelperTrait::checkForMetaRefresh protected function Checks for meta refresh tag and if found call drupalGet() recursively.
UiHelperTrait::click protected function Clicks the element with the given CSS selector.
UiHelperTrait::clickLink protected function Follows a link by complete name.
UiHelperTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
UiHelperTrait::drupalGet protected function Retrieves a Drupal path or an absolute path. 3
UiHelperTrait::drupalLogin protected function Logs in a user using the Mink controlled browser.
UiHelperTrait::drupalLogout protected function Logs a user out of the Mink controlled browser and confirms.
UiHelperTrait::drupalPostForm protected function Executes a form submission.
UiHelperTrait::drupalUserIsLoggedIn protected function Returns whether a given user account is logged in.
UiHelperTrait::getAbsoluteUrl protected function Takes a path and returns an absolute path.
UiHelperTrait::getTextContent protected function Retrieves the plain-text content from the current page.
UiHelperTrait::getUrl protected function Get the current URL from the browser.
UiHelperTrait::prepareRequest protected function Prepare for a request to testing site. 1
UiHelperTrait::submitForm protected function Fills and submits a form.
UserCreationTrait::checkPermissions protected function Checks whether a given list of permission names is valid.
UserCreationTrait::createAdminRole protected function Creates an administrative role.
UserCreationTrait::createRole protected function Creates a role with specified permissions. Aliased as: drupalCreateRole
UserCreationTrait::createUser protected function Create a user with a given set of permissions. Aliased as: drupalCreateUser
UserCreationTrait::grantPermissions protected function Grant permissions to a user role.
UserCreationTrait::setCurrentUser protected function Switch the current logged in user.
UserCreationTrait::setUpCurrentUser protected function Creates a random user account and sets it as current user.
WeatherCommonTestTrait::weatherCreateWeatherArray public function Create a weather array with the forecast data from database.
WeatherCommonTestTrait::weatherFillWeatherSchema public function Provides functionality for filling database tables from source XML file.
WeatherCommonTestTrait::weatherGetInformationAboutGeoid public function Get information about a GeoID.
WeatherCommonTestTrait::weatherGetLinkForGeoId public function Construct the link for the given GeoID.
XdebugRequestTrait::extractCookiesFromRequest protected function Adds xdebug cookies, from request setup.