Projet

Général

Profil

Paste
Télécharger (76,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / taxonomy / taxonomy.test @ f7a2490e

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for taxonomy.module.
6
 */
7

    
8
/**
9
 * Provides common helper methods for Taxonomy module tests.
10
 */
11
class TaxonomyWebTestCase extends DrupalWebTestCase {
12

    
13
  /**
14
   * Returns a new vocabulary with random properties.
15
   */
16
  function createVocabulary() {
17
    // Create a vocabulary.
18
    $vocabulary = new stdClass();
19
    $vocabulary->name = $this->randomName();
20
    $vocabulary->description = $this->randomName();
21
    $vocabulary->machine_name = drupal_strtolower($this->randomName());
22
    $vocabulary->help = '';
23
    $vocabulary->nodes = array('article' => 'article');
24
    $vocabulary->weight = mt_rand(0, 10);
25
    taxonomy_vocabulary_save($vocabulary);
26
    return $vocabulary;
27
  }
28

    
29
  /**
30
   * Returns a new term with random properties in vocabulary $vid.
31
   */
32
  function createTerm($vocabulary) {
33
    $term = new stdClass();
34
    $term->name = $this->randomName();
35
    $term->description = $this->randomName();
36
    // Use the first available text format.
37
    $term->format = db_query_range('SELECT format FROM {filter_format}', 0, 1)->fetchField();
38
    $term->vid = $vocabulary->vid;
39
    taxonomy_term_save($term);
40
    return $term;
41
  }
42

    
43
}
44

    
45
/**
46
 * Tests the taxonomy vocabulary interface.
47
 */
48
class TaxonomyVocabularyFunctionalTest extends TaxonomyWebTestCase {
49

    
50
  public static function getInfo() {
51
    return array(
52
      'name' => 'Taxonomy vocabulary interface',
53
      'description' => 'Test the taxonomy vocabulary interface.',
54
      'group' => 'Taxonomy',
55
    );
56
  }
57

    
58
  function setUp() {
59
    parent::setUp();
60
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
61
    $this->drupalLogin($this->admin_user);
62
    $this->vocabulary = $this->createVocabulary();
63
  }
64

    
65
  /**
66
   * Create, edit and delete a vocabulary via the user interface.
67
   */
68
  function testVocabularyInterface() {
69
    // Visit the main taxonomy administration page.
70
    $this->drupalGet('admin/structure/taxonomy');
71

    
72
    // Create a new vocabulary.
73
    $this->clickLink(t('Add vocabulary'));
74
    $edit = array();
75
    $machine_name = drupal_strtolower($this->randomName());
76
    $edit['name'] = $this->randomName();
77
    $edit['description'] = $this->randomName();
78
    $edit['machine_name'] = $machine_name;
79
    $this->drupalPost(NULL, $edit, t('Save'));
80
    $this->assertRaw(t('Created new vocabulary %name.', array('%name' => $edit['name'])), 'Vocabulary created successfully.');
81

    
82
    // Edit the vocabulary.
83
    $this->drupalGet('admin/structure/taxonomy');
84
    $this->assertText($edit['name'], 'Vocabulary found in the vocabulary overview listing.');
85
    $this->clickLink(t('edit vocabulary'));
86
    $edit = array();
87
    $edit['name'] = $this->randomName();
88
    $this->drupalPost(NULL, $edit, t('Save'));
89
    $this->drupalGet('admin/structure/taxonomy');
90
    $this->assertText($edit['name'], 'Vocabulary found in the vocabulary overview listing.');
91

    
92
    // Try to submit a vocabulary with a duplicate machine name.
93
    $edit['machine_name'] = $machine_name;
94
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
95
    $this->assertText(t('The machine-readable name is already in use. It must be unique.'));
96

    
97
    // Try to submit an invalid machine name.
98
    $edit['machine_name'] = '!&^%';
99
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
100
    $this->assertText(t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
101

    
102
    // Ensure that vocabulary titles are escaped properly.
103
    $edit = array();
104
    $edit['name'] = 'Don\'t Panic';
105
    $edit['description'] = $this->randomName();
106
    $edit['machine_name'] = 'don_t_panic';
107
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
108

    
109
    $site_name = variable_get('site_name', 'Drupal');
110
    $this->drupalGet('admin/structure/taxonomy/don_t_panic');
111
    $this->assertTitle(t('Don\'t Panic | @site-name', array('@site-name' => $site_name)));
112
    $this->assertNoTitle(t('Don&#039;t Panic | @site-name', array('@site-name' => $site_name)));
113
  }
114

    
115
  /**
116
   * Changing weights on the vocabulary overview with two or more vocabularies.
117
   */
118
  function testTaxonomyAdminChangingWeights() {
119
    // Create some vocabularies.
120
    for ($i = 0; $i < 10; $i++) {
121
      $this->createVocabulary();
122
    }
123
    // Get all vocabularies and change their weights.
124
    $vocabularies = taxonomy_get_vocabularies();
125
    $edit = array();
126
    foreach ($vocabularies as $key => $vocabulary) {
127
      $vocabulary->weight = -$vocabulary->weight;
128
      $vocabularies[$key]->weight = $vocabulary->weight;
129
      $edit[$key . '[weight]'] = $vocabulary->weight;
130
    }
131
    // Saving the new weights via the interface.
132
    $this->drupalPost('admin/structure/taxonomy', $edit, t('Save'));
133

    
134
    // Load the vocabularies from the database.
135
    $new_vocabularies = taxonomy_get_vocabularies();
136

    
137
    // Check that the weights are saved in the database correctly.
138
    foreach ($vocabularies as $key => $vocabulary) {
139
      $this->assertEqual($new_vocabularies[$key]->weight, $vocabularies[$key]->weight, 'The vocabulary weight was changed.');
140
    }
141
  }
142

    
143
  /**
144
   * Test the vocabulary overview with no vocabularies.
145
   */
146
  function testTaxonomyAdminNoVocabularies() {
147
    // Delete all vocabularies.
148
    $vocabularies = taxonomy_get_vocabularies();
149
    foreach ($vocabularies as $key => $vocabulary) {
150
      taxonomy_vocabulary_delete($key);
151
    }
152
    // Confirm that no vocabularies are found in the database.
153
    $this->assertFalse(taxonomy_get_vocabularies(), 'No vocabularies found in the database.');
154
    $this->drupalGet('admin/structure/taxonomy');
155
    // Check the default message for no vocabularies.
156
    $this->assertText(t('No vocabularies available.'), 'No vocabularies were found.');
157
  }
158

    
159
  /**
160
   * Deleting a vocabulary.
161
   */
162
  function testTaxonomyAdminDeletingVocabulary() {
163
    // Create a vocabulary.
164
    $edit = array(
165
      'name' => $this->randomName(),
166
      'machine_name' => drupal_strtolower($this->randomName()),
167
    );
168
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
169
    $this->assertText(t('Created new vocabulary'), 'New vocabulary was created.');
170

    
171
    // Check the created vocabulary.
172
    $vocabularies = taxonomy_get_vocabularies();
173
    $vocabularies_keys = array_keys($vocabularies);
174
    $vid = $vocabularies[end($vocabularies_keys)]->vid;
175
    entity_get_controller('taxonomy_vocabulary')->resetCache();
176
    $vocabulary = taxonomy_vocabulary_load($vid);
177
    $this->assertTrue($vocabulary, 'Vocabulary found in database.');
178

    
179
    // Delete the vocabulary.
180
    $edit = array();
181
    $this->drupalPost('admin/structure/taxonomy/' . $vocabulary->machine_name . '/edit', $edit, t('Delete'));
182
    $this->assertRaw(t('Are you sure you want to delete the vocabulary %name?', array('%name' => $vocabulary->name)), '[confirm deletion] Asks for confirmation.');
183
    $this->assertText(t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'), '[confirm deletion] Inform that all terms will be deleted.');
184

    
185
    // Confirm deletion.
186
    $this->drupalPost(NULL, NULL, t('Delete'));
187
    $this->assertRaw(t('Deleted vocabulary %name.', array('%name' => $vocabulary->name)), 'Vocabulary deleted.');
188
    entity_get_controller('taxonomy_vocabulary')->resetCache();
189
    $this->assertFalse(taxonomy_vocabulary_load($vid), 'Vocabulary is not found in the database.');
190
  }
191

    
192
}
193

    
194
/**
195
 * Tests for taxonomy vocabulary functions.
196
 */
197
class TaxonomyVocabularyTestCase extends TaxonomyWebTestCase {
198

    
199
  public static function getInfo() {
200
    return array(
201
      'name' => 'Taxonomy vocabularies',
202
      'description' => 'Test loading, saving and deleting vocabularies.',
203
      'group' => 'Taxonomy',
204
    );
205
  }
206

    
207
  function setUp() {
208
    parent::setUp('taxonomy', 'field_test');
209
    $admin_user = $this->drupalCreateUser(array('create article content', 'administer taxonomy'));
210
    $this->drupalLogin($admin_user);
211
    $this->vocabulary = $this->createVocabulary();
212
  }
213

    
214
  /**
215
   * Ensure that when an invalid vocabulary vid is loaded, it is possible
216
   * to load the same vid successfully if it subsequently becomes valid.
217
   */
218
  function testTaxonomyVocabularyLoadReturnFalse() {
219
    // Load a vocabulary that doesn't exist.
220
    $vocabularies = taxonomy_get_vocabularies();
221
    $vid = count($vocabularies) + 1;
222
    $vocabulary = taxonomy_vocabulary_load($vid);
223
    // This should not return an object because no such vocabulary exists.
224
    $this->assertTrue(empty($vocabulary), 'No object loaded.');
225

    
226
    // Create a new vocabulary.
227
    $this->createVocabulary();
228
    // Load the vocabulary with the same $vid from earlier.
229
    // This should return a vocabulary object since it now matches a real vid.
230
    $vocabulary = taxonomy_vocabulary_load($vid);
231
    $this->assertTrue(!empty($vocabulary) && is_object($vocabulary), 'Vocabulary is an object.');
232
    $this->assertEqual($vocabulary->vid, $vid, 'Valid vocabulary vid is the same as our previously invalid one.');
233
  }
234

    
235
  /**
236
   * Test deleting a taxonomy that contains terms.
237
   */
238
  function testTaxonomyVocabularyDeleteWithTerms() {
239
    // Delete any existing vocabularies.
240
    foreach (taxonomy_get_vocabularies() as $vocabulary) {
241
      taxonomy_vocabulary_delete($vocabulary->vid);
242
    }
243

    
244
    // Assert that there are no terms left.
245
    $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());
246

    
247
    // Create a new vocabulary and add a few terms to it.
248
    $vocabulary = $this->createVocabulary();
249
    $terms = array();
250
    for ($i = 0; $i < 5; $i++) {
251
      $terms[$i] = $this->createTerm($vocabulary);
252
    }
253

    
254
    // Set up hierarchy. term 2 is a child of 1 and 4 a child of 1 and 2.
255
    $terms[2]->parent = array($terms[1]->tid);
256
    taxonomy_term_save($terms[2]);
257
    $terms[4]->parent = array($terms[1]->tid, $terms[2]->tid);
258
    taxonomy_term_save($terms[4]);
259

    
260
    // Assert that there are now 5 terms.
261
    $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());
262

    
263
    taxonomy_vocabulary_delete($vocabulary->vid);
264

    
265
    // Assert that there are no terms left.
266
    $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());
267
  }
268

    
269
  /**
270
   * Ensure that the vocabulary static reset works correctly.
271
   */
272
  function testTaxonomyVocabularyLoadStaticReset() {
273
    $original_vocabulary = taxonomy_vocabulary_load($this->vocabulary->vid);
274
    $this->assertTrue(is_object($original_vocabulary), 'Vocabulary loaded successfully.');
275
    $this->assertEqual($this->vocabulary->name, $original_vocabulary->name, 'Vocabulary loaded successfully.');
276

    
277
    // Change the name and description.
278
    $vocabulary = $original_vocabulary;
279
    $vocabulary->name = $this->randomName();
280
    $vocabulary->description = $this->randomName();
281
    taxonomy_vocabulary_save($vocabulary);
282

    
283
    // Load the vocabulary.
284
    $new_vocabulary = taxonomy_vocabulary_load($original_vocabulary->vid);
285
    $this->assertEqual($new_vocabulary->name, $vocabulary->name);
286
    $this->assertEqual($new_vocabulary->name, $vocabulary->name);
287

    
288
    // Delete the vocabulary.
289
    taxonomy_vocabulary_delete($this->vocabulary->vid);
290
    $vocabularies = taxonomy_get_vocabularies();
291
    $this->assertTrue(!isset($vocabularies[$this->vocabulary->vid]), 'The vocabulary was deleted.');
292
  }
293

    
294
  /**
295
   * Tests for loading multiple vocabularies.
296
   */
297
  function testTaxonomyVocabularyLoadMultiple() {
298

    
299
    // Delete any existing vocabularies.
300
    foreach (taxonomy_get_vocabularies() as $vocabulary) {
301
      taxonomy_vocabulary_delete($vocabulary->vid);
302
    }
303

    
304
    // Create some vocabularies and assign weights.
305
    $vocabulary1 = $this->createVocabulary();
306
    $vocabulary1->weight = 0;
307
    taxonomy_vocabulary_save($vocabulary1);
308
    $vocabulary2 = $this->createVocabulary();
309
    $vocabulary2->weight = 1;
310
    taxonomy_vocabulary_save($vocabulary2);
311
    $vocabulary3 = $this->createVocabulary();
312
    $vocabulary3->weight = 2;
313
    taxonomy_vocabulary_save($vocabulary3);
314

    
315
    // Fetch the names for all vocabularies, confirm that they are keyed by
316
    // machine name.
317
    $names = taxonomy_vocabulary_get_names();
318
    $this->assertEqual($names[$vocabulary1->machine_name]->name, $vocabulary1->name, 'Vocabulary 1 name found.');
319

    
320
    // Fetch all of the vocabularies using taxonomy_get_vocabularies().
321
    // Confirm that the vocabularies are ordered by weight.
322
    $vocabularies = taxonomy_get_vocabularies();
323
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary1->vid, 'Vocabulary was found in the vocabularies array.');
324
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary2->vid, 'Vocabulary was found in the vocabularies array.');
325
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary3->vid, 'Vocabulary was found in the vocabularies array.');
326

    
327
    // Fetch the vocabularies with taxonomy_vocabulary_load_multiple(), specifying IDs.
