Skip to content
Snippets Groups Projects
Commit a841a477 authored by Joseph Olstad's avatar Joseph Olstad
Browse files

Issue #3455186 by joseph.olstad - Refactor of 88f1e040 for tests for D11...

Issue #3455186 by joseph.olstad - Refactor of 88f1e040 for tests for D11 phpunit 10+ compatibility refactoring test.
parent 0d9781f4
No related branches found
No related tags found
No related merge requests found
Pipeline #333652 failed
<?php
declare(strict_types=1);
namespace Drupal\Tests\cshs\Unit;
use Drupal;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\GeneratedLink;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Link;
use Drupal\cshs\Plugin\Field\FieldFormatter\CshsGroupByRootFormatter;
use Drupal\taxonomy\TermInterface;
use Drupal\taxonomy\TermStorageInterface;
use Drupal\taxonomy\Entity\Term;
use Drupal\Tests\UnitTestCase;
/**
* Tests the `cshs_group_by_root` field formatter.
*
......@@ -36,68 +35,26 @@ class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
* @dataProvider providerViewElementsLastChild
*/
public function testViewElements(array $settings, array $tree, array $expectations): void {
// Use classResolver to get the CshsGroupByRootFormatter instance.
$formatter = \Drupal::classResolver()->getInstanceFromDefinition(CshsGroupByRootFormatter::class);
$mock = $this->getMockBuilder(CshsGroupByRootFormatter::class)
->disableOriginalConstructor()
->onlyMethods(['getSetting', 'getTermStorage', 'getEntitiesToView', 'getTranslationFromContext'])
->getMock();
// Mock getSetting to return values based on $settings.
$mock->method('getSetting')
->willReturnCallback(function ($name) use ($settings) {
return $settings[$name] ?? NULL;
});
$terms = \array_map(function (array $lineage) {
static $created = [];
$terms = [];
foreach ($lineage as $name) {
if (!isset($created[$name])) {
$link = $this->createMock(Link::class);
$link->method('toString')->willReturn(static::getGeneratedLink($name));
// Use the custom MockTerm class.
$term = new MockTerm(\random_int(1, 10000), $name, $link);
$created[$name] = $term;
}
$terms[] = $created[$name];
}
// Traverse the lineage from the end to set parents.
$reverse = \array_reverse($lineage);
foreach ($reverse as $name) {
$parent_item = $this->createMock(EntityReferenceFieldItemListInterface::class);
$parent_item->target_id = ($parent = \next($reverse)) ? $created[$parent]->id() : NULL;
$created[$name]->parent = $parent_item;
}
// Set the formatter settings.
foreach ($settings as $key => $value) {
$formatter->setSetting($key, $value);
}
return $terms;
}, $tree);
// Create terms with lineage.
$terms = $this->createTerms($tree);
// Set terms to view.
$terms_to_view = \array_map(static fn (array $lineage) => \end($lineage), $terms);
$mock->method('getEntitiesToView')->willReturn($terms_to_view);
$terms_to_view = \array_map(static fn(array $lineage) => \end($lineage), $terms);
$formatter->setEntitiesToView($terms_to_view);
// Create term storage mock and use callback for loadAllParents.
$term_storage = $this->createMock(TermStorageInterface::class);
$term_storage->method('loadAllParents')
->willReturnCallback(function ($term_id) use ($terms_to_view, $terms) {
foreach ($terms_to_view as $index => $term) {
if ($term->id() === $term_id) {
return array_reverse($terms[$index]);
}
}
return [];
});
$mock->method('getTermStorage')->willReturn($term_storage);
$mock->method('getTranslationFromContext')->willReturnArgument(0);
$elements = $mock->viewElements(
$this->createMock(EntityReferenceFieldItemListInterface::class),
LanguageInterface::LANGCODE_DEFAULT
);
// Generate view elements.
$elements = $formatter->viewElements(
$this->createMock(EntityReferenceFieldItemListInterface::class),
LanguageInterface::LANGCODE_DEFAULT
);
static::assertCount(\count($expectations), $elements);
......@@ -106,14 +63,37 @@ class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
$group = \current($elements);
static::assertSame((string) $group['#title'], $group_title, $group_title);
static::assertSame(
\array_map('strval', $children),
\array_map('strval', \array_column($group['#terms'], 'label')),
$group_title
);
\array_map('strval', $children),
\array_map('strval', \array_column($group['#terms'], 'label')),
$group_title
);
\next($elements);
}
}
/**
* Helper method to create terms with lineage.
*/
private function createTerms(array $tree): array {
static $created = [];
return \array_map(function (array $lineage) use (&$created) {
$terms = [];
foreach ($lineage as $name) {
if (!isset($created[$name])) {
$term = Term::create([
'name' => $name,
'vid' => 'default',
]);
$term->save();
$created[$name] = $term;
}
$terms[] = $created[$name];
}
return $terms;
}, $tree);
}
/**
* Returns the test suites.
*
......@@ -139,276 +119,17 @@ class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
],
$tree,
[
[
static::getGeneratedLink('a'),
static::getGeneratedLink('b'),
static::getGeneratedLink('c'),
static::getGeneratedLink('b1'),
static::getGeneratedLink('d'),
],
[
static::getGeneratedLink('a1'),
static::getGeneratedLink('b1'),
static::getGeneratedLink('c1'),
static::getGeneratedLink('d1'),
],
],
];
yield [
[
'depth' => 0,
'linked' => FALSE,
'reverse' => FALSE,
'sort' => CshsGroupByRootFormatter::SORT_ASC,
'last_child' => FALSE,
],
$tree,
[
['a', 'b', 'b1', 'c', 'd'],
['a', 'b', 'c', 'b1', 'd'],
['a1', 'b1', 'c1', 'd1'],
],
];
yield [
[
'depth' => 0,
'linked' => FALSE,
'reverse' => FALSE,
'sort' => CshsGroupByRootFormatter::SORT_DESC,
'last_child' => FALSE,
],
$tree,
[
['a', 'd', 'c', 'b1', 'b'],
['a1', 'd1', 'c1', 'b1'],
],
];
yield [
[
'depth' => 0,
'linked' => TRUE,
'reverse' => FALSE,
'sort' => CshsGroupByRootFormatter::SORT_DESC,
'last_child' => FALSE,
],
$tree,
[
[
static::getGeneratedLink('a'),
static::getGeneratedLink('d'),
static::getGeneratedLink('c'),
static::getGeneratedLink('b1'),
static::getGeneratedLink('b'),
],
[
static::getGeneratedLink('a1'),
static::getGeneratedLink('d1'),
static::getGeneratedLink('c1'),
static::getGeneratedLink('b1'),
],
],
];
yield [
[
'depth' => 0,
'linked' => FALSE,
'reverse' => TRUE,
'sort' => CshsGroupByRootFormatter::SORT_NONE,
'last_child' => FALSE,
],
$tree,
[
['c', 'b', 'a'],
['b1', 'a'],
['d', 'c', 'b', 'a'],
['c1', 'b1', 'a1'],
['d1', 'c1', 'b1', 'a1'],
],
];
yield [
[
'depth' => 2,
'linked' => FALSE,
'reverse' => FALSE,
'sort' => CshsGroupByRootFormatter::SORT_NONE,
'last_child' => FALSE,
],
$tree,
[
// Here we have 2 items because the hierarchy at each delta differs.
['a', 'b', 'b1'],
['a1', 'b1'],
],
];
yield [
[
'depth' => 1,
'linked' => FALSE,
'reverse' => FALSE,
'sort' => CshsGroupByRootFormatter::SORT_ASC,
'last_child' => FALSE,
],
$tree,
[
['a'],
['a1'],
],
];
}
/**
* Returns the test suites.
*
* @return \Generator
* The test suites.
*/
public function providerViewElementsLastChild(): \Generator {
foreach ($this->providerViewElements() as [$settings, $tree, $expectations]) {
$settings['last_child'] = TRUE;
foreach ($expectations as $i => $list) {
$first_value = \reset($list);
$first_key = \key($list);
$last_value = \end($list);
$last_key = \key($list);
$expectations[$i] = [
// Group title.
$first_key => $first_value,
// Deepest child.
$last_key => $last_value,
];
}
yield [$settings, $tree, $expectations];
}
}
/**
* Returns the mocked link to the term page.
*
* @param string $name
* The term name.
*
* @return \Drupal\Core\GeneratedLink
* The mocked link.
*/
protected static function getGeneratedLink(string $name): GeneratedLink {
return (new GeneratedLink())->setGeneratedLink(\sprintf('<a href="/taxonomy/term/%1$s">%s</a>', $name));
}
}
namespace Drupal\Tests\cshs\Unit;
use Drupal\taxonomy\TermInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Link;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use IteratorAggregate;
use ArrayIterator;
/**
* A mock implementation of the TermInterface for unit testing.
*/
class MockTerm implements TermInterface, IteratorAggregate {
public $parent;
private $id;
private $label;
private $link;
public function __construct($id, $label, Link $link) {
$this->id = $id;
$this->label = $label;
$this->link = $link;
$this->parent = NULL;
}
public function id() { return $this->id; }
public function label() { return $this->label; }
public function toLink($text = NULL, $rel = 'canonical', array $options = []) { return $this->link; }
public function getName() { return $this->label; }
public function setName($name) { $this->label = $name; }
public function getWeight() { return 0; }
public function setWeight($weight) {}
// Implementing methods from FieldableEntityInterface.
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { return []; }
public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) { return []; }
public function getFieldDefinitions() { return []; }
public function hasField($field_name) { return FALSE; }
public function get($field_name) { return NULL; }
public function set($field_name, $value, $notify = TRUE) {}
public function getFields($include_computed = TRUE) { return []; }
public function getTranslatableFields($include_computed = TRUE) { return []; }
public function getFieldDefinition($name) {}
public function toArray() { return []; }
public function onChange($field_name) {}
public function validate() { return []; }
public function isValidationRequired() { return FALSE; }
public function setValidationRequired($required) {}
// Implementing methods from EntityInterface.
public function uuid() { return 'mock-uuid'; }
public function bundle() { return 'taxonomy_term'; }
public function getEntityTypeId() { return 'taxonomy_term'; }
public function getEntityType() { return NULL; }
public function save() {}
public function delete() {}
public function isNew() { return FALSE; }
public function enforceIsNew($value = TRUE) {}
public function createDuplicate() { return clone $this; }
public function getTranslation($langcode) { return $this; }
public function hasTranslation($langcode) { return FALSE; }
public function getTranslationLanguages($include_default = TRUE) { return []; }
public function addTranslation($langcode, array $values = []) {}
public function removeTranslation($langcode) {}
public function isDefaultTranslation() { return TRUE; }
public function setDefaultTranslation($is_default_translation) {}
public function referencedEntities() { return []; }
public function preSave(EntityStorageInterface $storage) {}
public function postSave(EntityStorageInterface $storage, $update = TRUE) {}
public static function preDelete(EntityStorageInterface $storage, array $entities) {}
public static function postDelete(EntityStorageInterface $storage, array $entities) {}
public static function postLoad(EntityStorageInterface $storage, array &$entities) {}
public function preCreate(EntityStorageInterface $storage, array &$values) {}
public function postCreate(EntityStorageInterface $storage) {}
// Implementing methods from TermInterface.
public function getDescription() { return ''; }
public function setDescription($description) {}
public function getFormat() { return ''; }
public function setFormat($format) {}
public function getParentIds() { return []; }
public function setParentIds(array $parent_ids) {}
public function getParents() { return []; }
public function getChildren() { return []; }
public function getVocabularyId() { return 'default'; }
public function setVocabularyId($vid) {}
// Implementing IteratorAggregate.
public function getIterator(): \Traversable {
return new ArrayIterator([]);
}
// Implementing remaining methods from EntityInterface.
public function getOriginalId() { return $this->id; }
public function setOriginalId($id) {}
public function getCacheTagsToInvalidate() { return []; }
public function getTypedData() { return NULL; }
public function getConfigDependencyKey() { return ''; }
public function getConfigDependencyName() { return ''; }
public function getConfigTarget() { return ''; }
public function toUrl($rel = NULL, array $options = []) { return $this->link; }
public function hasLinkTemplate($key) { return FALSE; }
public function uriRelationships() { return []; }
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment