XmlSitemapTestBase.php 13.5 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Definition of Drupal\xmlsitemap\Tests\XmlSitemapTestBase.
6
 */
7

8
9
10
namespace Drupal\xmlsitemap\Tests;

use Drupal\simpletest\WebTestBase;
11
use Drupal\Core\Url;
12

13
14
15
/**
 * Helper test class with some added functions for testing.
 */
16
abstract class XmlSitemapTestBase extends WebTestBase {
17

18
19
20
21
22
  /**
   * Modules to enable.
   *
   * @var array
   */
23
  public static $modules = ['xmlsitemap'];
24
25
26
27
28
29

  /**
   * The admin user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
30
  protected $admin_user;
31

32
33
34
35
36
37
38
  /**
   * The normal user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $normal_user;

39
40
41
42
43
  /**
   * The state store.
   *
   * @var \Drupal\Core\State\StateInterface
   */
44
  protected $state;
45
46
47
48
49
50

  /**
   * The xmlsitemap.settings configuration object.
   *
   * @var \Drupal\Core\Config\Config
   */
51
  protected $config;
52
53
54
55
56
57

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
58
  protected $moduleHandler;
59

60
61
62
63
64
65
66
  /**
   * The entity manager object.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

67
68
69
70
71
72
73
  /**
   * The language manager object.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

74
75
76
77
78
79
80
  /**
   * The xmlsitemap link storage handler.
   *
   * @var \Drupal\xmlsitemap\XmlSitemapLinkStorageInterface
   */
  protected $linkStorage;

81
82
83
  /**
   * {@inheritdoc}
   */
84
  protected function setUp() {
85
    parent::setUp();
86
87
88
    $this->state = \Drupal::state();
    $this->config = \Drupal::configFactory()->get('xmlsitemap.settings');
    $this->moduleHandler = \Drupal::moduleHandler();
89
    $this->entityManager = \Drupal::entityManager();
90
    $this->languageManager = \Drupal::languageManager();
91
    $this->linkStorage = \Drupal::service('xmlsitemap.link_storage');
92
93
  }

94
95
96
  /**
   * {@inheritdoc}
   */
97
  public function tearDown() {
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    // Capture any (remaining) watchdog errors.
    $this->assertNoWatchdogErrors();

    parent::tearDown();
  }