328
    // Ensure they are returned in the same order as the original array.
329
    $vocabularies = taxonomy_vocabulary_load_multiple(array($vocabulary3->vid, $vocabulary2->vid, $vocabulary1->vid));
330
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary3->vid, 'Vocabulary loaded successfully by ID.');
331
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary2->vid, 'Vocabulary loaded successfully by ID.');
332
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by ID.');
333

    
334
    // Fetch vocabulary 1 by name.
335
    $vocabulary = current(taxonomy_vocabulary_load_multiple(array(), array('name' => $vocabulary1->name)));
336
    $this->assertEqual($vocabulary->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by name.');
337

    
338
    // Fetch vocabulary 1 by name and ID.
339
    $this->assertEqual(current(taxonomy_vocabulary_load_multiple(array($vocabulary1->vid), array('name' => $vocabulary1->name)))->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by name and ID.');
340
  }
341

    
342
  /**
343
   * Tests that machine name changes are properly reflected.
344
   */
345
  function testTaxonomyVocabularyChangeMachineName() {
346
    // Add a field instance to the vocabulary.
347
    $field = array(
348
      'field_name' => 'field_test',
349
      'type' => 'test_field',
350
    );
351
    field_create_field($field);
352
    $instance = array(
353
      'field_name' => 'field_test',
354
      'entity_type' => 'taxonomy_term',
355
      'bundle' => $this->vocabulary->machine_name,
356
    );
357
    field_create_instance($instance);
358

    
359
    // Change the machine name.
360
    $new_name = drupal_strtolower($this->randomName());
361
    $this->vocabulary->machine_name = $new_name;
362
    taxonomy_vocabulary_save($this->vocabulary);
363

    
364
    // Check that the field instance is still attached to the vocabulary.
365
    $this->assertTrue(field_info_instance('taxonomy_term', 'field_test', $new_name), 'The bundle name was updated correctly.');
366
  }
367

    
368
  /**
369
   * Test uninstall and reinstall of the taxonomy module.
370
   */
371
  function testUninstallReinstall() {
372
    // Fields and field instances attached to taxonomy term bundles should be
373
    // removed when the module is uninstalled.
374
    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
375
    $this->field = array('field_name' => $this->field_name, 'type' => 'text', 'cardinality' => 4);
376
    $this->field = field_create_field($this->field);
377
    $this->instance = array(
378
      'field_name' => $this->field_name,
379
      'entity_type' => 'taxonomy_term',
380
      'bundle' => $this->vocabulary->machine_name,
381
      'label' => $this->randomName() . '_label',
382
    );
383
    field_create_instance($this->instance);
384

    
385
    module_disable(array('taxonomy'));
386
    require_once DRUPAL_ROOT . '/includes/install.inc';
387
    drupal_uninstall_modules(array('taxonomy'));
388
    module_enable(array('taxonomy'));
389

    
390
    // Now create a vocabulary with the same name. All field instances
391
    // connected to this vocabulary name should have been removed when the
392
    // module was uninstalled. Creating a new field with the same name and
393
    // an instance of this field on the same bundle name should be successful.
394
    unset($this->vocabulary->vid);
395
    taxonomy_vocabulary_save($this->vocabulary);
396
    unset($this->field['id']);
397
    field_create_field($this->field);
398
    field_create_instance($this->instance);
399
  }
400

    
401
}
402

    
403
/**
404
 * Unit tests for taxonomy term functions.
405
 */
406
class TaxonomyTermFunctionTestCase extends TaxonomyWebTestCase {
407

    
408
  public static function getInfo() {
409
    return array(
410
      'name' => 'Taxonomy term unit tests',
411
      'description' => 'Unit tests for taxonomy term functions.',
412
      'group' => 'Taxonomy',
413
    );
414
  }
415

    
416
  function testTermDelete() {
417
    $vocabulary = $this->createVocabulary();
418
    $valid_term = $this->createTerm($vocabulary);
419
    // Delete a valid term.
420
    taxonomy_term_delete($valid_term->tid);
421
    $terms = taxonomy_term_load_multiple(array(), array('vid' => $vocabulary->vid));
422
    $this->assertTrue(empty($terms), 'Vocabulary is empty after deletion.');
423

    
424
    // Delete an invalid term. Should not throw any notices.
425
    taxonomy_term_delete(42);
426
  }
427

    
428
  /**
429
   * Test a taxonomy with terms that have multiple parents of different depths.
430
   */
431
  function testTaxonomyVocabularyTree() {
432
    // Create a new vocabulary with 6 terms.
433
    $vocabulary = $this->createVocabulary();
434
    $term = array();
435
    for ($i = 0; $i < 6; $i++) {
436
      $term[$i] = $this->createTerm($vocabulary);
437
    }
438

    
439
    // $term[2] is a child of 1 and 5.
440
    $term[2]->parent = array($term[1]->tid, $term[5]->tid);
441
    taxonomy_term_save($term[2]);
442
    // $term[3] is a child of 2.
443
    $term[3]->parent = array($term[2]->tid);
444
    taxonomy_term_save($term[3]);
445
    // $term[5] is a child of 4.
446
    $term[5]->parent = array($term[4]->tid);
447
    taxonomy_term_save($term[5]);
448

    
449
    /**
450
     * Expected tree:
451
     * term[0] | depth: 0
452
     * term[1] | depth: 0
453
     * -- term[2] | depth: 1
454
     * ---- term[3] | depth: 2
455
     * term[4] | depth: 0
456
     * -- term[5] | depth: 1
457
     * ---- term[2] | depth: 2
458
     * ------ term[3] | depth: 3
459
     */
460
    // Count $term[1] parents with $max_depth = 1.
461
    $tree = taxonomy_get_tree($vocabulary->vid, $term[1]->tid, 1);
462
    $this->assertEqual(1, count($tree), 'We have one parent with depth 1.');
463

    
464
    // Count all vocabulary tree elements.
465
    $tree = taxonomy_get_tree($vocabulary->vid);
466
    $this->assertEqual(8, count($tree), 'We have all vocabulary tree elements.');
467

    
468
    // Count elements in every tree depth.
469
    foreach ($tree as $element) {
470
      if (!isset($depth_count[$element->depth])) {
471
        $depth_count[$element->depth] = 0;
472
      }
473
      $depth_count[$element->depth]++;
474
    }
475
    $this->assertEqual(3, $depth_count[0], 'Three elements in taxonomy tree depth 0.');
476
    $this->assertEqual(2, $depth_count[1], 'Two elements in taxonomy tree depth 1.');
477
    $this->assertEqual(2, $depth_count[2], 'Two elements in taxonomy tree depth 2.');
478
    $this->assertEqual(1, $depth_count[3], 'One element in taxonomy tree depth 3.');
479
  }
480

    
481
}
482

    
483
/**
484
 * Test for legacy node bug.
485
 */
