Projet

Général

Profil

Paste
Télécharger (38,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / token / token.test @ d719f12f

1
<?php
2

    
3
/**
4
 * @file
5
 * Test integration for the token module.
6
 */
7

    
8
/**
9
 * Helper test class with some added functions for testing.
10
 */
11
class TokenTestHelper extends DrupalWebTestCase {
12
  protected $profile = 'testing';
13

    
14
  public function setUp($modules = array()) {
15
    $modules[] = 'path';
16
    $modules[] = 'token';
17
    $modules[] = 'token_test';
18
    parent::setUp($modules);
19

    
20
    variable_set('clean_url', 1);
21
  }
22

    
23
  function assertToken($type, array $data, $token, $expected, array $options = array()) {
24
    return $this->assertTokens($type, $data, array($token => $expected), $options);
25
  }
26

    
27
  function assertTokens($type, array $data, array $tokens, array $options = array()) {
28
    $input = $this->mapTokenNames($type, array_keys($tokens));
29
    $replacements = token_generate($type, $input, $data, $options);
30
    foreach ($tokens as $name => $expected) {
31
      $token = $input[$name];
32
      if (!isset($expected)) {
33
        $this->assertTrue(!isset($values[$token]), t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token)));
34
      }
35
      elseif (!isset($replacements[$token])) {
36
        $this->fail(t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token)));
37
      }
38
      elseif (!empty($options['regex'])) {
39
        $this->assertTrue(preg_match('/^' . $expected . '$/', $replacements[$token]), t("Token value for @token was '@actual', matching regular expression pattern '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected)));
40
      }
41
      else {
42
        $this->assertIdentical($replacements[$token], $expected, t("Token value for @token was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected)));
43
      }
44
    }
45

    
46
    return $replacements;
47
  }
48

    
49
  function mapTokenNames($type, array $tokens = array()) {
50
    $return = array();
51
    foreach ($tokens as $token) {
52
      $return[$token] = "[$type:$token]";
53
    }
54
    return $return;
55
  }
56

    
57
  function assertNoTokens($type, array $data, array $tokens, array $options = array()) {
58
    $input = $this->mapTokenNames($type, $tokens);
59
    $replacements = token_generate($type, $input, $data, $options);
60
    foreach ($tokens as $name) {
61
      $token = $input[$name];
62
      $this->assertTrue(!isset($replacements[$token]), t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token)));
63
    }
64
    return $values;
65
  }
66

    
67
  function saveAlias($source, $alias, $language = LANGUAGE_NONE) {
68
    $alias = array(
69
      'source' => $source,
70
      'alias' => $alias,
71
      'language' => $language,
72
    );
73
    path_save($alias);
74
    return $alias;
75
  }
76

    
77
  function saveEntityAlias($entity_type, $entity, $alias, $language = LANGUAGE_NONE) {
78
    $uri = entity_uri($entity_type, $entity);
79
    return $this->saveAlias($uri['path'], $alias, $language);
80
  }
81

    
82
  /**
83
   * Make a page request and test for token generation.
84
   */
85
  function assertPageTokens($url, array $tokens, array $data = array(), array $options = array()) {
86
    if (empty($tokens)) {
87
      return TRUE;
88
    }
89

    
90
    $token_page_tokens = array(
91
      'tokens' => $tokens,
92
      'data' => $data,
93
      'options' => $options,
94
    );
95
    variable_set('token_page_tokens', $token_page_tokens);
96

    
97
    $options += array('url_options' => array());
98
    $this->drupalGet($url, $options['url_options']);
99
    $this->refreshVariables();
100
    $result = variable_get('token_page_tokens', array());
101

    
102
    if (!isset($result['values']) || !is_array($result['values'])) {
103
      return $this->fail('Failed to generate tokens.');
104
    }
105

    
106
    foreach ($tokens as $token => $expected) {
107
      if (!isset($expected)) {
108
        $this->assertTrue(!isset($result['values'][$token]) || $result['values'][$token] === $token, t("Token value for @token was not generated.", array('@token' => $token)));
109
      }
110
      elseif (!isset($result['values'][$token])) {
111
        $this->fail(t('Failed to generate token @token.', array('@token' => $token)));
112
      }
113
      else {
114
        $this->assertIdentical($result['values'][$token], (string) $expected, t("Token value for @token was '@actual', expected value '@expected'.", array('@token' => $token, '@actual' => $result['values'][$token], '@expected' => $expected)));
115
      }
116
    }
117
  }