  /**
   * Assert the page does not respond with the specified response code.
   *
   * @param $code
   *   Response code. For example 200 is a successful page request. For a list
   *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
   * @param $message
   *   Message to display.
   * @return
   *   Assertion result.
   */
115
  protected function assertNoResponse($code, $message = '', $group = 'Browser') {
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
    $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
    return $this->assertFalse($match, $message ? $message : t('HTTP response not expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  }

  /**
   * Check the files directory is created (massive fails if not done).
   *
   * @todo This can be removed when http://drupal.org/node/654752 is fixed.
   */
  protected function checkFilesDirectory() {
    if (!xmlsitemap_check_directory()) {
      $this->fail(t('Sitemap directory was found and writable for testing.'));
    }
  }

  /**
   * Retrieves an XML sitemap.
   *
   * @param $context
   *   An optional array of the XML sitemap's context.
   * @param $options
138
   *   Options to be forwarded to Url::fromUri(). These values will be merged with, but
139
140
141
142
143
144
145
146
   *   always override $sitemap->uri['options'].
   * @param $headers
   *   An array containing additional HTTP request headers, each formatted as
   *   "name: value".
   * @return
   *   The retrieved HTML string, also available as $this->drupalGetContent()
   */
  protected function drupalGetSitemap(array $context = array(), array $options = array(), array $headers = array()) {
147
    $sitemap = $this->entityManager->getStorage('xmlsitemap')->loadByContext($context);
148
149
150
    if (!$sitemap) {
      return $this->fail('Could not load sitemap by context.');
    }
151
152
    $uri = xmlsitemap_sitemap_uri($sitemap);
    return $this->drupalGet($uri['path'], $options + $uri['options'], $headers);
153
154
155
156
157
158
  }

  /**
   * Regenerate the sitemap by setting the regenerate flag and running cron.
   */
  protected function regenerateSitemap() {
159
160
    $this->state->set('xmlsitemap_regenerate_needed', TRUE);
    $this->state->set('xmlsitemap_generated_last', 0);
161
    $this->cronRun();
162
    $this->assertTrue($this->state->get('xmlsitemap_generated_last') && !$this->state->get('xmlsitemap_regenerate_needed'), t('XML sitemaps regenerated and flag cleared.'));
163
164
165
166
  }

  protected function assertSitemapLink($entity_type, $entity_id = NULL) {
    if (is_array($entity_type)) {
167
      $links = $this->linkStorage->loadMultiple($entity_type);
168
169
170
      $link = $links ? reset($links) : FALSE;
    }
    else {
171
      $link = $this->linkStorage->load($entity_type, $entity_id);
172
173
174
175
176
177
178
    }
    $this->assertTrue(is_array($link), 'Link loaded.');
    return $link;
  }

  protected function assertNoSitemapLink($entity_type, $entity_id = NULL) {
    if (is_array($entity_type)) {
179
      $links = $this->linkStorage->loadMultiple($entity_type);
180
181
182
      $link = $links ? reset($links) : FALSE;
    }
    else {
183
      $link = $this->linkStorage->load($entity_type, $entity_id);
184
185
186
187
188
189
    }
    $this->assertFalse($link, 'Link not loaded.');
    return $link;
  }

  protected function assertSitemapLinkVisible($entity_type, $entity_id) {
190
    $link = $this->linkStorage->load($entity_type, $entity_id);
191
192
193
194
    $this->assertTrue($link && $link['access'] && $link['status'], t('Sitemap link @type @id is visible.', array('@type' => $entity_type, '@id' => $entity_id)));
  }

  protected function assertSitemapLinkNotVisible($entity_type, $entity_id) {
195
    $link = $this->linkStorage->load($entity_type, $entity_id);
196
197
198
199
    $this->assertTrue($link && !($link['access'] && $link['status']), t('Sitemap link @type @id is not visible.', array('@type' => $entity_type, '@id' => $entity_id)));
  }

  protected function assertSitemapLinkValues($entity_type, $entity_id, array $conditions) {
200
    $link = $this->linkStorage->load($entity_type, $entity_id);
201
202
203
204
205
206
207
208
209
210
211
212

    if (!$link) {
      return $this->fail(t('Could not load sitemap link for @type @id.', array('@type' => $entity_type, '@id' => $entity_id)));
    }

    foreach ($conditions as $key => $value) {
      if ($value === NULL || $link[$key] === NULL) {
        // For nullable fields, always check for identical values (===).
        $this->assertIdentical($link[$key], $value, t('Identical values for @type @id link field @key.', array('@type' => $entity_type, '@id' => $entity_id, '@key' => $key)));
      }
      else {
        // Otherwise check simple equality (==).
213
        $this->assertEqual($link[$key], $value, t('Equal values for @type @id link field @key - @a - @b.', array('@type' => $entity_type, '@id' => $entity_id, '@key' => $key, '@a' => $link[$key], '@b' => $value)));
214
215
216
217
218
      }
    }
  }

  protected function assertNotSitemapLinkValues($entity_type, $entity_id, array $conditions) {
219
    $link = $this->linkStorage->load($entity_type, $entity_id);
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

    if (!$link) {
      return $this->fail(t('Could not load sitemap link for @type @id.', array('@type' => $entity_type, '@id' => $entity_id)));
    }

    foreach ($conditions as $key => $value) {
      if ($value === NULL || $link[$key] === NULL) {
        // For nullable fields, always check for identical values (===).
        $this->assertNotIdentical($link[$key], $value, t('Not identical values for @type @id link field @key.', array('@type' => $entity_type, '@id' => $entity_id, '@key' => $key)));
      }
      else {
        // Otherwise check simple equality (==).
        $this->assertNotEqual($link[$key], $value, t('Not equal values for link @type @id field @key.', array('@type' => $entity_type, '@id' => $entity_id, '@key' => $key)));
      }
    }
  }

  protected function assertRawSitemapLinks() {
    $links = func_get_args();
    foreach ($links as $link) {
240
      $path = Url::fromUri($link['loc'], array('language' => xmlsitemap_language_load($link['language']), 'absolute' => TRUE));
241
242
243
244
245
246
247
      $this->assertRaw($link['loc'], t('Link %path found in the sitemap.', array('%path' => $path)));
    }
  }

  protected function assertNoRawSitemapLinks() {
    $links = func_get_args();
    foreach ($links as $link) {
248
      $path = Url::fromUri($link['loc'], array('language' => xmlsitemap_language_load($link['language']), 'absolute' => TRUE));
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
      $this->assertNoRaw($link['loc'], t('Link %path not found in the sitemap.', array('%path' => $path)));
    }
  }

  protected function addSitemapLink(array $link = array()) {
    $last_id = &drupal_static(__FUNCTION__, 1);

    $link += array(
      'type' => 'testing',
      'id' => $last_id,
      'access' => 1,
      'status' => 1,
    );

    // Make the default path easier to read than a random string.
    $link += array('loc' => $link['type'] . '-' . $link['id']);

    $last_id = max($last_id, $link['id']) + 1;
267
    $this->linkStorage->save($link);
268
269
270
271
272
273
274
    return $link;
  }

  protected function assertFlag($variable, $assert_value = TRUE, $reset_if_true = TRUE) {
    $value = xmlsitemap_var($variable);

    if ($reset_if_true && $value) {
275
276
      $state_variables = xmlsitemap_state_variables();
      if (isset($state_variables[$variable])) {
277
        $this->state->set($variable, FALSE);
278
279
      }
      else {
280
        $this->config->set($variable, FALSE)->save();
281
      }
282
283
284
285
286
287
288
289
290
    }

    return $this->assertEqual($value, $assert_value, "xmlsitemap_$variable is " . ($assert_value ? 'TRUE' : 'FALSE'));
  }

  protected function assertXMLSitemapProblems($problem_text = FALSE) {
    $this->drupalGet('admin/config/search/xmlsitemap');
    $this->assertText(t('One or more problems were detected with your XML sitemap configuration'));
    if ($problem_text) {
291
      $this->clickLink(t('status report'));
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
      $this->assertText($problem_text);
    }
  }

  protected function assertNoXMLSitemapProblems() {
    $this->drupalGet('admin/config/search/xmlsitemap');
    $this->assertNoText(t('One or more problems were detected with your XML sitemap configuration'));
  }

  /**
   * Fetch all seen watchdog messages.
   *
   * @todo Add unit tests for this function.
   */
  protected function getWatchdogMessages(array $conditions = array(), $reset = FALSE) {
    static $seen_ids = array();

309
    if (!$this->moduleHandler->moduleExists('dblog') || $reset) {
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
      $seen_ids = array();
      return array();
    }

    $query = db_select('watchdog');
    $query->fields('watchdog', array('wid', 'type', 'severity', 'message', 'variables', 'timestamp'));
    foreach ($conditions as $field => $value) {
      if ($field == 'variables' && !is_string($value)) {
        $value = serialize($value);
      }
      $query->condition($field, $value);
    }
    if ($seen_ids) {
      $query->condition('wid', $seen_ids, 'NOT IN');
    }
    $query->orderBy('timestamp');
    $messages = $query->execute()->fetchAllAssoc('wid');

    $seen_ids = array_merge($seen_ids, array_keys($messages));
    return $messages;
  }

  protected function assertWatchdogMessage(array $conditions, $message = 'Watchdog message found.') {
    $this->assertTrue($this->getWatchdogMessages($conditions), $message);
  }

  protected function assertNoWatchdogMessage(array $conditions, $message = 'Watchdog message not found.') {
    $this->assertFalse($this->getWatchdogMessages($conditions), $message);
  }

  /**
   * Check that there were no watchdog errors or worse.
   */
  protected function assertNoWatchdogErrors() {
    $messages = $this->getWatchdogMessages();
    $verbose = array();

    foreach ($messages as $message) {
      $message->text = $this->formatWatchdogMessage($message);
      if (in_array($message->severity, array(WATCHDOG_EMERGENCY, WATCHDOG_ALERT, WATCHDOG_CRITICAL, WATCHDOG_ERROR, WATCHDOG_WARNING))) {
        $this->fail($message->text);
      }
      $verbose[] = $message->text;
    }

    if ($verbose) {
      array_unshift($verbose, '<h2>Watchdog messages</h2>');
357
      $this->verbose(implode('<br />', $verbose), 'Watchdog messages from test run');
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    }

    // Clear the seen watchdog messages since we've failed on any errors.
    $this->getWatchdogMessages(array(), TRUE);
  }

  /**
   * Format a watchdog message in a one-line summary.
   *
   * @param $message
   *   A watchdog messsage object.
   * @return
   *   A string containing the watchdog message's timestamp, severity, type,
   *   and actual message.
   */
373
  private function formatWatchdogMessage($message) {
374
375
376
377
378
379
380
381
382
383
384
    static $levels;

    if (!isset($levels)) {
      module_load_include('admin.inc', 'dblog');
      $levels = watchdog_severity_levels();
    }

    return t('@timestamp - @severity - @type - !message', array(
      '@timestamp' => $message->timestamp,
      '@severity' => $levels[$message->severity],
      '@type' => $message->type,
385
        // '!message' => theme_dblog_message(array('event' => $message, 'link' => FALSE)),
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
    ));
  }

  /**
   * Log verbose message in a text file.
   *
   * This is a copy of DrupalWebTestCase->verbose() but allows a customizable
   * summary message rather than hard-coding 'Verbose message'.
   *
   * @param $verbose_message
   *   The verbose message to be stored.
   * @param $message
   *   Message to display.
   * @see simpletest_verbose()
   *
   * @todo Remove when http://drupal.org/node/800426 is fixed.
   */
  protected function verbose($verbose_message, $message = 'Verbose message') {
404
    if ($id = parent::verbose($verbose_message)) {
405
      $url = file_create_url($this->originalFileDirectory . '/simpletest/verbose/' . get_class($this) . '-' . $id . '.html');
406
      $message_url = Url::fromUri($url, array('attributes' => array('target' => '_blank')));
407
      $this->error($this->l($message, $message_url), 'User notice');
408
409
410
411
    }
  }

}