486
class TaxonomyLegacyTestCase extends TaxonomyWebTestCase {
487

    
488
  public static function getInfo() {
489
    return array(
490
      'name' => 'Test for legacy node bug.',
491
      'description' => 'Posts an article with a taxonomy term and a date prior to 1970.',
492
      'group' => 'Taxonomy',
493
    );
494
  }
495

    
496
  function setUp() {
497
    parent::setUp('taxonomy');
498
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'administer nodes', 'bypass node access'));
499
    $this->drupalLogin($this->admin_user);
500
  }
501

    
502
  /**
503
   * Test taxonomy functionality with nodes prior to 1970.
504
   */
505
  function testTaxonomyLegacyNode() {
506
    // Posts an article with a taxonomy term and a date prior to 1970.
507
    $langcode = LANGUAGE_NONE;
508
    $edit = array();
509
    $edit['title'] = $this->randomName();
510
    $edit['date'] = '1969-01-01 00:00:00 -0500';
511
    $edit["body[$langcode][0][value]"] = $this->randomName();
512
    $edit["field_tags[$langcode]"] = $this->randomName();
513
    $this->drupalPost('node/add/article', $edit, t('Save'));
514
    // Checks that the node has been saved.
515
    $node = $this->drupalGetNodeByTitle($edit['title']);
516
    $this->assertEqual($node->created, strtotime($edit['date']), 'Legacy node was saved with the right date.');
517
  }
518

    
519
}
520

    
521
/**
522
 * Tests for taxonomy term functions.
523
 */
524
class TaxonomyTermTestCase extends TaxonomyWebTestCase {
525

    
526
  public static function getInfo() {
527
    return array(
528
      'name' => 'Taxonomy term functions and forms.',
529
      'description' => 'Test load, save and delete for taxonomy terms.',
530
      'group' => 'Taxonomy',
531
    );
532
  }
533

    
534
  function setUp() {
535
    parent::setUp('taxonomy');
536
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
537
    $this->drupalLogin($this->admin_user);
538
    $this->vocabulary = $this->createVocabulary();
539

    
540
    $field = array(
541
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
542
      'type' => 'taxonomy_term_reference',
543
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
544
      'settings' => array(
545
        'allowed_values' => array(
546
          array(
547
            'vocabulary' => $this->vocabulary->machine_name,
548
            'parent' => 0,
549
          ),
550
        ),
551
      ),
552
    );
553
    field_create_field($field);
554

    
555
    $this->instance = array(
556
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
557
      'bundle' => 'article',
558
      'entity_type' => 'node',
559
      'widget' => array(
560
        'type' => 'options_select',
561
      ),
562
      'display' => array(
563
        'default' => array(
564
          'type' => 'taxonomy_term_reference_link',
565
        ),
566
      ),
567
    );
568
    field_create_instance($this->instance);
569
  }
570

    
571
  /**
572
   * Test terms in a single and multiple hierarchy.
573
   */
574
  function testTaxonomyTermHierarchy() {
575
    // Create two taxonomy terms.
576
    $term1 = $this->createTerm($this->vocabulary);
577
    $term2 = $this->createTerm($this->vocabulary);
578

    
579
    // Check that hierarchy is flat.
580
    $vocabulary = taxonomy_vocabulary_load($this->vocabulary->vid);
581
    $this->assertEqual(0, $vocabulary->hierarchy, 'Vocabulary is flat.');
582

    
583
    // Edit $term2, setting $term1 as parent.
584
    $edit = array();
585
    $edit['parent[]'] = array($term1->tid);
586
    $this->drupalPost('taxonomy/term/' . $term2->tid . '/edit', $edit, t('Save'));
587

    
588
    // Check the hierarchy.
589
    $children = taxonomy_get_children($term1->tid);
590
    $parents = taxonomy_get_parents($term2->tid);
591
    $this->assertTrue(isset($children[$term2->tid]), 'Child found correctly.');
592
    $this->assertTrue(isset($parents[$term1->tid]), 'Parent found correctly.');
593

    
594
    // Load and save a term, confirming that parents are still set.
595
    $term = taxonomy_term_load($term2->tid);
596
    taxonomy_term_save($term);
597
    $parents = taxonomy_get_parents($term2->tid);
598
    $this->assertTrue(isset($parents[$term1->tid]), 'Parent found correctly.');
599

    
600
    // Create a third term and save this as a parent of term2.
601
    $term3 = $this->createTerm($this->vocabulary);
602
    $term2->parent = array($term1->tid, $term3->tid);
603
    taxonomy_term_save($term2);
604
    $parents = taxonomy_get_parents($term2->tid);
605
    $this->assertTrue(isset($parents[$term1->tid]) && isset($parents[$term3->tid]), 'Both parents found successfully.');
606
  }
607

    
608
  /**
609
   * Test that hook_node_$op implementations work correctly.
610
   *
611
   * Save & edit a node and assert that taxonomy terms are saved/loaded properly.
612
   */
613
  function testTaxonomyNode() {
614
    // Create two taxonomy terms.
615
    $term1 = $this->createTerm($this->vocabulary);
616
    $term2 = $this->createTerm($this->vocabulary);
617

    
618
    // Post an article.
619
    $edit = array();
620
    $langcode = LANGUAGE_NONE;
621
    $edit["title"] = $this->randomName();
622
    $edit["body[$langcode][0][value]"] = $this->randomName();
623
    $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term1->tid;
624
    $this->drupalPost('node/add/article', $edit, t('Save'));
625

    
626
    // Check that the term is displayed when the node is viewed.
627
    $node = $this->drupalGetNodeByTitle($edit["title"]);
628
    $this->drupalGet('node/' . $node->nid);
629
    $this->assertText($term1->name, 'Term is displayed when viewing the node.');
630

    
631
    // Edit the node with a different term.
632
    $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term2->tid;
633
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
634

    
635
    $this->drupalGet('node/' . $node->nid);
636
    $this->assertText($term2->name, 'Term is displayed when viewing the node.');
637

    
638
    // Preview the node.
639
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Preview'));
640
    $this->assertNoUniqueText($term2->name, 'Term is displayed when previewing the node.');
641
    $this->drupalPost(NULL, NULL, t('Preview'));
642
    $this->assertNoUniqueText($term2->name, 'Term is displayed when previewing the node again.');
643
  }
644

    
645
  /**
646
   * Test term creation with a free-tagging vocabulary from the node form.
647
   */
648
  function testNodeTermCreationAndDeletion() {
649
    // Enable tags in the vocabulary.
650
    $instance = $this->instance;
651
    $instance['widget'] = array('type' => 'taxonomy_autocomplete');
652
    $instance['bundle'] = 'page';
653
    field_create_instance($instance);
654
    $terms = array(
655
      'term1' => $this->randomName(),
656
      'term2' => $this->randomName() . ', ' . $this->randomName(),
657
      'term3' => $this->randomName(),
658
    );
659

    
660
    $edit = array();
661
    $langcode = LANGUAGE_NONE;
662
    $edit["title"] = $this->randomName();
663
    $edit["body[$langcode][0][value]"] = $this->randomName();
664
    // Insert the terms in a comma separated list. Vocabulary 1 is a
665
    // free-tagging field created by the default profile.
666
    $edit[$instance['field_name'] . "[$langcode]"] = drupal_implode_tags($terms);
667

    
668
    // Preview and verify the terms appear but are not created.
669
    $this->drupalPost('node/add/page', $edit, t('Preview'));
670
    foreach ($terms as $term) {
671
      $this->assertText($term, 'The term appears on the node preview.');
672
    }
673
    $tree = taxonomy_get_tree($this->vocabulary->vid);
674
    $this->assertTrue(empty($tree), 'The terms are not created on preview.');
675

    
676
    // taxonomy.module does not maintain its static caches.
677
    drupal_static_reset();
678

    
679
    // Save, creating the terms.
680
    $this->drupalPost('node/add/page', $edit, t('Save'));
681
    $this->assertRaw(t('@type %title has been created.', array('@type' => t('Basic page'), '%title' => $edit["title"])), 'The node was created successfully.');
682
    foreach ($terms as $term) {
683
      $this->assertText($term, 'The term was saved and appears on the node page.');
684
    }
685

    
686
    // Get the created terms.
687
    $term_objects = array();
688
    foreach ($terms as $key => $term) {
689
      $term_objects[$key] = taxonomy_get_term_by_name($term);
690
      $term_objects[$key] = reset($term_objects[$key]);
691
    }
692

    
693
    // Delete term 1.
694
    $this->drupalPost('taxonomy/term/' . $term_objects['term1']->tid . '/edit', array(), t('Delete'));
695
    $this->drupalPost(NULL, NULL, t('Delete'));
696
    $term_names = array($term_objects['term2']->name, $term_objects['term3']->name);
697

    
698
    // Get the node.
699
    $node = $this->drupalGetNodeByTitle($edit["title"]);
700
    $this->drupalGet('node/' . $node->nid);
701

    
702
    foreach ($term_names as $term_name) {
703
      $this->assertText($term_name, format_string('The term %name appears on the node page after one term %deleted was deleted', array('%name' => $term_name, '%deleted' => $term_objects['term1']->name)));
704
    }
705
    $this->assertNoText($term_objects['term1']->name, format_string('The deleted term %name does not appear on the node page.', array('%name' => $term_objects['term1']->name)));
706

    
707
    // Test autocomplete on term 2, which contains a comma.
708
    // The term will be quoted, and the " will be encoded in unicode (\u0022).
709
    $input = substr($term_objects['term2']->name, 0, 3);
710
    $this->drupalGet('taxonomy/autocomplete/taxonomy_' . $this->vocabulary->machine_name . '/' . $input);
711
    $this->assertRaw('{"\u0022' . $term_objects['term2']->name . '\u0022":"' . $term_objects['term2']->name . '"}', format_string('Autocomplete returns term %term_name after typing the first 3 letters.', array('%term_name' => $term_objects['term2']->name)));
712

    
713
    // Test autocomplete on term 3 - it is alphanumeric only, so no extra
714
    // quoting.
715
    $input = substr($term_objects['term3']->name, 0, 3);
716
    $this->drupalGet('taxonomy/autocomplete/taxonomy_' . $this->vocabulary->machine_name . '/' . $input);
717
    $this->assertRaw('{"' . $term_objects['term3']->name . '":"' . $term_objects['term3']->name . '"}', format_string('Autocomplete returns term %term_name after typing the first 3 letters.', array('%term_name' => $term_objects['term3']->name)));
718

    
719
    // Test taxonomy autocomplete with a nonexistent field.
720
    $field_name = $this->randomName();
721
    $tag = $this->randomName();
722
    $message = t("Taxonomy field @field_name not found.", array('@field_name' => $field_name));
723
    $this->assertFalse(field_info_field($field_name), format_string('Field %field_name does not exist.', array('%field_name' => $field_name)));
724
    $this->drupalGet('taxonomy/autocomplete/' . $field_name . '/' . $tag);
725
    $this->assertRaw($message, 'Autocomplete returns correct error message when the taxonomy field does not exist.');
726

    
727
    // Test the autocomplete path without passing a field_name and terms.
728
    // This should not trigger a PHP notice.
729
    $field_name = '';
730
    $message = t("Taxonomy field @field_name not found.", array('@field_name' => $field_name));
731
    $this->drupalGet('taxonomy/autocomplete');
732
    $this->assertRaw($message, 'Autocomplete returns correct error message when no taxonomy field is given.');
733
  }
734

    
735
  /**
736
   * Tests term autocompletion edge cases with slashes in the names.
737
   */
738
  function testTermAutocompletion() {
739
    // Add a term with a slash in the name.
740
    $first_term = $this->createTerm($this->vocabulary);
741
    $first_term->name = '10/16/2011';
742
    taxonomy_term_save($first_term);
743
    // Add another term that differs after the slash character.
744
    $second_term = $this->createTerm($this->vocabulary);
745
    $second_term->name = '10/17/2011';
746
    taxonomy_term_save($second_term);
747
    // Add another term that has both a comma and a slash character.
748
    $third_term = $this->createTerm($this->vocabulary);
749
    $third_term->name = 'term with, a comma and / a slash';
750
    taxonomy_term_save($third_term);
751

    
752
    // Try to autocomplete a term name that matches both terms.
753
    // We should get both term in a json encoded string.
754
    $input = '10/';
755
    $path = 'taxonomy/autocomplete/taxonomy_';
756
    $path .= $this->vocabulary->machine_name . '/' . $input;
757
    // The result order is not guaranteed, so check each term separately.
758
    $url = url($path, array('absolute' => TRUE));
759
    $result = drupal_http_request($url);
760
    $data = drupal_json_decode($result->data);
761
    $this->assertEqual($data[$first_term->name], check_plain($first_term->name), 'Autocomplete returned the first matching term.');
762
    $this->assertEqual($data[$second_term->name], check_plain($second_term->name), 'Autocomplete returned the second matching term.');
763

    
764
    // Try to autocomplete a term name that matches first term.
765
    // We should only get the first term in a json encoded string.
766
    $input = '10/16';
767
    $url = 'taxonomy/autocomplete/taxonomy_';
768
    $url .= $this->vocabulary->machine_name . '/' . $input;
769
    $this->drupalGet($url);
770
    $target = array($first_term->name => check_plain($first_term->name));
771
    $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns only the expected matching term.');
772

    
773
    // Try to autocomplete a term name with both a comma and a slash.
774
    $input = '"term with, comma and / a';
775
    $url = 'taxonomy/autocomplete/taxonomy_';
776
    $url .= $this->vocabulary->machine_name . '/' . $input;
777
    $this->drupalGet($url);
778
    $n = $third_term->name;
779
    // Term names containing commas or quotes must be wrapped in quotes.
780
    if (strpos($third_term->name, ',') !== FALSE || strpos($third_term->name, '"') !== FALSE) {
781
      $n = '"' . str_replace('"', '""', $third_term->name) . '"';
782
    }
783
    $target = array($n => check_plain($third_term->name));
784
    $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns a term containing a comma and a slash.');
785
  }
786

    
787
  /**
788
   * Save, edit and delete a term using the user interface.
789
   */
790
  function testTermInterface() {
791
    $edit = array(
792
      'name' => $this->randomName(12),
793
      'description[value]' => $this->randomName(100),
794
    );
795
    // Explicitly set the parents field to 'root', to ensure that
796
    // taxonomy_form_term_submit() handles the invalid term ID correctly.
797
    $edit['parent[]'] = array(0);
798

    
799
    // Create the term to edit.
800
    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));
