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

namespace Drupal\xmlsitemap\Tests;

5
use Drupal\Core\Logger\RfcLogLevel;
6
use Drupal\Core\Url;
7
use Drupal\simpletest\WebTestBase;
8
use Drupal\xmlsitemap\Entity\XmlSitemap;
9

10
11
12
/**
 * Helper test class with some added functions for testing.
 */
13
abstract class XmlSitemapTestBase extends WebTestBase {
14

15
16
17
18
19
  /**
   * Modules to enable.
   *
   * @var array
   */
amateescu's avatar
amateescu committed
20
  public static $modules = ['node', 'system', 'user', 'xmlsitemap'];
21
22
23
24
25
26

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

29
30
31
32
33
34
35
  /**
   * The normal user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $normal_user;

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

  /**
   * The xmlsitemap.settings configuration object.
   *
   * @var \Drupal\Core\Config\Config
   */
48
  protected $config;
49
50
51
52
53
54

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

57
58
59
60
61
62
63
  /**
   * The language manager object.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

64
65
66
67
68
69
70
  /**
   * The xmlsitemap link storage handler.
   *
   * @var \Drupal\xmlsitemap\XmlSitemapLinkStorageInterface
   */
  protected $linkStorage;

71
72
73
  /**
   * {@inheritdoc}
   */
74
  protected function setUp() {
75
    parent::setUp();
amateescu's avatar
amateescu committed
76

77
    $this->state = \Drupal::state();
amateescu's avatar
amateescu committed
78
    $this->config = \Drupal::configFactory()->getEditable('xmlsitemap.settings');
79
    $this->moduleHandler = \Drupal::moduleHandler();
80
    $this->languageManager = \Drupal::languageManager();
81
    $this->linkStorage = \Drupal::service('xmlsitemap.link_storage');
82
83
84

    // Create the Article and Page content types.
    if ($this->profile != 'standard') {
amateescu's avatar
amateescu committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
      $this->drupalCreateContentType([
        'type' => 'article',
        'name' => 'Article',
      ]);
      $this->drupalCreateContentType([
      'type' => 'page',
      'name' => 'Basic page',
      'settings' => [
        // Set proper default options for the page content type.
        'node' => [
          'options' => ['promote' => FALSE],
          'submitted' => FALSE,
        ],
      ]]);
99
    }
100
101
  }

102
103
104
  /**
   * {@inheritdoc}
   */
105
  public function tearDown() {
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    // 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.
   */
123
  protected function assertNoResponse($code, $message = '', $group = 'Browser') {
124
125
    $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
    $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
126
    return $this->assertFalse($match, $message ? $message : t('HTTP response not expected @code, actual @curl_code', array('@code' => $code, '@curl_code' => $curl_code)), t('Browser'));
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
  }

  /**
   * 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
146
   *   Options to be forwarded to Url::fromUri(). These values will be merged with, but
147
148
149
150
151
152
153
154
   *   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()) {
155
    $sitemap = XmlSitemap::loadByContext($context);
156
157
158
    if (!$sitemap) {
      return $this->fail('Could not load sitemap by context.');
    }
159
160
    $uri = xmlsitemap_sitemap_uri($sitemap);
    return $this->drupalGet($uri['path'], $options + $uri['options'], $headers);
161
162
163
164
165
166
  }

  /**
   * Regenerate the sitemap by setting the regenerate flag and running cron.
   */
  protected function regenerateSitemap() {
167
168
    $this->state->set('xmlsitemap_regenerate_needed', TRUE);
    $this->state->set('xmlsitemap_generated_last', 0);
169
    $this->cronRun();
170
    $this->assertTrue($this->state->get('xmlsitemap_generated_last') && !$this->state->get('xmlsitemap_regenerate_needed'), t('XML sitemaps regenerated and flag cleared.'));
171
172
173
174
  }

  protected function assertSitemapLink($entity_type, $entity_id = NULL) {
    if (is_array($entity_type)) {
175
      $links = $this->linkStorage->loadMultiple($entity_type);
176
177
178
      $link = $links ? reset($links) : FALSE;
    }
    else {
179
      $link = $this->linkStorage->load($entity_type, $entity_id);
180
181
182
183
184
185
186
    }
    $this->assertTrue(is_array($link), 'Link loaded.');
    return $link;
  }

  protected function assertNoSitemapLink($entity_type, $entity_id = NULL) {
    if (is_array($entity_type)) {
187
      $links = $this->linkStorage->loadMultiple($entity_type);
188
189
190
      $link = $links ? reset($links) : FALSE;
    }
    else {
191
      $link = $this->linkStorage->load($entity_type, $entity_id);
192
193
194
195
196
197
    }
    $this->assertFalse($link, 'Link not loaded.');
    return $link;
  }

  protected function assertSitemapLinkVisible($entity_type, $entity_id) {
198
    $link = $this->linkStorage->load($entity_type, $entity_id);
199
200
201
202
    $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) {
203
    $link = $this->linkStorage->load($entity_type, $entity_id);
204
205
206
207
    $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) {
208
    $link = $this->linkStorage->load($entity_type, $entity_id);
209
210
211
212
213
214
215
216
217
218
219
220

    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 (==).
221
        $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)));