118
}
119

    
120
class TokenUnitTestCase extends TokenTestHelper {
121
  public static function getInfo() {
122
    return array(
123
      'name' => 'Token unit tests',
124
      'description' => 'Test basic, low-level token functions.',
125
      'group' => 'Token',
126
    );
127
  }
128

    
129
  /**
130
   * Test token_get_invalid_tokens() and token_get_invalid_tokens_by_context().
131
   */
132
  public function testGetInvalidTokens() {
133
    $tests = array();
134
    $tests[] = array(
135
      'valid tokens' => array(
136
        '[node:title]',
137
        '[node:created:short]',
138
        '[node:created:custom:invalid]',
139
        '[node:created:custom:mm-YYYY]',
140
        '[node:colons:in:name]',
141
        '[site:name]',
142
        '[site:slogan]',
143
        '[current-date:short]',
144
        '[current-user:uid]',
145
        '[current-user:ip-address]',
146
      ),
147
      'invalid tokens' => array(
148
        '[node:title:invalid]',
149
        '[node:created:invalid]',
150
        '[node:created:short:invalid]',
151
        '[node:colons:in:name:invalid]',
152
        '[invalid:title]',
153
        '[site:invalid]',
154
        '[user:ip-address]',
155
        '[user:uid]',
156
        '[comment:cid]',
157
        // Deprecated tokens
158
        '[node:tnid]',
159
        '[node:type]',
160
        '[node:type-name]',
161
        '[date:short]',
162
      ),
163
      'types' => array('node'),
164
    );
165
    $tests[] = array(
166
      'valid tokens' => array(
167
        '[node:title]',
168
        '[node:created:short]',
169
        '[node:created:custom:invalid]',
170
        '[node:created:custom:mm-YYYY]',
171
        '[node:colons:in:name]',
172
        '[site:name]',
173
        '[site:slogan]',
174
        '[user:uid]',
175
        '[current-date:short]',
176
        '[current-user:uid]',
177
      ),
178
      'invalid tokens' => array(
179
        '[node:title:invalid]',
180
        '[node:created:invalid]',
181
        '[node:created:short:invalid]',
182
        '[node:colons:in:name:invalid]',
183
        '[invalid:title]',
184
        '[site:invalid]',
185
        '[user:ip-address]',
186
        '[comment:cid]',
187
        // Deprecated tokens
188
        '[node:tnid]',
189
        '[node:type]',
190
        '[node:type-name]',
191
      ),
192
      'types' => array('all'),
193
    );
194

    
195
    foreach ($tests as $test) {
196
      $tokens = array_merge($test['valid tokens'], $test['invalid tokens']);
197
      shuffle($tokens);
198

    
199
      $invalid_tokens = token_get_invalid_tokens_by_context(implode(' ', $tokens), $test['types']);
200

    
201
      sort($invalid_tokens);
202
      sort($test['invalid tokens']);
203
      $this->assertEqual($invalid_tokens, $test['invalid tokens'], 'Invalid tokens detected properly: ' . implode(', ', $invalid_tokens));
204
    }
205
  }
206
}
207

    
208
class TokenURLTestCase extends TokenTestHelper {
209
  public static function getInfo() {
210
    return array(
211
      'name' => 'URL token tests',
212
      'description' => 'Test the URL tokens.',
213
      'group' => 'Token',
214
    );
215
  }
216

    
217
  public function setUp($modules = array()) {
218
    parent::setUp($modules);
219
    $this->saveAlias('node/1', 'first-node');
220
  }
221

    
222
  function testURLTokens() {
223
    $tokens = array(
224
      'absolute' => 'http://example.com/first-node',
225
      'relative' => base_path() . 'first-node',
226
      'path' => 'first-node',
227
      'brief' => 'example.com/first-node',
228
      'args:value:0' => 'first-node',
229
      'args:value:1' => NULL,
230
      'args:value:N' => NULL,
231
      'unaliased' => 'http://example.com/node/1',
232
      'unaliased:relative' => base_path() . 'node/1',
233
      'unaliased:path' => 'node/1',
234
      'unaliased:brief' => 'example.com/node/1',
235
      'unaliased:args:value:0' => 'node',
236
      'unaliased:args:value:1' => '1',
237
      'unaliased:args:value:2' => NULL,
238
      // Deprecated tokens.
239
      'alias' => 'first-node',
240
    );
241
    $this->assertTokens('url', array('path' => 'node/1', 'options' => array('base_url' => 'http://example.com')), $tokens);
242
  }
243
}
244

    
245
class TokenCommentTestCase extends TokenTestHelper {
246
  public static function getInfo() {
247
    return array(
248
      'name' => 'Comment token tests',
249
      'description' => 'Test the comment tokens.',
250
      'group' => 'Token',
251
    );
252
  }
253

    
254
  public function setUp($modules = array()) {
255
    $modules[] = 'comment';
256
    parent::setUp($modules);
257
  }
258

    
259
  function testCommentTokens() {
260
    $node = $this->drupalCreateNode(array('comment' => COMMENT_NODE_OPEN));
261

    
262
    $parent_comment = new stdClass;
263
    $parent_comment->nid = $node->nid;
264
    $parent_comment->pid = 0;
265
    $parent_comment->cid = NULL;
266
    $parent_comment->uid = 0;
267
    $parent_comment->name = 'anonymous user';
268
    $parent_comment->mail = 'anonymous@example.com';
269
    $parent_comment->subject = $this->randomName();
270
    $parent_comment->timestamp = mt_rand($node->created, REQUEST_TIME);
271
    $parent_comment->language = LANGUAGE_NONE;
272
    $parent_comment->body[LANGUAGE_NONE][0] = $this->randomName();
273
    comment_save($parent_comment);
274

    
275
    $tokens = array(
276
      'url' => url('comment/' . $parent_comment->cid, array('fragment' => 'comment-' . $parent_comment->cid, 'absolute' => TRUE)),
277
      'url:absolute' => url('comment/' . $parent_comment->cid, array('fragment' => 'comment-' . $parent_comment->cid, 'absolute' => TRUE)),
278
      'url:relative' => url('comment/' . $parent_comment->cid, array('fragment' => 'comment-' . $parent_comment->cid, 'absolute' => FALSE)),
279
      'url:path' => 'comment/' . $parent_comment->cid,
280
      'parent:url:absolute' => NULL,
281
    );
282
    $this->assertTokens('comment', array('comment' => $parent_comment), $tokens);
283

    
284
    $comment = new stdClass();
285
    $comment->nid = $node->nid;
286
    $comment->pid = $parent_comment->cid;
287
    $comment->cid = NULL;
288
    $comment->uid = 1;
289
    $comment->subject = $this->randomName();
290
    $comment->timestamp = mt_rand($parent_comment->created, REQUEST_TIME);
291
    $comment->language = LANGUAGE_NONE;
292
    $comment->body[LANGUAGE_NONE][0] = $this->randomName();
293
    comment_save($comment);
294

    
295
    $tokens = array(
296
      'url' => url('comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid, 'absolute' => TRUE)),
297
      'url:absolute' => url('comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid, 'absolute' => TRUE)),
298
      'url:relative' => url('comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid, 'absolute' => FALSE)),
299
      'url:path' => 'comment/' . $comment->cid,
300
      'parent:url:absolute' => url('comment/' . $parent_comment->cid, array('fragment' => 'comment-' . $parent_comment->cid, 'absolute' => TRUE)),
301
    );
302
    $this->assertTokens('comment', array('comment' => $comment), $tokens);
303
  }
304
}
305

    
306
class TokenNodeTestCase extends TokenTestHelper {
307
  protected $profile = 'standard';
308

    
309
  public static function getInfo() {
310
    return array(
311
      'name' => 'Node and content type token tests',
312
      'description' => 'Test the node and content type tokens.',
313
      'group' => 'Token',
314
    );
315
  }
316

    
317
  function testNodeTokens() {
318
    $source_node = $this->drupalCreateNode(array('log' => $this->randomName(), 'path' => array('alias' => 'content/source-node')));
319
    $tokens = array(
320
      'source' => NULL,
321
      'source:nid' => NULL,
322
      'log' => $source_node->log,
323
      'url:path' => 'content/source-node',
324
      'url:absolute' => url("node/{$source_node->nid}", array('absolute' => TRUE)),
325
      'url:relative' => url("node/{$source_node->nid}", array('absolute' => FALSE)),
326
      'url:unaliased:path' => "node/{$source_node->nid}",
327
      'content-type' => 'Basic page',
328
      'content-type:name' => 'Basic page',
329
      'content-type:machine-name' => 'page',
330
      'content-type:description' => "Use <em>basic pages</em> for your static content, such as an 'About us' page.",
331
      'content-type:node-count' => 1,
332
      'content-type:edit-url' => url('admin/structure/types/manage/page', array('absolute' => TRUE)),
333
      // Deprecated tokens.
334
      'tnid' => 0,
335
      'type' => 'page',
336
      'type-name' => 'Basic page',
337
      'url:alias' => 'content/source-node',
338
    );
339
    $this->assertTokens('node', array('node' => $source_node), $tokens);
340

    
341
    $translated_node = $this->drupalCreateNode(array('tnid' => $source_node->nid, 'type' => 'article'));
342
    $tokens = array(
343
      'source' => $source_node->title,
344
      'source:nid' => $source_node->nid,
345
      'log' => '',
346
      'url:path' => "node/{$translated_node->nid}",
347
      'url:absolute' => url("node/{$translated_node->nid}", array('absolute' => TRUE)),
348
      'url:relative' => url("node/{$translated_node->nid}", array('absolute' => FALSE)),
349
      'url:unaliased:path' => "node/{$translated_node->nid}",
350
      'content-type' => 'Article',
351
      'content-type:name' => 'Article',
352
      'content-type:machine-name' => 'article',
353
      'content-type:description' => "Use <em>articles</em> for time-sensitive content like news, press releases or blog posts.",
354
      'content-type:node-count' => 1,
355
      'content-type:edit-url' => url('admin/structure/types/manage/article', array('absolute' => TRUE)),
356
      // Deprecated tokens.
357
      'type' => 'article',
358
      'type-name' => 'Article',
359
      'tnid' => $source_node->nid,
360
      'url:alias' => "node/{$translated_node->nid}",
361
    );
362
    $this->assertTokens('node', array('node' => $translated_node), $tokens);
363
  }
364
}
365

    
366
class TokenMenuTestCase extends TokenTestHelper {
367
  public static function getInfo() {
368
    return array(
369
      'name' => 'Menu link and menu token tests',
370
      'description' => 'Test the menu tokens.',
371
      'group' => 'Token',
372
    );
373
  }
374

    
375
  public function setUp($modules = array()) {
376
    $modules[] = 'menu';
377
    parent::setUp($modules);
378
  }
379

    
380
  function testMenuTokens() {
381
    // Add a root link.
382
    $root_link = array(
383
      'link_path' => 'root',
384
      'link_title' => 'Root link',
385
      'menu_name' => 'main-menu',
386
    );
387
    menu_link_save($root_link);
388

    
389
    // Add another link with the root link as the parent
390
    $parent_link = array(
391
      'link_path' => 'root/parent',
392
      'link_title' => 'Parent link',
393
      'menu_name' => 'main-menu',
394
      'plid' => $root_link['mlid'],
395
    );
396
    menu_link_save($parent_link);
397

    
398
    // Test menu link tokens.
399
    $tokens = array(
400
      'mlid' => $parent_link['mlid'],
401
      'title' => 'Parent link',
402
      'menu' => 'Main menu',
403
      'menu:name' => 'Main menu',
404
      'menu:machine-name' => 'main-menu',
405
      'menu:description' => 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.',
406
      'menu:menu-link-count' => 2,
407
      'menu:edit-url' => url("admin/structure/menu/manage/main-menu", array('absolute' => TRUE)),
408
      'url' => url('root/parent', array('absolute' => TRUE)),
409
      'url:absolute' => url('root/parent', array('absolute' => TRUE)),
410
      'url:relative' => url('root/parent', array('absolute' => FALSE)),
411
      'url:path' => 'root/parent',
412
      'url:alias' => 'root/parent',
413
      'edit-url' => url("admin/structure/menu/item/{$parent_link['mlid']}/edit", array('absolute' => TRUE)),
414
      'parent' => 'Root link',
415
      'parent:mlid' => $root_link['mlid'],
416
      'parent:title' => 'Root link',
417
      'parent:menu' => 'Main menu',
418
      'parent:parent' => NULL,
419
      'parents' => 'Root link',
420
      'parents:count' => 1,
421
      'parents:keys' => $root_link['mlid'],
422
      'root' => 'Root link',
423
      'root:mlid' => $root_link['mlid'],
424
      'root:parent' => NULL,
425
      'root:root' => NULL,
426
    );
427
    $this->assertTokens('menu-link', array('menu-link' => $parent_link), $tokens);
428

    
429
    // Add a node menu link
430
    $node_link = array(
431
      'enabled' => TRUE,
432
      'link_title' => 'Node link',
433
      'plid' => $parent_link['mlid'],
434
      'customized' => 0,
435
      'description' => '',
436
    );
437
    $node = $this->drupalCreateNode(array('menu' => $node_link));
438

    
439
    // Test [node:menu] tokens.
440
    $tokens = array(
441
      'menu-link' => 'Node link',
442
      'menu-link:mlid' => $node->menu['mlid'],
443
      'menu-link:title' => 'Node link',
444
      'menu-link:menu' => 'Main menu',
445
      'menu-link:url' => url('node/' . $node->nid, array('absolute' => TRUE)),
446
      'menu-link:url:path' => 'node/' . $node->nid,
447
      'menu-link:edit-url' => url("admin/structure/menu/item/{$node->menu['mlid']}/edit", array('absolute' => TRUE)),
448
      'menu-link:parent' => 'Parent link',
449
      'menu-link:parent:mlid' => $node->menu['plid'],
450
      'menu-link:parent:mlid' => $parent_link['mlid'],
451
      'menu-link:parents' => 'Root link, Parent link',
452
      'menu-link:parents:count' => 2,
453
      'menu-link:parents:keys' => $root_link['mlid'] . ', ' . $parent_link['mlid'],
454
      'menu-link:root' => 'Root link',
455
      'menu-link:root:mlid' => $root_link['mlid'],
456
    );
457
    $this->assertTokens('node', array('node' => $node), $tokens);
458

    
459
    // Reload the node which will not have $node->menu defined and re-test.
460
    $loaded_node = node_load($node->nid);
461
    $this->assertTokens('node', array('node' => $loaded_node), $tokens);
462

    
463
    // Regression test for http://drupal.org/node/1317926 to ensure the
464
    // original node object is not changed when calling menu_node_prepare().
465
    $this->assertTrue(!isset($loaded_node->menu), t('The $node->menu property was not modified during token replacement.'), 'Regression');
466
  }
467
}
468

    
469
class TokenTaxonomyTestCase extends TokenTestHelper {
470
  protected $vocab;
471

    
472
  public static function getInfo() {
473
    return array(
474
      'name' => 'Taxonomy and vocabulary token tests',
475
      'description' => 'Test the taxonomy tokens.',
476
      'group' => 'Token',
477
    );
478
  }
479

    
480
  public function setUp($modules = array()) {
481
    $modules[] = 'taxonomy';
482
    parent::setUp($modules);
483

    
484
    // Create the default tags vocabulary.
485
    $vocabulary = (object) array(
486
      'name' => 'Tags',
487
      'machine_name' => 'tags',
488
    );
489
    taxonomy_vocabulary_save($vocabulary);
490
    $this->vocab = $vocabulary;
491
  }
492

    
493
  /**
494
   * Test the additional taxonomy term tokens.
495
   */
496
  function testTaxonomyTokens() {
497
    $root_term = $this->addTerm($this->vocab, array('name' => 'Root term', 'path' => array('alias' => 'root-term')));
498
    $tokens = array(
499
      'url' => url("taxonomy/term/{$root_term->tid}", array('absolute' => TRUE)),
500
      'url:absolute' => url("taxonomy/term/{$root_term->tid}", array('absolute' => TRUE)),
501
      'url:relative' => url("taxonomy/term/{$root_term->tid}", array('absolute' => FALSE)),
502
      'url:path' => 'root-term',
503
      'url:unaliased:path' => "taxonomy/term/{$root_term->tid}",
504
      'edit-url' => url("taxonomy/term/{$root_term->tid}/edit", array('absolute' => TRUE)),
505
      'parents' => NULL,
506
      'parents:count' => NULL,
507
      'parents:keys' => NULL,
508
      'root' => NULL,
509
      // Deprecated tokens
510
      'url:alias' => 'root-term',
511
    );
512
    $this->assertTokens('term', array('term' => $root_term), $tokens);
513

    
514
    $parent_term = $this->addTerm($this->vocab, array('name' => 'Parent term', 'parent' => $root_term->tid));
515
    $tokens = array(
516
      'url' => url("taxonomy/term/{$parent_term->tid}", array('absolute' => TRUE)),
517
      'url:absolute' => url("taxonomy/term/{$parent_term->tid}", array('absolute' => TRUE)),
518
      'url:relative' => url("taxonomy/term/{$parent_term->tid}", array('absolute' => FALSE)),
519
      'url:path' => "taxonomy/term/{$parent_term->tid}",
520
      'url:unaliased:path' => "taxonomy/term/{$parent_term->tid}",
521
      'edit-url' => url("taxonomy/term/{$parent_term->tid}/edit", array('absolute' => TRUE)),
522
      'parents' => 'Root term',
523
      'parents:count' => 1,
524
      'parents:keys' => $root_term->tid,
525
      'root' => check_plain($root_term->name),
526
      'root:tid' => $root_term->tid,
527
      // Deprecated tokens
528
      'url:alias' => "taxonomy/term/{$parent_term->tid}",
529
    );
530
    $this->assertTokens('term', array('term' => $parent_term), $tokens);
531

    
532
    $term = $this->addTerm($this->vocab, array('name' => 'Test term', 'parent' => $parent_term->tid));
533
    $tokens = array(
534
      'parents' => 'Root term, Parent term',
535
      'parents:count' => 2,
536
      'parents:keys' => implode(', ', array($root_term->tid, $parent_term->tid)),
537
    );
538
    $this->assertTokens('term', array('term' => $term), $tokens);
539
  }
540

    
541
  /**
542
   * Test the additional vocabulary tokens.
543
   */
544
  function testVocabularyTokens() {
545
    $vocabulary = $this->vocab;
546
    $tokens = array(
547
      'machine-name' => 'tags',
548
      'edit-url' => url("admin/structure/taxonomy/{$vocabulary->machine_name}/edit", array('absolute' => TRUE)),
549
    );
550
    $this->assertTokens('vocabulary', array('vocabulary' => $vocabulary), $tokens);
551
  }
552

    
553
  function addVocabulary(array $vocabulary = array()) {
554
    $vocabulary += array(
555
      'name' => drupal_strtolower($this->randomName(5)),
556
      'nodes' => array('article' => 'article'),
557
    );
558
    $vocabulary = (object) $vocabulary;
559
    taxonomy_vocabulary_save($vocabulary);
560
    return $vocabulary;
561
  }
562

    
563
  function addTerm(stdClass $vocabulary, array $term = array()) {
564
    $term += array(
565
      'name' => drupal_strtolower($this->randomName(5)),
566
      'vid' => $vocabulary->vid,
567
    );
568
    $term = (object) $term;
569
    taxonomy_term_save($term);
570
    return $term;
571
  }
572
}
573

    
574
class TokenUserTestCase extends TokenTestHelper {
575
  protected $account = NULL;
576

    
577
  public static function getInfo() {
578
    return array(
579
      'name' => 'User token tests',
580
      'description' => 'Test the user tokens.',
581
      'group' => 'Token',
582
    );
583
  }
584

    
585
  public function setUp($modules = array()) {
586
    parent::setUp($modules);
587

    
588
    // Enable user pictures.
589
    variable_set('user_pictures', 1);
590
    variable_set('user_picture_file_size', '');
591

    
592
    // Set up the pictures directory.
593
    $picture_path = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
594
    if (!file_prepare_directory($picture_path, FILE_CREATE_DIRECTORY)) {
595
      $this->fail('Could not create directory ' . $picture_path . '.');
596
    }
597

    
598
    $this->account = $this->drupalCreateUser(array('administer users'));
599
    $this->drupalLogin($this->account);
600
  }
601

    
602
  function testUserTokens() {
603
    // Add a user picture to the account.
604
    $image = current($this->drupalGetTestFiles('image'));
605
    $edit = array('files[picture_upload]' => drupal_realpath($image->uri));
606
    $this->drupalPost('user/' . $this->account->uid . '/edit', $edit, t('Save'));
607

    
608
    // Load actual user data from database.
609
    $this->account = user_load($this->account->uid, TRUE);
610
    $this->assertTrue(!empty($this->account->picture->fid), 'User picture uploaded.');
611

    
612
    $user_tokens = array(
613
      'picture' => theme('user_picture', array('account' => $this->account)),
614
      'picture:fid' => $this->account->picture->fid,
615
      'picture:size-raw' => 125,
616
      'ip-address' => NULL,
617
      'roles' => implode(', ', $this->account->roles),
618
      'roles:keys' => implode(', ', array_keys($this->account->roles)),
619
    );
620
    $this->assertTokens('user', array('user' => $this->account), $user_tokens);
621

    
622
    $edit = array('user_pictures' => FALSE);
623
    $this->drupalPost('admin/config/people/accounts', $edit, 'Save configuration');
624
    $this->assertText('The configuration options have been saved.');
625

    
626
    // Remove the simpletest-created user role.
627
    user_role_delete(end($this->account->roles));
628
    $this->account = user_load($this->account->uid, TRUE);
629

    
630
    $user_tokens = array(
631
      'picture' => NULL,
632
      'picture:fid' => NULL,
633
      'ip-address' => NULL,
634
      'roles' => 'authenticated user',
635
      'roles:keys' => (string) DRUPAL_AUTHENTICATED_RID,
636
    );
637
    $this->assertTokens('user', array('user' => $this->account), $user_tokens);
638

    
639
    // The ip address token should work for the current user token type.
640
    $tokens = array(
641
      'ip-address' => ip_address(),
642
    );
643
    $this->assertTokens('current-user', array(), $tokens);
644

    
645
    $anonymous = drupal_anonymous_user();
646
    // Mess with the role array to ensure we still get consistent output.
647
    $anonymous->roles[DRUPAL_ANONYMOUS_RID] = DRUPAL_ANONYMOUS_RID;
648
    $tokens = array(
649
      'roles' => 'anonymous user',
650
      'roles:keys' => (string) DRUPAL_ANONYMOUS_RID,
651
    );
652
    $this->assertTokens('user', array('user' => $anonymous), $tokens);
653
  }
654
}
655

    
656
class TokenEntityTestCase extends TokenTestHelper {
657
  public static function getInfo() {
658
    return array(
659
      'name' => 'Entity token tests',
660
      'description' => 'Test the entity tokens.',
661
      'group' => 'Token',
662
    );
663
  }
664

    
665
  public function setUp($modules = array()) {
666
    $modules[] = 'taxonomy';
667
    parent::setUp($modules);
668

    
669
    // Create the default tags vocabulary.
670
    $vocabulary = (object) array(
671
      'name' => 'Tags',
672
      'machine_name' => 'tags',
673
    );
674
    taxonomy_vocabulary_save($vocabulary);
675
    $this->vocab = $vocabulary;
676
  }
677

    
678
  function testEntityMapping() {
679
    $this->assertIdentical(token_get_entity_mapping('token', 'node'), 'node');
680
    $this->assertIdentical(token_get_entity_mapping('token', 'term'), 'taxonomy_term');
681
    $this->assertIdentical(token_get_entity_mapping('token', 'vocabulary'), 'taxonomy_vocabulary');
682
    $this->assertIdentical(token_get_entity_mapping('token', 'invalid'), FALSE);
683
    $this->assertIdentical(token_get_entity_mapping('token', 'invalid', TRUE), 'invalid');
684
    $this->assertIdentical(token_get_entity_mapping('entity', 'node'), 'node');
685
    $this->assertIdentical(token_get_entity_mapping('entity', 'taxonomy_term'), 'term');
686
    $this->assertIdentical(token_get_entity_mapping('entity', 'taxonomy_vocabulary'), 'vocabulary');
687
    $this->assertIdentical(token_get_entity_mapping('entity', 'invalid'), FALSE);
688
    $this->assertIdentical(token_get_entity_mapping('entity', 'invalid', TRUE), 'invalid');
689

    
690
    // Test that when we send the mis-matched entity type into token_replace()
691
    // that we still get the tokens replaced.
692
    $vocabulary = taxonomy_vocabulary_machine_name_load('tags');
693
    $term = $this->addTerm($vocabulary);
694
    $this->assertIdentical(token_replace('[vocabulary:name]', array('taxonomy_vocabulary' => $vocabulary)), $vocabulary->name);
695
    $this->assertIdentical(token_replace('[term:name][term:vocabulary:name]', array('taxonomy_term' => $term)), $term->name . $vocabulary->name);
696
  }
697

    
698
  function addTerm(stdClass $vocabulary, array $term = array()) {
699
    $term += array(
700
      'name' => drupal_strtolower($this->randomName(5)),
701
      'vid' => $vocabulary->vid,
702
    );
703
    $term = (object) $term;
704
    taxonomy_term_save($term);
705
    return $term;
706
  }
707

    
708
  /**
709
   * Test the [entity:original:*] tokens.
710
   */
711
  function testEntityOriginal() {
712
    $node = $this->drupalCreateNode(array('title' => 'Original title'));
713

    
714
    $tokens = array(
715
      'nid' => $node->nid,
716
      'title' => 'Original title',
717
      'original' => NULL,
718
      'original:nid' => NULL,
719
    );
720
    $this->assertTokens('node', array('node' => $node), $tokens);
721

    
722
    // Emulate the original entity property that would be available from
723
    // node_save() and change the title for the node.
724
    $node->original = entity_load_unchanged('node', $node->nid);
725
    $node->title = 'New title';
726

    
727
    $tokens = array(
728
      'nid' => $node->nid,
729
      'title' => 'New title',
730
      'original' => 'Original title',
731
      'original:nid' => $node->nid,
732
    );
733
    $this->assertTokens('node', array('node' => $node), $tokens);
734
  }
735
}
736

    
737
/**
738
 * Test the profile tokens.
739
 */
740
class TokenProfileTestCase extends TokenTestHelper {
741
  private $account;
742

    
743
  public static function getInfo() {
744
    return array(
745
      'name' => 'Profile token tests',
746
      'description' => 'Test the profile tokens.',
747
      'group' => 'Token',
748
    );
749
  }
750

    
751
  public function setUp($modules = array()) {
752
    $modules[] = 'profile';
753
    parent::setUp($modules);
754
    $this->account = $this->drupalCreateUser(array('administer users'));
755
    $this->drupalLogin($this->account);
756
  }
757

    
758
  /**
759
   * Test the profile tokens.
760
   */
761
  function testProfileTokens() {
762
    $field_types = _profile_field_types();
763
    foreach (array_keys($field_types) as $field_type) {
764
      $field = array();
765
      switch ($field_type) {
766
        case 'checkbox':
767
          $field['title'] = 'This is a checkbox';
768
          break;
769
        case 'selection':
770
          $field['options'] = implode("\n", array('Red', 'Blue', 'Green'));
771
          break;
772
      }
773
      $this->addProfileField($field_type, $field);
774
    }
775

    
776
    // Submit the profile fields for the user.
777
    $edit = array(
778
      'profile_textfield' => 'This is a text field',
779
      'profile_textarea' => "First paragraph.\n\nSecond paragraph.",
780
      'profile_checkbox' => TRUE,
781
      'profile_selection' => 'Red',
782
      'profile_list' => ' Drupal ,  Joomla ',
783
      'profile_url' => 'http://www.example.com/',
784
      'profile_date[month]' => 5,
785
      'profile_date[day]' => 20,
786
      'profile_date[year]' => 1984,
787
    );
788
    $this->drupalPost("user/{$this->account->uid}/edit/SimpleTest", $edit, 'Save');
789
    $account = user_load($this->account->uid, TRUE);
790

    
791
    // Test the profile token values.
792
    $tokens = array(
793
      'profile-textfield' => 'This is a text field',
794
      'profile-textarea' => "<p>First paragraph.</p>\n<p>Second paragraph.</p>\n",
795
      'profile-checkbox' => 'This is a checkbox',
796
      'profile-selection' => 'Red',
797
      'profile-list' => 'Drupal, Joomla',
798
      'profile-url' => 'http://www.example.com/',
799
      'profile-date' => format_date(453859200, 'medium', '', NULL),
800
      'profile-date:raw' => '453859200',
801
      'profile-date:custom:Y' => '1984',
802
    );
803
    $this->assertTokens('user', array('user' => $account), $tokens);
804

    
805
    // 'Un-select' the checkbox and select profile fields.
806
    $edit = array(
807
      'profile_checkbox' => FALSE,
808
      'profile_selection' => '0',
809
    );
810
    $this->drupalPost("user/{$this->account->uid}/edit/SimpleTest", $edit, 'Save');
811
    $account = user_load($this->account->uid, TRUE);
812

    
813
    // The checkbox and select profile tokens should no longer return a value.
814
    $tokens = array(
815
      'profile-checkbox' => NULL,
816
      'profile-selection' => NULL,
817
    );
818
    $this->assertTokens('user', array('user' => $account), $tokens);
819
  }
820

    
821
  /**
822
   * Add a profile field.
823
   *
824
   * @param $type
825
   *   The profile field type.
826
   * @param $field
827
   *   (optional) An array of the profile field properties.
828
   *
829
   * @return
830
   *   The saved profile field record object.
831
   *
832
   * @see drupal_form_submit()
833
   */
834
  function addProfileField($type, array $field = array()) {
835
    $field += array(
836
      'type' => $type,
837
      'category' => 'SimpleTest',
838
      'title' => $this->randomName(8),
839
      'name' => 'profile_' . $type,
840
      'explanation' => $this->randomName(50),
841
      'autocomplete' => 0,
842
      'required' => 0,
843
      'register' => 0,
844
    );
845
    drupal_write_record('profile_field', $field);
846

    
847
    // Verify the profile field was created successfully.
848
    $saved_field = db_query("SELECT * FROM {profile_field} WHERE type = :type AND name = :name", array(':type' => $type, ':name' => $field['name']))->fetchObject();
849
    if (empty($saved_field)) {
850
      $this->fail(t('Failed to create profile field @name.', array('@name' => $saved_field->name)));
851
    }
852

    
853
    return $saved_field;
854
  }
855
}
856

    
857
/**
858
 * Test the current page tokens.
859
 */
860
class TokenCurrentPageTestCase extends TokenTestHelper {
861
  public static function getInfo() {
862
    return array(
863
      'name' => 'Current page token tests',
864
      'description' => 'Test the [current-page:*] tokens.',
865
      'group' => 'Token',
866
    );
867
  }
868

    
869
  function testCurrentPageTokens() {
870
    $tokens = array(
871
      '[current-page:title]' => t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))),
872
      '[current-page:url]' => url('node', array('absolute' => TRUE)),
873
      '[current-page:url:absolute]' => url('node', array('absolute' => TRUE)),
874
      '[current-page:url:relative]' => url('node', array('absolute' => FALSE)),
875
      '[current-page:url:path]' => 'node',
876
      '[current-page:url:args:value:0]' => 'node',
877
      '[current-page:url:args:value:1]' => NULL,
878
      '[current-page:url:unaliased]' => url('node', array('absolute' => TRUE, 'alias' => TRUE)),
879
      '[current-page:page-number]' => 1,
880
      '[current-page:query:foo]' => NULL,
881
      '[current-page:query:bar]' => NULL,
882
      '[current-page:query:q]' => 'node',
883
      // Deprecated tokens
884
      '[current-page:arg:0]' => 'node',
885
      '[current-page:arg:1]' => NULL,
886
    );
887
    $this->assertPageTokens('', $tokens);
888

    
889
    $node = $this->drupalCreateNode(array('title' => 'Node title', 'path' => array('alias' => 'node-alias')));
890
    $tokens = array(
891
      '[current-page:title]' => 'Node title',
892
      '[current-page:url]' => url("node/{$node->nid}", array('absolute' => TRUE)),
893
      '[current-page:url:absolute]' => url("node/{$node->nid}", array('absolute' => TRUE)),
894
      '[current-page:url:relative]' => url("node/{$node->nid}", array('absolute' => FALSE)),
895
      '[current-page:url:alias]' => 'node-alias',
896
      '[current-page:url:args:value:0]' => 'node-alias',
897
      '[current-page:url:args:value:1]' => NULL,
898
      '[current-page:url:unaliased]' => url("node/{$node->nid}", array('absolute' => TRUE, 'alias' => TRUE)),
899
      '[current-page:url:unaliased:args:value:0]' => 'node',
900
      '[current-page:url:unaliased:args:value:1]' => $node->nid,
901
      '[current-page:url:unaliased:args:value:2]' => NULL,
902
      '[current-page:page-number]' => 1,
903
      '[current-page:query:foo]' => 'bar',
904
      '[current-page:query:bar]' => NULL,
905
      '[current-page:query:q]' => 'node/1',
906
      // Deprecated tokens
907
      '[current-page:arg:0]' => 'node',
908
      '[current-page:arg:1]' => 1,
909
      '[current-page:arg:2]' => NULL,
910
    );
911
    $this->assertPageTokens("node/{$node->nid}", $tokens, array(), array('url_options' => array('query' => array('foo' => 'bar'))));
912
  }
913
}
914

    
915
class TokenArrayTestCase extends TokenTestHelper {
916
  public static function getInfo() {
917
    return array(
918
      'name' => 'Array token tests',
919
      'description' => 'Test the array tokens.',
920
      'group' => 'Token',
921
    );
922
  }
923

    
924
  function testArrayTokens() {
925
    // Test a simple array.
926
    $array = array(0 => 'a', 1 => 'b', 2 => 'c', 4 => 'd');
927
    $tokens = array(
928
      'first' => 'a',
929
      'last' => 'd',
930
      'value:0' => 'a',
931
      'value:2' => 'c',
932
      'count' => 4,
933
      'keys' => '0, 1, 2, 4',
934
      'keys:value:3' => '4',
935
      'keys:join' => '0124',
936
      'reversed' => 'd, c, b, a',
937
      'reversed:keys' => '4, 2, 1, 0',
938
      'join:/' => 'a/b/c/d',
939
      'join' => 'abcd',
940
      'join:, ' => 'a, b, c, d',
941
      'join: ' => 'a b c d',
942
    );
943
    $this->assertTokens('array', array('array' => $array), $tokens);
944

    
945
    // Test a mixed simple and render array.
946
    // 2 => c, 0 => a, 4 => d, 1 => b
947
    $array = array(
948
      '#property' => 'value',
949
      0 => 'a',
950
      1 => array('#markup' => 'b', '#weight' => 0.01),
951
      2 => array('#markup' => 'c', '#weight' => -10),
952
      4 => array('#markup' => 'd', '#weight' => 0),
953
    );
954
    $tokens = array(
955
      'first' => 'c',
956
      'last' => 'b',
957
      'value:0' => 'a',
958
      'value:2' => 'c',
959
      'count' => 4,
960
      'keys' => '2, 0, 4, 1',
961
      'keys:value:3' => '1',
962
      'keys:join' => '2041',
963
      'reversed' => 'b, d, a, c',
964
      'reversed:keys' => '1, 4, 0, 2',
965
      'join:/' => 'c/a/d/b',
966
      'join' => 'cadb',
967
      'join:, ' => 'c, a, d, b',
968
      'join: ' => 'c a d b',
969
    );
970
    $this->assertTokens('array', array('array' => $array), $tokens);
971
  }
972
}
973

    
974
class TokenRandomTestCase extends TokenTestHelper {
975
  public static function getInfo() {
976
    return array(
977
      'name' => 'Random token tests',
978
      'description' => 'Test the random tokens.',
979
      'group' => 'Token',
980
    );
981
  }
982

    
983
  function testRandomTokens() {
984
    $tokens = array(
985
      'number' => '[0-9]{1,}',
986
      'hash:md5' => '[0-9a-f]{32}',
987
      'hash:sha1' => '[0-9a-f]{40}',
988
      'hash:sha256' => '[0-9a-f]{64}',
989
      'hash:invalid-algo' => NULL,
990
    );
991

    
992
    $first_set = $this->assertTokens('random', array(), $tokens, array('regex' => TRUE));
993
    $second_set = $this->assertTokens('random', array(), $tokens, array('regex' => TRUE));
994
    foreach ($first_set as $token => $value) {
995
      $this->assertNotIdentical($first_set[$token], $second_set[$token]);
996
    }
997
  }
998
}
999

    
1000
/**
1001
 * @todo Remove when http://drupal.org/node/1173706 is fixed.
1002
 */