801

    
802
    $terms = taxonomy_get_term_by_name($edit['name']);
803
    $term = reset($terms);
804
    $this->assertNotNull($term, 'Term found in database.');
805

    
806
    // Submitting a term takes us to the add page; we need the List page.
807
    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
808

    
809
    // Test edit link as accessed from Taxonomy administration pages.
810
    // Because Simpletest creates its own database when running tests, we know
811
    // the first edit link found on the listing page is to our term.
812
    $this->clickLink(t('edit'));
813

    
814
    $this->assertRaw($edit['name'], 'The randomly generated term name is present.');
815
    $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');
816

    
817
    $edit = array(
818
      'name' => $this->randomName(14),
819
      'description[value]' => $this->randomName(102),
820
    );
821

    
822
    // Edit the term.
823
    $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));
824

    
825
    // Check that the term is still present at admin UI after edit.
826
    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
827
    $this->assertText($edit['name'], 'The randomly generated term name is present.');
828
    $this->assertLink(t('edit'));
829

    
830
    // View the term and check that it is correct.
831
    $this->drupalGet('taxonomy/term/' . $term->tid);
832
    $this->assertText($edit['name'], 'The randomly generated term name is present.');
833
    $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');
834

    
835
    // Did this page request display a 'term-listing-heading'?
836
    $this->assertPattern('|class="taxonomy-term-description"|', 'Term page displayed the term description element.');
837
    // Check that it does NOT show a description when description is blank.
838
    $term->description = '';
839
    taxonomy_term_save($term);
840
    $this->drupalGet('taxonomy/term/' . $term->tid);
841
    $this->assertNoPattern('|class="taxonomy-term-description"|', 'Term page did not display the term description when description was blank.');
842

    
843
    // Check that the term feed page is working.
844
    $this->drupalGet('taxonomy/term/' . $term->tid . '/feed');
845

    
846
    // Check that the term edit page does not try to interpret additional path
847
    // components as arguments for taxonomy_form_term().
848
    $this->drupalGet('taxonomy/term/' . $term->tid . '/edit/' . $this->randomName());
849

    
850
    // Delete the term.
851
    $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', array(), t('Delete'));
852
    $this->drupalPost(NULL, NULL, t('Delete'));
853

    
854
    // Assert that the term no longer exists.
855
    $this->drupalGet('taxonomy/term/' . $term->tid);
856
    $this->assertResponse(404, 'The taxonomy term page was not found.');
857
  }
858

    
859
  /**
860
   * Save, edit and delete a term using the user interface.
861
   */
862
  function testTermReorder() {
863
    $this->createTerm($this->vocabulary);
864
    $this->createTerm($this->vocabulary);
865
    $this->createTerm($this->vocabulary);
866

    
867
    // Fetch the created terms in the default alphabetical order, i.e. term1
868
    // precedes term2 alphabetically, and term2 precedes term3.
869
    drupal_static_reset('taxonomy_get_tree');
870
    drupal_static_reset('taxonomy_get_treeparent');
871
    drupal_static_reset('taxonomy_get_treeterms');
872
    list($term1, $term2, $term3) = taxonomy_get_tree($this->vocabulary->vid);
873

    
874
    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
875

    
876
    // Each term has four hidden fields, "tid:1:0[tid]", "tid:1:0[parent]",
877
    // "tid:1:0[depth]", and "tid:1:0[weight]". Change the order to term2,
878
    // term3, term1 by setting weight property, make term3 a child of term2 by
879
    // setting the parent and depth properties, and update all hidden fields.
880
    $edit = array(
881
      'tid:' . $term2->tid . ':0[tid]' => $term2->tid,
882
      'tid:' . $term2->tid . ':0[parent]' => 0,
883
      'tid:' . $term2->tid . ':0[depth]' => 0,
884
      'tid:' . $term2->tid . ':0[weight]' => 0,
885
      'tid:' . $term3->tid . ':0[tid]' => $term3->tid,
886
      'tid:' . $term3->tid . ':0[parent]' => $term2->tid,
887
      'tid:' . $term3->tid . ':0[depth]' => 1,
888
      'tid:' . $term3->tid . ':0[weight]' => 1,
889
      'tid:' . $term1->tid . ':0[tid]' => $term1->tid,
890
      'tid:' . $term1->tid . ':0[parent]' => 0,
891
      'tid:' . $term1->tid . ':0[depth]' => 0,
892
      'tid:' . $term1->tid . ':0[weight]' => 2,
893
    );
894
    $this->drupalPost(NULL, $edit, t('Save'));
895

    
896
    drupal_static_reset('taxonomy_get_tree');
897
    drupal_static_reset('taxonomy_get_treeparent');
898
    drupal_static_reset('taxonomy_get_treeterms');
899
    $terms = taxonomy_get_tree($this->vocabulary->vid);
900
    $this->assertEqual($terms[0]->tid, $term2->tid, 'Term 2 was moved above term 1.');
901
    $this->assertEqual($terms[1]->parents, array($term2->tid), 'Term 3 was made a child of term 2.');
902
    $this->assertEqual($terms[2]->tid, $term1->tid, 'Term 1 was moved below term 2.');
903

    
904
    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name, array(), t('Reset to alphabetical'));
905
    // Submit confirmation form.
906
    $this->drupalPost(NULL, array(), t('Reset to alphabetical'));
907

    
908
    drupal_static_reset('taxonomy_get_tree');
909
    drupal_static_reset('taxonomy_get_treeparent');
910
    drupal_static_reset('taxonomy_get_treeterms');
911
    $terms = taxonomy_get_tree($this->vocabulary->vid);
912
    $this->assertEqual($terms[0]->tid, $term1->tid, 'Term 1 was moved to back above term 2.');
913
    $this->assertEqual($terms[1]->tid, $term2->tid, 'Term 2 was moved to back below term 1.');
914
    $this->assertEqual($terms[2]->tid, $term3->tid, 'Term 3 is still below term 2.');
915
    $this->assertEqual($terms[2]->parents, array($term2->tid), 'Term 3 is still a child of term 2.' . var_export($terms[1]->tid, 1));
916
  }
917

    
918
  /**
919
   * Test saving a term with multiple parents through the UI.
920
   */
921
  function testTermMultipleParentsInterface() {
922
    // Add a new term to the vocabulary so that we can have multiple parents.
923
    $parent = $this->createTerm($this->vocabulary);
924

    
925
    // Add a new term with multiple parents.
926
    $edit = array(
927
      'name' => $this->randomName(12),
928
      'description[value]' => $this->randomName(100),
929
      'parent[]' => array(0, $parent->tid),
930
    );
931
    // Save the new term.
932
    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));
933

    
934
    // Check that the term was successfully created.
935
    $terms = taxonomy_get_term_by_name($edit['name']);