222
223
224
225
226
      }
    }
  }

  protected function assertNotSitemapLinkValues($entity_type, $entity_id, array $conditions) {
227
    $link = $this->linkStorage->load($entity_type, $entity_id);
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

    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) {
amateescu's avatar
amateescu committed
248
      $path = Url::fromUri('base://' . $link['loc'], array('language' => xmlsitemap_language_load($link['language']), 'absolute' => TRUE))->toString();
249
250
251
252
253
254
255
      $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) {
amateescu's avatar
amateescu committed
256
      $path = Url::fromUri('base://' . $link['loc'], array('language' => xmlsitemap_language_load($link['language']), 'absolute' => TRUE))->toString();
257
258
259
260
261
262
263
264
265
      $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',
amateescu's avatar
amateescu committed
266
      'subtype' => '',
267
268
269
270
271
272
273
274
275
      '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;
276
    $this->linkStorage->save($link);
277
278
279
280
281
282
283
    return $link;
  }

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

    if ($reset_if_true && $value) {
284
285
      $state_variables = xmlsitemap_state_variables();
      if (isset($state_variables[$variable])) {
286
        $this->state->set($variable, FALSE);
287
288
      }
      else {
289
        $this->config->set($variable, FALSE)->save();
290
      }
291
292
293
294
295
296
297
298
299
    }

    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) {
300
      $this->clickLink(t('status report'));
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
      $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();

318
    if (!$this->moduleHandler->moduleExists('dblog') || $reset) {
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
357
      $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);
358
      if (in_array($message->severity, array(RfcLogLevel::EMERGENCY, RfcLogLevel::ALERT, RfcLogLevel::CRITICAL, RfcLogLevel::ERROR, RfcLogLevel::WARNING))) {
359
360
361
362
363
364
365
        $this->fail($message->text);
      }
      $verbose[] = $message->text;
    }

    if ($verbose) {
      array_unshift($verbose, '<h2>Watchdog messages</h2>');
366
      $this->verbose(implode('<br />', $verbose), 'Watchdog messages from test run');
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
    }

    // 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.
   */
382
  private function formatWatchdogMessage($message) {
383
384
385
386
    static $levels;

    if (!isset($levels)) {
      module_load_include('admin.inc', 'dblog');
387
      $levels = RfcLogLevel::getLevels();
388
389
    }

390
    return t('@timestamp - @severity - @type - @message', array(
391
392
393
      '@timestamp' => $message->timestamp,
      '@severity' => $levels[$message->severity],
      '@type' => $message->type,
394
        // '@message' => theme_dblog_message(array('event' => $message, 'link' => FALSE)),
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    ));
  }

  /**
   * 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') {
413
    if ($id = parent::verbose($verbose_message)) {
414
      $url = file_create_url($this->originalFileDirectory . '/simpletest/verbose/' . get_class($this) . '-' . $id . '.html');
415
      $message_url = Url::fromUri($url, array('attributes' => array('target' => '_blank')));
416
      $this->error($this->l($message, $message_url), 'User notice');
417
418
419
420
    }
  }

}