1003
class TokenDateTestCase extends TokenTestHelper {
1004
  public static function getInfo() {
1005
    return array(
1006
      'name' => 'Date token tests',
1007
      'description' => 'Test the date tokens.',
1008
      'group' => 'Token',
1009
    );
1010
  }
1011

    
1012
  function testDateTokens() {
1013
    $tokens = array(
1014
      'token_test' => '1984',
1015
      'invalid_format' => NULL,
1016
    );
1017

    
1018
    $this->assertTokens('date', array('date' => 453859200), $tokens);
1019
  }
1020
}
1021

    
1022
class TokenFileTestCase extends TokenTestHelper {
1023
  public static function getInfo() {
1024
    return array(
1025
      'name' => 'File token tests',
1026
      'description' => 'Test the file tokens.',
1027
      'group' => 'Token',
1028
    );
1029
  }
1030

    
1031
  function testFileTokens() {
1032
    // Create a test file object.
1033
    $file = new stdClass();
1034
    $file->fid = 1;
1035
    $file->filename = 'test.png';
1036
    $file->filesize = 100;
1037
    $file->uri = 'public://images/test.png';
1038
    $file->filemime = 'image/png';
1039

    
1040
    $tokens = array(
1041
      'basename' => 'test.png',
1042
      'extension' => 'png',
1043
      'size-raw' => 100,
1044
    );
1045
    $this->assertTokens('file', array('file' => $file), $tokens);
1046

    
1047
    // Test a file with no extension and a fake name.
1048
    $file->filename = 'Test PNG image';
1049
    $file->uri = 'public://images/test';
1050

    
1051
    $tokens = array(
1052
      'basename' => 'test',
1053
      'extension' => '',
1054
      'size-raw' => 100,
1055
    );
1056
    $this->assertTokens('file', array('file' => $file), $tokens);
1057
  }
1058
}
1059

    
1060
class TokenBlockTestCase extends TokenTestHelper {
1061
  public static function getInfo() {
1062
    return array(
1063
      'name' => 'Block token tests',
1064
      'description' => 'Test the block title token replacement.',
1065
      'group' => 'Token',
1066
    );
1067
  }
1068

    
1069
  public function setUp($modules = array()) {
1070
    $modules[] = 'block';
1071
    parent::setUp($modules);
1072

    
1073
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer blocks'));
1074
    $this->drupalLogin($this->admin_user);
1075
  }
1076

    
1077
  public function testBlockTitleTokens() {
1078
    $edit['title'] = '[user:name]';
1079
    $edit['info'] = 'Test token title block';
1080
    $edit['body[value]'] = 'This is the test token title block.';
1081
    $this->drupalPost('admin/structure/block/add', $edit, 'Save block');
1082
    // Ensure token validation is working on the block.
1083
    $this->assertText('The Block title is using the following invalid tokens: [user:name].');
1084

    
1085
    // Create the block for real now with a valid title.
1086
    $edit['title'] = '[current-page:title] block title';
1087
    $edit['regions[bartik]'] = 'sidebar_first';
1088
    $this->drupalPost(NULL, $edit, 'Save block');
1089

    
1090
    $this->drupalGet('node');
1091
    $this->assertText('Welcome to ' . variable_get('site_name', 'Drupal') . ' block title');
1092

    
1093
    // Ensure that tokens are not double-escaped when output as a block title.
1094
    $node = $this->drupalCreateNode(array('title' => "Site's first node"));
1095
    $this->drupalGet('node/' . $node->nid);
1096
    // The apostraphe should only be escaped once via check_plain().
1097
    $this->assertRaw("Site&#039;s first node block title");
1098
  }
1099
}