936
    $term = reset($terms);
937
    $this->assertNotNull($term, 'Term found in database.');
938
    $this->assertEqual($edit['name'], $term->name, 'Term name was successfully saved.');
939
    $this->assertEqual($edit['description[value]'], $term->description, 'Term description was successfully saved.');
940
    // Check that the parent tid is still there. The other parent (<root>) is
941
    // not added by taxonomy_get_parents().
942
    $parents = taxonomy_get_parents($term->tid);
943
    $parent = reset($parents);
944
    $this->assertEqual($edit['parent[]'][1], $parent->tid, 'Term parents were successfully saved.');
945
  }
946

    
947
  /**
948
   * Test taxonomy_get_term_by_name().
949
   */
950
  function testTaxonomyGetTermByName() {
951
    $term = $this->createTerm($this->vocabulary);
952

    
953
    // Load the term with the exact name.
954
    $terms = taxonomy_get_term_by_name($term->name);
955
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name.');
956

    
957
    // Load the term with space concatenated.
958
    $terms  = taxonomy_get_term_by_name('  ' . $term->name . '   ');
959
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with extra whitespace.');
960

    
961
    // Load the term with name uppercased.
962
    $terms = taxonomy_get_term_by_name(strtoupper($term->name));
963
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with uppercased name.');
964

    
965
    // Load the term with name lowercased.
966
    $terms = taxonomy_get_term_by_name(strtolower($term->name));
967
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with lowercased name.');
968

    
969
    // Try to load an invalid term name.
970
    $terms = taxonomy_get_term_by_name('Banana');
971
    $this->assertFalse($terms);
972

    
973
    // Try to load the term using a substring of the name.
974
    $terms = taxonomy_get_term_by_name(drupal_substr($term->name, 2));
975
    $this->assertFalse($terms);
976

    
977
    // Create a new term in a different vocabulary with the same name.
978
    $new_vocabulary = $this->createVocabulary();
979
    $new_term = new stdClass();
980
    $new_term->name = $term->name;
981
    $new_term->vid = $new_vocabulary->vid;
982
    taxonomy_term_save($new_term);
983

    
984
    // Load multiple terms with the same name.
985
    $terms = taxonomy_get_term_by_name($term->name);
986
    $this->assertEqual(count($terms), 2, 'Two terms loaded with the same name.');
987

    
988
    // Load single term when restricted to one vocabulary.
989
    $terms = taxonomy_get_term_by_name($term->name, $this->vocabulary->machine_name);
990
    $this->assertEqual(count($terms), 1, 'One term loaded when restricted by vocabulary.');
991
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name and vocabulary machine name.');
992

    
993
    // Create a new term with another name.
994
    $term2 = $this->createTerm($this->vocabulary);
995

    
996
    // Try to load a term by name that doesn't exist in this vocabulary but
997
    // exists in another vocabulary.
998
    $terms = taxonomy_get_term_by_name($term2->name, $new_vocabulary->machine_name);
999
    $this->assertFalse($terms, 'Invalid term name restricted by vocabulary machine name not loaded.');
1000

    
1001
    // Try to load terms filtering by a non-existing vocabulary.
1002
    $terms = taxonomy_get_term_by_name($term2->name, 'non_existing_vocabulary');
1003
    $this->assertEqual(count($terms), 0, 'No terms loaded when restricted by a non-existing vocabulary.');
1004
  }
1005

    
1006
}
1007

    
1008
/**
1009
 * Tests the rendering of term reference fields in RSS feeds.
1010
 */
1011
class TaxonomyRSSTestCase extends TaxonomyWebTestCase {
1012

    
1013
  public static function getInfo() {
1014
    return array(
1015
      'name' => 'Taxonomy RSS Content.',
1016
      'description' => 'Ensure that data added as terms appears in RSS feeds if "RSS Category" format is selected.',
1017
      'group' => 'Taxonomy',
1018
    );
1019
  }
1020

    
1021
  function setUp() {
1022
    parent::setUp('taxonomy');
1023
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access', 'administer content types'));
1024
    $this->drupalLogin($this->admin_user);
1025
    $this->vocabulary = $this->createVocabulary();
1026

    
1027
    $field = array(
1028
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
1029
      'type' => 'taxonomy_term_reference',
1030
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1031
      'settings' => array(
1032
        'allowed_values' => array(
1033
          array(
1034
            'vocabulary' => $this->vocabulary->machine_name,
1035
            'parent' => 0,
1036
          ),
1037
        ),
1038
      ),
1039
    );
1040
    field_create_field($field);
1041

    
1042
    $this->instance = array(
1043
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
1044
      'bundle' => 'article',
1045
      'entity_type' => 'node',
1046
      'widget' => array(
1047
        'type' => 'options_select',
1048
      ),
1049
      'display' => array(
1050
        'default' => array(
1051
          'type' => 'taxonomy_term_reference_link',
1052
        ),
1053
      ),
1054
    );
1055
    field_create_instance($this->instance);
1056
  }
1057

    
1058
  /**
1059
   * Tests that terms added to nodes are displayed in core RSS feed.
1060
   *
1061
   * Create a node and assert that taxonomy terms appear in rss.xml.
1062
   */
1063
  function testTaxonomyRSS() {
1064
    // Create two taxonomy terms.
1065
    $term1 = $this->createTerm($this->vocabulary);
1066

    
1067
    // RSS display must be added manually.
1068
    $this->drupalGet("admin/structure/types/manage/article/display");
1069
    $edit = array(
1070
      "view_modes_custom[rss]" => '1',
1071
    );
1072
    $this->drupalPost(NULL, $edit, t('Save'));
1073

    
1074
    // Change the format to 'RSS category'.
1075
    $this->drupalGet("admin/structure/types/manage/article/display/rss");
1076
    $edit = array(
1077
      "fields[taxonomy_" . $this->vocabulary->machine_name . "][type]" => 'taxonomy_term_reference_rss_category',
1078
    );
1079
    $this->drupalPost(NULL, $edit, t('Save'));
1080

    
1081
    // Post an article.
1082
    $edit = array();
1083
    $langcode = LANGUAGE_NONE;
1084
    $edit["title"] = $this->randomName();
1085
    $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term1->tid;
1086
    $this->drupalPost('node/add/article', $edit, t('Save'));
1087

    
1088
    // Check that the term is displayed when the RSS feed is viewed.
1089
    $this->drupalGet('rss.xml');
1090
    $test_element = array(
1091
      'key' => 'category',
1092
      'value' => $term1->name,
1093
      'attributes' => array(
1094
        'domain' => url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE)),
1095
      ),
1096
    );
1097
    $this->assertRaw(format_xml_elements(array($test_element)), 'Term is displayed when viewing the rss feed.');
1098
  }
1099

    
1100
}
1101

    
1102
/**
1103
 * Tests the hook implementations that maintain the taxonomy index.
1104
 */
1105
class TaxonomyTermIndexTestCase extends TaxonomyWebTestCase {
1106

    
1107
  public static function getInfo() {
1108
    return array(
1109
      'name' => 'Taxonomy term index',
1110
      'description' => 'Tests the hook implementations that maintain the taxonomy index.',
1111
      'group' => 'Taxonomy',
1112
    );
1113
  }
1114

    
1115
  function setUp() {
1116
    parent::setUp('taxonomy');
1117

    
1118
    // Create an administrative user.
1119
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
1120
    $this->drupalLogin($this->admin_user);
1121

    
1122
    // Create a vocabulary and add two term reference fields to article nodes.
1123
    $this->vocabulary = $this->createVocabulary();
1124

    
1125
    $this->field_name_1 = drupal_strtolower($this->randomName());
1126
    $this->field_1 = array(
1127
      'field_name' => $this->field_name_1,
1128
      'type' => 'taxonomy_term_reference',
1129
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1130
      'settings' => array(
1131
        'allowed_values' => array(
1132
          array(
1133
            'vocabulary' => $this->vocabulary->machine_name,
1134
            'parent' => 0,
1135
          ),
1136
        ),
1137
      ),
1138
    );
1139
    field_create_field($this->field_1);
1140
    $this->instance_1 = array(
1141
      'field_name' => $this->field_name_1,
1142
      'bundle' => 'article',
1143
      'entity_type' => 'node',
1144
      'widget' => array(
1145
        'type' => 'options_select',
1146
      ),
1147
      'display' => array(
1148
        'default' => array(
1149
          'type' => 'taxonomy_term_reference_link',
1150
        ),
1151
      ),
1152
    );
1153
    field_create_instance($this->instance_1);
1154

    
1155
    $this->field_name_2 = drupal_strtolower($this->randomName());
1156
    $this->field_2 = array(
1157
      'field_name' => $this->field_name_2,
1158
      'type' => 'taxonomy_term_reference',
1159
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1160
      'settings' => array(
1161
        'allowed_values' => array(
1162
          array(
1163
            'vocabulary' => $this->vocabulary->machine_name,
1164
            'parent' => 0,
1165
          ),
1166
        ),
1167
      ),
1168
    );
1169
    field_create_field($this->field_2);
1170
    $this->instance_2 = array(
1171
      'field_name' => $this->field_name_2,
1172
      'bundle' => 'article',
1173
      'entity_type' => 'node',
1174
      'widget' => array(
1175
        'type' => 'options_select',
1176
      ),
1177
      'display' => array(
1178
        'default' => array(
1179
          'type' => 'taxonomy_term_reference_link',
1180
        ),
1181
      ),
1182
    );
1183
    field_create_instance($this->instance_2);
1184
  }
1185

    
1186
  /**
1187
   * Tests that the taxonomy index is maintained properly.
1188
   */
1189
  function testTaxonomyIndex() {
1190
    // Create terms in the vocabulary.
1191
    $term_1 = $this->createTerm($this->vocabulary);
1192
    $term_2 = $this->createTerm($this->vocabulary);
1193

    
1194
    // Post an article.
1195
    $edit = array();
1196
    $langcode = LANGUAGE_NONE;
1197
    $edit["title"] = $this->randomName();
1198
    $edit["body[$langcode][0][value]"] = $this->randomName();
1199
    $edit["{$this->field_name_1}[$langcode][]"] = $term_1->tid;
1200
    $edit["{$this->field_name_2}[$langcode][]"] = $term_1->tid;
1201
    $this->drupalPost('node/add/article', $edit, t('Save'));
1202

    
1203
    // Check that the term is indexed, and only once.
1204
    $node = $this->drupalGetNodeByTitle($edit["title"]);
1205
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1206
      ':nid' => $node->nid,
1207
      ':tid' => $term_1->tid,
1208
    ))->fetchField();
1209
    $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');
1210

    
1211
    // Update the article to change one term.
1212
    $edit["{$this->field_name_1}[$langcode][]"] = $term_2->tid;
1213
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
1214

    
1215
    // Check that both terms are indexed.
1216
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1217
      ':nid' => $node->nid,
1218
      ':tid' => $term_1->tid,
1219
    ))->fetchField();
1220
    $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
1221
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1222
      ':nid' => $node->nid,
1223
      ':tid' => $term_2->tid,
1224
    ))->fetchField();
1225
    $this->assertEqual(1, $index_count, 'Term 2 is indexed.');
1226

    
1227
    // Update the article to change another term.
1228
    $edit["{$this->field_name_2}[$langcode][]"] = $term_2->tid;
1229
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
1230

    
1231
    // Check that only one term is indexed.
1232
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1233
      ':nid' => $node->nid,
1234
      ':tid' => $term_1->tid,
1235
    ))->fetchField();
1236
    $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
1237
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1238
      ':nid' => $node->nid,
1239
      ':tid' => $term_2->tid,
1240
    ))->fetchField();
1241
    $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');
1242

    
1243
    // Redo the above tests without interface.
1244
    $update_node = array(
1245
      'nid' => $node->nid,
1246
      'vid' => $node->vid,
1247
      'uid' => $node->uid,
1248
      'type' => $node->type,
1249
      'title' => $this->randomName(),
1250
    );
1251

    
1252
    // Update the article with no term changed.
1253
    $updated_node = (object) $update_node;
1254
    node_save($updated_node);
1255

    
1256
    // Check that the index was not changed.
1257
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1258
      ':nid' => $node->nid,
1259
      ':tid' => $term_1->tid,
1260
    ))->fetchField();
1261
    $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
1262
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1263
      ':nid' => $node->nid,
1264
      ':tid' => $term_2->tid,
1265
    ))->fetchField();
1266
    $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');
1267

    
1268
    // Update the article to change one term.
1269
    $update_node[$this->field_name_1][$langcode] = array(array('tid' => $term_1->tid));
1270
    $updated_node = (object) $update_node;
1271
    node_save($updated_node);
1272

    
1273
    // Check that both terms are indexed.
1274
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1275
      ':nid' => $node->nid,
1276
      ':tid' => $term_1->tid,
1277
    ))->fetchField();
1278
    $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
1279
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1280
      ':nid' => $node->nid,
1281
      ':tid' => $term_2->tid,
1282
    ))->fetchField();
1283
    $this->assertEqual(1, $index_count, 'Term 2 is indexed.');
1284

    
1285
    // Update the article to change another term.
1286
    $update_node[$this->field_name_2][$langcode] = array(array('tid' => $term_1->tid));
1287
    $updated_node = (object) $update_node;
1288
    node_save($updated_node);
1289

    
1290
    // Check that only one term is indexed.
1291
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1292
      ':nid' => $node->nid,
1293
      ':tid' => $term_1->tid,
1294
    ))->fetchField();
1295
    $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');
1296
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
1297
      ':nid' => $node->nid,
1298
      ':tid' => $term_2->tid,
1299
    ))->fetchField();
1300
    $this->assertEqual(0, $index_count, 'Term 2 is not indexed.');
1301
  }
1302

    
1303
  /**
1304
   * Tests that there is a link to the parent term on the child term page.
1305
   */
1306
  function testTaxonomyTermHierarchyBreadcrumbs() {
1307
    // Create two taxonomy terms and set term2 as the parent of term1.
1308
    $term1 = $this->createTerm($this->vocabulary);
1309
    $term2 = $this->createTerm($this->vocabulary);
1310
    $term1->parent = array($term2->tid);
1311
    taxonomy_term_save($term1);
1312

    
1313
    // Verify that the page breadcrumbs include a link to the parent term.
1314
    $this->drupalGet('taxonomy/term/' . $term1->tid);
1315
    $this->assertRaw(l($term2->name, 'taxonomy/term/' . $term2->tid), 'Parent term link is displayed when viewing the node.');
1316
  }
1317

    
1318
}
1319

    
1320
/**
1321
 * Test the taxonomy_term_load_multiple() function.
1322
 */
1323
class TaxonomyLoadMultipleTestCase extends TaxonomyWebTestCase {
1324

    
1325
  public static function getInfo() {
1326
    return array(
1327
      'name' => 'Taxonomy term multiple loading',
1328
      'description' => 'Test the loading of multiple taxonomy terms at once',
1329
      'group' => 'Taxonomy',
1330
    );
1331
  }
1332

    
1333
  function setUp() {
1334
    parent::setUp();
1335
    $this->taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
1336
    $this->drupalLogin($this->taxonomy_admin);
1337
  }
1338

    
1339
  /**
1340
   * Create a vocabulary and some taxonomy terms, ensuring they're loaded
1341
   * correctly using taxonomy_term_load_multiple().
1342
   */
1343
  function testTaxonomyTermMultipleLoad() {
1344
    // Create a vocabulary.
1345
    $vocabulary = $this->createVocabulary();
1346

    
1347
    // Create five terms in the vocabulary.
1348
    $i = 0;
1349
    while ($i < 5) {
1350
      $i++;
1351
      $this->createTerm($vocabulary);
1352
    }
1353
    // Load the terms from the vocabulary.
1354
    $terms = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
1355
    $count = count($terms);
1356
    $this->assertEqual($count, 5, format_string('Correct number of terms were loaded. !count terms.', array('!count' => $count)));
1357

    
1358
    // Load the same terms again by tid.
1359
    $terms2 = taxonomy_term_load_multiple(array_keys($terms));
1360
    $this->assertEqual($count, count($terms2), 'Five terms were loaded by tid.');
1361
    $this->assertEqual($terms, $terms2, 'Both arrays contain the same terms.');
1362

    
1363
    // Load the terms by tid, with a condition on vid.
1364
    $terms3 = taxonomy_term_load_multiple(array_keys($terms2), array('vid' => $vocabulary->vid));
1365
    $this->assertEqual($terms2, $terms3);
1366

    
1367
    // Remove one term from the array, then delete it.
1368
    $deleted = array_shift($terms3);
1369
    taxonomy_term_delete($deleted->tid);
1370
    $deleted_term = taxonomy_term_load($deleted->tid);
1371
    $this->assertFalse($deleted_term);
1372

    
1373
    // Load terms from the vocabulary by vid.
1374
    $terms4 = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
1375
    $this->assertEqual(count($terms4), 4, 'Correct number of terms were loaded.');
1376
    $this->assertFalse(isset($terms4[$deleted->tid]));
1377

    
1378
    // Create a single term and load it by name.
1379
    $term = $this->createTerm($vocabulary);
1380
    $loaded_terms = taxonomy_term_load_multiple(array(), array('name' => $term->name));
1381
    $this->assertEqual(count($loaded_terms), 1, 'One term was loaded.');
1382
    $loaded_term = reset($loaded_terms);
1383
    $this->assertEqual($term->tid, $loaded_term->tid, 'Term loaded by name successfully.');
1384
  }
1385
}
1386

    
1387
/**
1388
 * Tests for taxonomy hook invocation.
1389
 */
1390
class TaxonomyHooksTestCase extends TaxonomyWebTestCase {
1391
  public static function getInfo() {
1392
    return array(
1393
      'name' => 'Taxonomy term hooks',
1394
      'description' => 'Hooks for taxonomy term load/save/delete.',
1395
      'group' => 'Taxonomy',
1396
    );
1397
  }
1398

    
1399
  function setUp() {
1400
    parent::setUp('taxonomy', 'taxonomy_test');
1401
    module_load_include('inc', 'taxonomy', 'taxonomy.pages');
1402
    $taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
1403
    $this->drupalLogin($taxonomy_admin);
1404
  }
1405

    
1406
  /**
1407
   * Test that hooks are run correctly on creating, editing, viewing,
1408
   * and deleting a term.
1409
   *
1410
   * @see taxonomy_test.module
1411
   */
1412
  function testTaxonomyTermHooks() {
1413
    $vocabulary = $this->createVocabulary();
1414

    
1415
    // Create a term with one antonym.
1416
    $edit = array(
1417
      'name' => $this->randomName(),
1418
      'antonym' => 'Long',
1419
    );
1420
    $this->drupalPost('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add', $edit, t('Save'));
1421
    $terms = taxonomy_get_term_by_name($edit['name']);
1422
    $term = reset($terms);
1423
    $this->assertEqual($term->antonym, $edit['antonym'], 'Antonym was loaded into the term object.');
1424

    
1425
    // Update the term with a different antonym.
1426
    $edit = array(
1427
      'name' => $this->randomName(),
1428
      'antonym' => 'Short',
1429
    );
1430
    $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));
1431
    taxonomy_terms_static_reset();
1432
    $term = taxonomy_term_load($term->tid);
1433
    $this->assertEqual($edit['antonym'], $term->antonym, 'Antonym was successfully edited.');
1434

    
1435
    // View the term and ensure that hook_taxonomy_term_view() and
1436
    // hook_entity_view() are invoked.
1437
    $term = taxonomy_term_load($term->tid);
1438
    $term_build = taxonomy_term_page($term);
1439
    $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_term_view_check']), 'hook_taxonomy_term_view() was invoked when viewing the term.');
1440
    $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_entity_view_check']), 'hook_entity_view() was invoked when viewing the term.');
1441

    
1442
    // Delete the term.
1443
    taxonomy_term_delete($term->tid);
1444
    $antonym = db_query('SELECT tid FROM {taxonomy_term_antonym} WHERE tid = :tid', array(':tid' => $term->tid))->fetchField();
1445
    $this->assertFalse($antonym, 'The antonym were deleted from the database.');
1446
  }
1447

    
1448
}
1449

    
1450
/**
1451
 * Tests for taxonomy term field and formatter.
1452
 */
