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

Issue #3455186 by cmlara, joseph.olstad - Refactor tests for D11 phpunit 10+...

Issue #3455186 by cmlara, joseph.olstad - Refactor tests for D11 phpunit 10+ compatibility refactoring test.
parent bb3e0e3f
No related branches found
No related tags found
No related merge requests found
Pipeline #333301 failed
......@@ -4,12 +4,11 @@ declare(strict_types=1);
namespace Drupal\Tests\cshs\Unit;
use Drupal\Core\Entity\ContentEntityInterface;
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\Entity\Term;
use Drupal\taxonomy\TermInterface;
use Drupal\taxonomy\TermStorageInterface;
use Drupal\Tests\UnitTestCase;
......@@ -22,11 +21,6 @@ use Drupal\Tests\UnitTestCase;
*/
class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
/**
* Define parent relationships as a class property.
*/
protected array $parentRelationships = [];
/**
* Test the `viewElements()` logic.
*
......@@ -41,158 +35,97 @@ class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
* @dataProvider providerViewElementsLastChild
*/
public function testViewElements(array $settings, array $tree, array $expectations): void {
$mock = $this->getMockBuilder(CshsGroupByRootFormatter::class)
->disableOriginalConstructor()
->onlyMethods(['getSetting', 'getTermStorage', 'getEntitiesToView', 'getTranslationFromContext'])
->getMock();
$mock->method('getSetting')->willReturnCallback(fn($key) => $settings[$key] ?? NULL);
$terms = $this->createTerms($tree);
$terms_to_view = array_map(static fn (array $lineage): TermInterface => end($lineage), $terms);
$mock->expects($this->once())->method('getEntitiesToView')->willReturn($terms_to_view);
$term_storage = $this->createMock(TermStorageInterface::class);
// Use class property `$this->parentRelationships` in the callback.
$term_storage->method('loadAllParents')
->willReturnCallback(function ($term_id) {
$parents = [];
while (isset($this->parentRelationships[$term_id])) {
$parent = $this->parentRelationships[$term_id];
/**
*
*/
public function testViewElements(array $settings, array $tree, array $expectations): void {
$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;
});
// Create terms with lineage.
$terms = \array_map(function (array $lineage) {
static $created = [];
$terms = [];
// Ensure $parent is a valid object before accessing its properties.
if ($parent === NULL || !is_object($parent) || !method_exists($parent, 'id')) {
break;
foreach ($lineage as $name) {
if (!isset($created[$name])) {
$link = $this->createMock(Link::class);
$link->method('toString')->willReturn(static::getGeneratedLink($name));
$created[$name] = $this->createMock(TermInterface::class);
$created[$name]->method('id')->willReturn(\random_int(1, 10000));
$created[$name]->method('label')->willReturn($name);
$created[$name]->method('toLink')->willReturn($link);
}
$parents[] = $parent;
$term_id = $parent->id();
$terms[] = $created[$name];
}
return array_reverse($parents);
});
$mock->method('getTermStorage')->willReturn($term_storage);
$mock->method('getTranslationFromContext')->willReturnArgument(0);
$elements = $mock->viewElements(
$this->createMock(EntityReferenceFieldItemListInterface::class),
LanguageInterface::LANGCODE_DEFAULT,
);
var_dump($elements);
// Enhanced assertion and debugging as before.
$this->assertCount(count($expectations), $elements);
foreach ($expectations as $expected_terms) {
$group_title = (string) array_shift($expected_terms);
$group = current($elements);
$this->assertSame((string) $group['#title'], $group_title);
$actual_labels = array_map(static fn($term) => (string) $term['label'], $group['#terms']);
$this->assertSame(array_values($actual_labels), array_values(array_map('strval', $expected_terms)));
next($elements);
}
}
/**
* Creates a partial mock term based on the provided parameters.
*
* @param int $id
* The term ID.
* @param string $label
* The term label.
* @param \Drupal\Core\Link $link
* The link object.
* @param string|null $parent
* The parent term ID (if any).
*
* @return object
* The stubbed term object.
*/
protected function createMockTerm(int $id, string $label, Link $link, $parent = NULL): ContentEntityInterface {
$term_mock = $this->getMockBuilder(\Drupal\taxonomy\Entity\Term::class)
->disableOriginalConstructor()
->onlyMethods([
'id',
'label',
'toLink',
'getFields',
'getFieldDefinition',
'getTranslatableFields',
'toArray',
'set',
'get',
'hasField',
'loadAllParents'
])
->getMock();
$term_mock->method('id')->willReturn($id);
$term_mock->method('label')->willReturn($label);
$term_mock->method('toLink')->willReturn($link);
$term_mock->method('getFields')->willReturn([]);
$term_mock->method('getFieldDefinition')->willReturn(NULL);
$term_mock->method('getTranslatableFields')->willReturn([]);
$term_mock->method('toArray')->willReturn([]);
$term_mock->method('set')->willReturnSelf();
$term_mock->method('get')->willReturn(NULL);
$term_mock->method('hasField')->willReturn(FALSE);
$term_mock->method('loadAllParents')->willReturn([]);
return $term_mock;
}
/**
* Creates mock terms based on a hierarchy tree and assigns parent IDs.
*
* @param array $tree
* Array representing term hierarchy.
*
* @return array[]
* Array of mock term hierarchies.
*/
protected function createTerms(array $tree): array {
$created = [];
$this->parentRelationships = [];
return array_map(function (array $lineage) use (&$created): array {
$terms = [];
foreach ($lineage as $name) {
if (!isset($created[$name])) {
$link = $this->createMock(Link::class);
$link->method('toString')->willReturn(static::getGeneratedLink($name));
// Use the updated createMockTerm method.
$term_id = $this->getFixedTermId($name);
$term = $this->createMockTerm($term_id, $name, $link);
// Store the created term.
$created[$name] = $term;
// Assign parents in reverse order.
$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;
}
$terms[] = $created[$name];
}
// Establish parent relationships.
$previous = NULL;
foreach (array_reverse($terms) as $term) {
if ($previous) {
$this->parentRelationships[$previous->id()] = $term;
$previous->parent = $term;
}
$previous = $term;
return $terms;
}, $tree);
// Set terms to view.
$terms_to_view = \array_map(static fn (array $lineage) => \end($lineage), $terms);
$mock->method('getEntitiesToView')->willReturn($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
);
static::assertCount(\count($expectations), $elements);
foreach ($expectations as $children) {
$group_title = (string) \array_shift($children);
$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
);
\next($elements);
}
}
return $terms;
}, $tree);
}
/**
* Provides base test data for view elements.
* Returns the test suites.
*
* @return \Generator
* The test data.
* The test suites.
*/
public function providerViewElements(): \Generator {
$tree = [
......@@ -204,20 +137,142 @@ class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
];
yield [
['depth' => 0, 'linked' => TRUE, 'reverse' => FALSE, 'sort' => CshsGroupByRootFormatter::SORT_NONE, 'last_child' => FALSE],
[
'depth' => 0,
'linked' => TRUE,
'reverse' => FALSE,
'sort' => CshsGroupByRootFormatter::SORT_NONE,
'last_child' => FALSE,
],
$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'],
['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,
[
[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')],
['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'],
],
];
}
/**
* Provides modified test data for view elements with the `last_child` setting.
* Returns the test suites.
*
* @return \Generator
* The test data with `last_child` set to TRUE.
* The test suites.
*/
public function providerViewElementsLastChild(): \Generator {
foreach ($this->providerViewElements() as [$settings, $tree, $expectations]) {
......@@ -225,11 +280,15 @@ class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
foreach ($expectations as $i => $list) {
$first_value = \reset($list);
$first_key = \key($list);
$last_value = \end($list);
$last_key = \key($list);
$expectations[$i] = [
$first_value,
$last_value,
// Group title.
$first_key => $first_value,
// Deepest child.
$last_key => $last_value,
];
}
......@@ -238,39 +297,16 @@ class CshsGroupByRootFormatterUnitTest extends UnitTestCase {
}
/**
* Returns a generated link string.
* Returns the mocked link to the term page.
*
* @param string $name
* The term name.
*
* @return string
* @return \Drupal\Core\GeneratedLink
* The mocked link.
*/
protected static function getGeneratedLink(string $name): string {
return sprintf('<a href="/taxonomy/term/%1$s">%s</a>', $name);
}
/**
* Returns a fixed ID for a term name.
*
* @param string $name
* The term name.
*
* @return int
* The Term Id.
*/
protected function getFixedTermId(string $name): int {
$ids = [
'a' => 123,
'b' => 456,
'c' => 789,
'd' => 1011,
'a1' => 2023,
'b1' => 3034,
'c1' => 4056,
'd1' => 5078,
];
return $ids[$name] ?? 0;
protected static function getGeneratedLink(string $name): GeneratedLink {
return (new GeneratedLink())->setGeneratedLink(\sprintf('<a href="/taxonomy/term/%1$s">%s</a>', $name));
}
}
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