1453
class TaxonomyTermFieldTestCase extends TaxonomyWebTestCase {
1454

    
1455
  protected $instance;
1456
  protected $vocabulary;
1457

    
1458
  public static function getInfo() {
1459
    return array(
1460
      'name' => 'Taxonomy term reference field',
1461
      'description' => 'Test the creation of term fields.',
1462
      'group' => 'Taxonomy',
1463
    );
1464
  }
1465

    
1466
  function setUp() {
1467
    parent::setUp('field_test');
1468

    
1469
    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
1470
    $this->drupalLogin($web_user);
1471
    $this->vocabulary = $this->createVocabulary();
1472

    
1473
    // Setup a field and instance.
1474
    $this->field_name = drupal_strtolower($this->randomName());
1475
    $this->field = array(
1476
      'field_name' => $this->field_name,
1477
      'type' => 'taxonomy_term_reference',
1478
      'settings' => array(
1479
        'allowed_values' => array(
1480
          array(
1481
            'vocabulary' => $this->vocabulary->machine_name,
1482
            'parent' => '0',
1483
          ),
1484
        ),
1485
      )
1486
    );
1487
    field_create_field($this->field);
1488
    $this->instance = array(
1489
      'field_name' => $this->field_name,
1490
      'entity_type' => 'test_entity',
1491
      'bundle' => 'test_bundle',
1492
      'widget' => array(
1493
        'type' => 'options_select',
1494
      ),
1495
      'display' => array(
1496
        'full' => array(
1497
          'type' => 'taxonomy_term_reference_link',
1498
        ),
1499
      ),
1500
    );
1501
    field_create_instance($this->instance);
1502
  }
1503

    
1504
  /**
1505
   * Test term field validation.
1506
   */
1507
  function testTaxonomyTermFieldValidation() {
1508
    // Test valid and invalid values with field_attach_validate().
1509
    $langcode = LANGUAGE_NONE;
1510
    $entity = field_test_create_stub_entity();
1511
    $term = $this->createTerm($this->vocabulary);
1512
    $entity->{$this->field_name}[$langcode][0]['tid'] = $term->tid;
1513
    try {
1514
      field_attach_validate('test_entity', $entity);
1515
      $this->pass('Correct term does not cause validation error.');
1516
    }
1517
    catch (FieldValidationException $e) {
1518
      $this->fail('Correct term does not cause validation error.');
1519
    }
1520

    
1521
    $entity = field_test_create_stub_entity();
1522
    $bad_term = $this->createTerm($this->createVocabulary());
1523
    $entity->{$this->field_name}[$langcode][0]['tid'] = $bad_term->tid;
1524
    try {
1525
      field_attach_validate('test_entity', $entity);
1526
      $this->fail('Wrong term causes validation error.');
1527
    }
1528
    catch (FieldValidationException $e) {
1529
      $this->pass('Wrong term causes validation error.');
1530
    }
1531
  }
1532

    
1533
  /**
1534
   * Test widgets.
1535
   */
1536
  function testTaxonomyTermFieldWidgets() {
1537
    // Create a term in the vocabulary.
1538
    $term = $this->createTerm($this->vocabulary);
1539

    
1540
    // Display creation form.
1541
    $langcode = LANGUAGE_NONE;
1542
    $this->drupalGet('test-entity/add/test-bundle');
1543
    $this->assertFieldByName("{$this->field_name}[$langcode]", '', 'Widget is displayed.');
1544

    
1545
    // Submit with some value.
1546
    $edit = array(
1547
      "{$this->field_name}[$langcode]" => array($term->tid),
1548
    );
1549
    $this->drupalPost(NULL, $edit, t('Save'));
1550
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
1551
    $id = $match[1];
1552
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');
1553

    
1554
    // Display the object.
1555
    $entity = field_test_entity_test_load($id);
1556
    $entities = array($id => $entity);
1557
    field_attach_prepare_view('test_entity', $entities, 'full');
1558
    $entity->content = field_attach_view('test_entity', $entity, 'full');
1559
    $this->content = drupal_render($entity->content);
1560
    $this->assertText($term->name, 'Term name is displayed.');
1561

    
1562
    // Delete the vocabulary and verify that the widget is gone.
1563
    taxonomy_vocabulary_delete($this->vocabulary->vid);
1564
    $this->drupalGet('test-entity/add/test-bundle');
1565
    $this->assertNoFieldByName("{$this->field_name}[$langcode]", '', 'Widget is not displayed.');
1566
  }
1567

    
1568
  /**
1569
   * Tests that vocabulary machine name changes are mirrored in field definitions.
1570
   */
1571
  function testTaxonomyTermFieldChangeMachineName() {
1572
    // Add several entries in the 'allowed_values' setting, to make sure that
1573
    // they all get updated.
1574
    $this->field['settings']['allowed_values'] = array(
1575
      array(
1576
        'vocabulary' => $this->vocabulary->machine_name,
1577
        'parent' => '0',
1578
      ),
1579
      array(
1580
        'vocabulary' => $this->vocabulary->machine_name,
1581
        'parent' => '0',
1582
      ),
1583
      array(
1584
        'vocabulary' => 'foo',
1585
        'parent' => '0',
1586
      ),
1587
    );
1588
    field_update_field($this->field);
1589
    // Change the machine name.
1590
    $old_name = $this->vocabulary->machine_name;
1591
    $new_name = drupal_strtolower($this->randomName());
1592
    $this->vocabulary->machine_name = $new_name;
1593
    taxonomy_vocabulary_save($this->vocabulary);
1594

    
1595
    // Check that entity bundles are properly updated.
1596
    $info = entity_get_info('taxonomy_term');
1597
    $this->assertFalse(isset($info['bundles'][$old_name]), 'The old bundle name does not appear in entity_get_info().');
1598
    $this->assertTrue(isset($info['bundles'][$new_name]), 'The new bundle name appears in entity_get_info().');
1599

    
1600
    // Check that the field instance is still attached to the vocabulary.
1601
    $field = field_info_field($this->field_name);
1602
    $allowed_values = $field['settings']['allowed_values'];
1603
    $this->assertEqual($allowed_values[0]['vocabulary'], $new_name, 'Index 0: Machine name was updated correctly.');
1604
    $this->assertEqual($allowed_values[1]['vocabulary'], $new_name, 'Index 1: Machine name was updated correctly.');
1605
    $this->assertEqual($allowed_values[2]['vocabulary'], 'foo', 'Index 2: Machine name was left untouched.');
1606
  }
1607

    
1608
}
1609

    
1610
/**
1611
 * Tests a taxonomy term reference field that allows multiple vocabularies.
1612
 */
1613
class TaxonomyTermFieldMultipleVocabularyTestCase extends TaxonomyWebTestCase {
1614

    
1615
  protected $instance;
1616
  protected $vocabulary1;
1617
  protected $vocabulary2;
1618

    
1619
  public static function getInfo() {
1620
    return array(
1621
      'name' => 'Multiple vocabulary term reference field',
1622
      'description' => 'Tests term reference fields that allow multiple vocabularies.',
1623
      'group' => 'Taxonomy',
1624
    );
1625
  }
1626

    
1627
  function setUp() {
1628
    parent::setUp('field_test');
1629

    
1630
    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
1631
    $this->drupalLogin($web_user);
1632
    $this->vocabulary1 = $this->createVocabulary();
1633
    $this->vocabulary2 = $this->createVocabulary();
1634

    
1635
    // Set up a field and instance.
1636
    $this->field_name = drupal_strtolower($this->randomName());
1637
    $this->field = array(
1638
      'field_name' => $this->field_name,
1639
      'type' => 'taxonomy_term_reference',
1640
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1641
      'settings' => array(
1642
        'allowed_values' => array(
1643
          array(
1644
            'vocabulary' => $this->vocabulary1->machine_name,
1645
            'parent' => '0',
1646
          ),
1647
          array(
1648
            'vocabulary' => $this->vocabulary2->machine_name,
1649
            'parent' => '0',
1650
          ),
1651
        ),
1652
      )
1653
    );
1654
    field_create_field($this->field);
1655
    $this->instance = array(
1656
      'field_name' => $this->field_name,
1657
      'entity_type' => 'test_entity',
1658
      'bundle' => 'test_bundle',
1659
      'widget' => array(
1660
        'type' => 'options_select',
1661
      ),
1662
      'display' => array(
1663
        'full' => array(
1664
          'type' => 'taxonomy_term_reference_link',
1665
        ),
1666
      ),
1667
    );
1668
    field_create_instance($this->instance);
1669
  }
1670

    
1671
  /**
1672
   * Tests term reference field and widget with multiple vocabularies.
1673
   */
1674
  function testTaxonomyTermFieldMultipleVocabularies() {
1675
    // Create a term in each vocabulary.
1676
    $term1 = $this->createTerm($this->vocabulary1);
1677
    $term2 = $this->createTerm($this->vocabulary2);
1678

    
1679
    // Submit an entity with both terms.
1680
    $langcode = LANGUAGE_NONE;
1681
    $this->drupalGet('test-entity/add/test-bundle');
1682
    $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is displayed.');
1683
    $edit = array(
1684
      "{$this->field_name}[$langcode][]" => array($term1->tid, $term2->tid),
1685
    );
1686
    $this->drupalPost(NULL, $edit, t('Save'));
1687
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
1688
    $id = $match[1];
1689
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');
1690

    
1691
    // Render the entity.
1692
    $entity = field_test_entity_test_load($id);
1693
    $entities = array($id => $entity);
1694
    field_attach_prepare_view('test_entity', $entities, 'full');
1695
    $entity->content = field_attach_view('test_entity', $entity, 'full');
1696
    $this->content = drupal_render($entity->content);
1697
    $this->assertText($term1->name, 'Term 1 name is displayed.');
1698
    $this->assertText($term2->name, 'Term 2 name is displayed.');
1699

    
1700
    // Delete vocabulary 2.
1701
    taxonomy_vocabulary_delete($this->vocabulary2->vid);
1702

    
1703
    // Re-render the content.
1704
    $entity = field_test_entity_test_load($id);
1705
    $entities = array($id => $entity);
1706
    field_attach_prepare_view('test_entity', $entities, 'full');
1707
    $entity->content = field_attach_view('test_entity', $entity, 'full');
1708
    $this->plainTextContent = FALSE;
1709
    $this->content = drupal_render($entity->content);
1710

    
1711
    // Term 1 should still be displayed; term 2 should not be.
1712
    $this->assertText($term1->name, 'Term 1 name is displayed.');
1713
    $this->assertNoText($term2->name, 'Term 2 name is not displayed.');
1714

    
1715
    // Verify that field and instance settings are correct.
1716
    $field_info = field_info_field($this->field_name);
1717
    $this->assertEqual(sizeof($field_info['settings']['allowed_values']), 1, 'Only one vocabulary is allowed for the field.');
1718

    
1719
    // The widget should still be displayed.
1720
    $this->drupalGet('test-entity/add/test-bundle');
1721
    $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is still displayed.');
1722

    
1723
    // Term 1 should still pass validation.
1724
    $edit = array(
1725
      "{$this->field_name}[$langcode][]" => array($term1->tid),
1726
    );
1727
    $this->drupalPost(NULL, $edit, t('Save'));
1728
  }
1729

    
1730
}
1731

    
1732
/**
1733
 * Test taxonomy token replacement in strings.
1734
 */
1735
class TaxonomyTokenReplaceTestCase extends TaxonomyWebTestCase {
1736

    
1737
  public static function getInfo() {
1738
    return array(
1739
      'name' => 'Taxonomy token replacement',
1740
      'description' => 'Generates text using placeholders for dummy content to check taxonomy token replacement.',
1741
      'group' => 'Taxonomy',
1742
    );
1743
  }
1744

    
1745
  function setUp() {
1746
    parent::setUp();
1747
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
1748
    $this->drupalLogin($this->admin_user);
1749
    $this->vocabulary = $this->createVocabulary();
1750
    $this->langcode = LANGUAGE_NONE;
1751

    
1752
    $field = array(
1753
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
1754
      'type' => 'taxonomy_term_reference',
1755
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1756
      'settings' => array(
1757
        'allowed_values' => array(
1758
          array(
1759
            'vocabulary' => $this->vocabulary->machine_name,
1760
            'parent' => 0,
1761
          ),
1762
        ),
1763
      ),
1764
    );
1765
    field_create_field($field);
1766

    
1767
    $this->instance = array(
1768
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
1769
      'bundle' => 'article',
1770
      'entity_type' => 'node',
1771
      'widget' => array(
1772
        'type' => 'options_select',
1773
      ),
1774
      'display' => array(
1775
        'default' => array(
1776
          'type' => 'taxonomy_term_reference_link',
1777
        ),
1778
      ),
1779
    );
1780
    field_create_instance($this->instance);
1781
  }
1782

    
1783
  /**
1784
   * Creates some terms and a node, then tests the tokens generated from them.
1785
   */
1786
  function testTaxonomyTokenReplacement() {
1787
    global $language;
1788

    
1789
    // Create two taxonomy terms.
1790
    $term1 = $this->createTerm($this->vocabulary);
1791
    $term2 = $this->createTerm($this->vocabulary);
1792

    
1793
    // Edit $term2, setting $term1 as parent.
1794
    $edit = array();
1795
    $edit['name'] = '<blink>Blinking Text</blink>';
1796
    $edit['parent[]'] = array($term1->tid);
1797
    $this->drupalPost('taxonomy/term/' . $term2->tid . '/edit', $edit, t('Save'));
1798

    
1799
    // Create node with term2.
1800
    $edit = array();
1801
    $node = $this->drupalCreateNode(array('type' => 'article'));
1802
    $edit[$this->instance['field_name'] . '[' . $this->langcode . '][]'] = $term2->tid;
1803
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
1804

    
1805
    // Generate and test sanitized tokens for term1.
1806
    $tests = array();
1807
    $tests['[term:tid]'] = $term1->tid;
1808
    $tests['[term:name]'] = check_plain($term1->name);
1809
    $tests['[term:description]'] = check_markup($term1->description, $term1->format);
1810
    $tests['[term:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
1811
    $tests['[term:node-count]'] = 0;
1812
    $tests['[term:parent:name]'] = '[term:parent:name]';
1813
    $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);
1814

    
1815
    foreach ($tests as $input => $expected) {
1816
      $output = token_replace($input, array('term' => $term1), array('language' => $language));
1817
      $this->assertEqual($output, $expected, format_string('Sanitized taxonomy term token %token replaced.', array('%token' => $input)));
1818
    }
1819

    
1820
    // Generate and test sanitized tokens for term2.
1821
    $tests = array();
1822
    $tests['[term:tid]'] = $term2->tid;
1823
    $tests['[term:name]'] = check_plain($term2->name);
1824
    $tests['[term:description]'] = check_markup($term2->description, $term2->format);
1825
    $tests['[term:url]'] = url('taxonomy/term/' . $term2->tid, array('absolute' => TRUE));
1826
    $tests['[term:node-count]'] = 1;
1827
    $tests['[term:parent:name]'] = check_plain($term1->name);
1828
    $tests['[term:parent:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
1829
    $tests['[term:parent:parent:name]'] = '[term:parent:parent:name]';
1830
    $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);
1831

    
1832
    // Test to make sure that we generated something for each token.
1833
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
1834

    
1835
    foreach ($tests as $input => $expected) {
1836
      $output = token_replace($input, array('term' => $term2), array('language' => $language));
1837
      $this->assertEqual($output, $expected, format_string('Sanitized taxonomy term token %token replaced.', array('%token' => $input)));
1838
    }
1839

    
1840
    // Generate and test unsanitized tokens.
1841
    $tests['[term:name]'] = $term2->name;
1842
    $tests['[term:description]'] = $term2->description;
1843
    $tests['[term:parent:name]'] = $term1->name;
1844
    $tests['[term:vocabulary:name]'] = $this->vocabulary->name;
1845

    
1846
    foreach ($tests as $input => $expected) {
1847
      $output = token_replace($input, array('term' => $term2), array('language' => $language, 'sanitize' => FALSE));
1848
      $this->assertEqual($output, $expected, format_string('Unsanitized taxonomy term token %token replaced.', array('%token' => $input)));
1849
    }
1850

    
1851
    // Generate and test sanitized tokens.
1852
    $tests = array();
1853
    $tests['[vocabulary:vid]'] = $this->vocabulary->vid;
1854
    $tests['[vocabulary:name]'] = check_plain($this->vocabulary->name);
1855
    $tests['[vocabulary:description]'] = filter_xss($this->vocabulary->description);
1856
    $tests['[vocabulary:node-count]'] = 1;
1857
    $tests['[vocabulary:term-count]'] = 2;
1858

    
1859
    // Test to make sure that we generated something for each token.
1860
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
1861

    
1862
    foreach ($tests as $input => $expected) {
1863
      $output = token_replace($input, array('vocabulary' => $this->vocabulary), array('language' => $language));
1864
      $this->assertEqual($output, $expected, format_string('Sanitized taxonomy vocabulary token %token replaced.', array('%token' => $input)));
1865
    }
1866

    
1867
    // Generate and test unsanitized tokens.
1868
    $tests['[vocabulary:name]'] = $this->vocabulary->name;
1869
    $tests['[vocabulary:description]'] = $this->vocabulary->description;
1870

    
1871
    foreach ($tests as $input => $expected) {
1872
      $output = token_replace($input, array('vocabulary' => $this->vocabulary), array('language' => $language, 'sanitize' => FALSE));
1873
      $this->assertEqual($output, $expected, format_string('Unsanitized taxonomy vocabulary token %token replaced.', array('%token' => $input)));
1874
    }
1875
  }
1876

    
1877
}
1878

    
1879
/**
1880
 * Tests for verifying that taxonomy pages use the correct theme.
1881
 */
1882
class TaxonomyThemeTestCase extends TaxonomyWebTestCase {
1883

    
1884
  public static function getInfo() {
1885
    return array(
1886
      'name' => 'Taxonomy theme switching',
1887
      'description' => 'Verifies that various taxonomy pages use the expected theme.',
1888
      'group' => 'Taxonomy',
1889
    );
1890
  }
1891

    
1892
  function setUp() {
1893
    parent::setUp();
1894

    
1895
    // Make sure we are using distinct default and administrative themes for
1896
    // the duration of these tests.
1897
    variable_set('theme_default', 'bartik');
1898
    variable_set('admin_theme', 'seven');
1899

    
1900
    // Create and log in as a user who has permission to add and edit taxonomy
1901
    // terms and view the administrative theme.
1902
    $admin_user = $this->drupalCreateUser(array('administer taxonomy', 'view the administration theme'));
1903
    $this->drupalLogin($admin_user);
1904
  }
1905

    
1906
  /**
1907
   * Test the theme used when adding, viewing and editing taxonomy terms.
1908
   */
1909
  function testTaxonomyTermThemes() {
1910
    // Adding a term to a vocabulary is considered an administrative action and
1911
    // should use the administrative theme.
1912
    $vocabulary = $this->createVocabulary();
1913
    $this->drupalGet('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add');
1914
    $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for adding a taxonomy term.");
1915

    
1916
    // Viewing a taxonomy term should use the default theme.
1917
    $term = $this->createTerm($vocabulary);
1918
    $this->drupalGet('taxonomy/term/' . $term->tid);
1919
    $this->assertRaw('bartik/css/style.css', "The default theme's CSS appears on the page for viewing a taxonomy term.");
1920

    
1921
    // Editing a taxonomy term should use the same theme as adding one.
1922
    $this->drupalGet('taxonomy/term/' . $term->tid . '/edit');
1923
    $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for editing a taxonomy term.");
1924
  }
1925

    
1926
}
1927

    
1928
/**
1929
 * Tests the functionality of EntityFieldQuery for taxonomy entities.
1930
 */
1931
class TaxonomyEFQTestCase extends TaxonomyWebTestCase {
1932
  public static function getInfo() {
1933
    return array(
1934
      'name' => 'Taxonomy EntityFieldQuery',
1935
      'description' => 'Verifies operation of a taxonomy-based EntityFieldQuery.',
1936
      'group' => 'Taxonomy',
1937
    );
1938
  }
1939

    
1940
  function setUp() {
1941
    parent::setUp();
1942
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
1943
    $this->drupalLogin($this->admin_user);
1944
    $this->vocabulary = $this->createVocabulary();
1945
  }
1946

    
1947
  /**
1948
   * Tests that a basic taxonomy EntityFieldQuery works.
1949
   */
1950
  function testTaxonomyEFQ() {
1951
    $terms = array();
1952
    for ($i = 0; $i < 5; $i++) {
1953
      $term = $this->createTerm($this->vocabulary);
1954
      $terms[$term->tid] = $term;
1955
    }
1956
    $query = new EntityFieldQuery();
1957
    $query->entityCondition('entity_type', 'taxonomy_term');
1958
    $result = $query->execute();
1959
    $result = $result['taxonomy_term'];
1960
    asort($result);
1961
    $this->assertEqual(array_keys($terms), array_keys($result), 'Taxonomy terms were retrieved by EntityFieldQuery.');
1962

    
1963
    // Create a second vocabulary and five more terms.
1964
    $vocabulary2 = $this->createVocabulary();
1965
    $terms2 = array();
1966
    for ($i = 0; $i < 5; $i++) {
1967
      $term = $this->createTerm($vocabulary2);
1968
      $terms2[$term->tid] = $term;
1969
    }
1970

    
1971
    $query = new EntityFieldQuery();
1972
    $query->entityCondition('entity_type', 'taxonomy_term');
1973
    $query->entityCondition('bundle', $vocabulary2->machine_name);
1974
    $result = $query->execute();
1975
    $result = $result['taxonomy_term'];
1976
    asort($result);
1977
    $this->assertEqual(array_keys($terms2), array_keys($result), format_string('Taxonomy terms from the %name vocabulary were retrieved by EntityFieldQuery.', array('%name' => $vocabulary2->name)));
1978
  }
1979

    
1980
}