Newer
Older

Dries Buytaert
committed
<?php

Lee Rowlands
committed
declare(strict_types=1);

Dries Buytaert
committed
namespace Drupal\Tests;
use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Component\Utility\NestedArray;

catch
committed
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;

Angie Byron
committed
use Drupal\Core\DependencyInjection\ContainerBuilder;

Alex Bronstein
committed
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
use Drupal\TestTools\Extension\DeprecationBridge\ExpectDeprecationTrait;

Alex Pott
committed
use Drupal\TestTools\TestVarDumper;

Alex Pott
committed
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;

Alex Pott
committed
use Symfony\Component\VarDumper\VarDumper;

Alex Pott
committed
/**
* Provides a base class and helpers for Drupal unit tests.

Angie Byron
committed
*
* Module tests extending UnitTestCase must exist in the
* Drupal\Tests\your_module\Unit namespace and live in the
* modules/your_module/tests/src/Unit directory.
*
* Tests for core/lib/Drupal classes extending UnitTestCase must exist in the
* \Drupal\Tests\Core namespace and live in the core/lib/tests/Drupal/Tests/Core
* directory.

Théodore Biadala
committed
*
* Using Symfony's dump() function in Unit tests will produce output on the

Alex Pott
committed
* command line.
*

Angie Byron
committed
* @ingroup testing

Alex Pott
committed
*/

Alex Pott
committed
abstract class UnitTestCase extends TestCase {
use PhpUnitCompatibilityTrait;
use ProphecyTrait;
use ExpectDeprecationTrait;
use RandomGeneratorTrait;

Dries Buytaert
committed
/**
* The app root.
*
* @var string
*/
protected $root;

Alex Pott
committed
/**
* {@inheritdoc}
*/
public static function setUpBeforeClass(): void {

Alex Pott
committed
parent::setUpBeforeClass();
VarDumper::setHandler(TestVarDumper::class . '::cliHandler');
}

Angie Byron
committed
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Ensure that an instantiated container in the global state of \Drupal from
// a previous test does not leak into this test.

Alex Pott
committed
\Drupal::unsetContainer();
// Ensure that the NullFileCache implementation is used for the FileCache as
// unit tests should not be relying on caches implicitly.
FileCacheFactory::setConfiguration([FileCacheFactory::DISABLE_CACHE => TRUE]);

Alex Pott
committed
// Ensure that FileCacheFactory has a prefix.
FileCacheFactory::setPrefix('prefix');
$this->root = dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)), 2);
chdir($this->root);

Angie Byron
committed
}
/**
* Returns a stub config factory that behaves according to the passed array.
*
* Use this to generate a config factory that will return the desired values
* for the given config names.
*
* @param array $configs
* An associative array of configuration settings whose keys are
* configuration object names and whose values are key => value arrays for
* the configuration object in question. Defaults to an empty array.

catch
committed
* @return \PHPUnit\Framework\MockObject\MockObject|\Drupal\Core\Config\ConfigFactoryInterface
* A mock configuration factory object.
*/
public function getConfigFactoryStub(array $configs = []) {
$config_get_map = [];
$config_editable_map = [];
// Construct the desired configuration object stubs, each with its own
// desired return map.
foreach ($configs as $config_name => $config_values) {
// Define a closure over the $config_values, which will be used as a
// returnCallback below. This function will mimic
// \Drupal\Core\Config\Config::get and allow using dotted keys.
$config_get = function ($key = '') use ($config_values) {
// Allow to pass in no argument.
if (empty($key)) {
return $config_values;
}
// See if we have the key as is.
if (isset($config_values[$key])) {
return $config_values[$key];
}
$parts = explode('.', $key);
$value = NestedArray::getValue($config_values, $parts, $key_exists);
return $key_exists ? $value : NULL;
};

Alex Pott
committed
$immutable_config_object = $this->getMockBuilder('Drupal\Core\Config\ImmutableConfig')
->disableOriginalConstructor()
->getMock();
$immutable_config_object->expects($this->any())
->method('get')
->willReturnCallback($config_get);
$config_get_map[] = [$config_name, $immutable_config_object];

Alex Pott
committed
$mutable_config_object = $this->getMockBuilder('Drupal\Core\Config\Config')
->disableOriginalConstructor()
->getMock();
$mutable_config_object->expects($this->any())
->method('get')
->willReturnCallback($config_get);
$config_editable_map[] = [$config_name, $mutable_config_object];
}
// Construct a config factory with the array of configuration object stubs
// as its return map.

Lee Rowlands
committed
$config_factory = $this->createMock('Drupal\Core\Config\ConfigFactoryInterface');
$config_factory->expects($this->any())
->method('get')
->willReturnMap($config_get_map);
$config_factory->expects($this->any())
->method('getEditable')
->willReturnMap($config_editable_map);
return $config_factory;
}

Alex Pott
committed

Alex Pott
committed
/**
* Returns a stub translation manager that just returns the passed string.
*
* @return \PHPUnit\Framework\MockObject\MockObject|\Drupal\Core\StringTranslation\TranslationInterface
* A mock translation object.

Alex Pott
committed
*/
public function getStringTranslationStub() {

Lee Rowlands
committed
$translation = $this->createMock('Drupal\Core\StringTranslation\TranslationInterface');

Alex Pott
committed
$translation->expects($this->any())
->method('translate')
->willReturnCallback(function ($string, array $args = [], array $options = []) use ($translation) {
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString

Alex Bronstein
committed
return new TranslatableMarkup($string, $args, $options, $translation);

Alex Bronstein
committed
});
$translation->expects($this->any())
->method('translateString')

Alex Bronstein
committed
->willReturnCallback(function (TranslatableMarkup $wrapper) {

Alex Bronstein
committed
return $wrapper->getUntranslatedString();
});
$translation->expects($this->any())
->method('formatPlural')
->willReturnCallback(function ($count, $singular, $plural, array $args = [], array $options = []) use ($translation) {

Alex Bronstein
committed
$wrapper = new PluralTranslatableMarkup($count, $singular, $plural, $args, $options, $translation);
});

Alex Pott
committed
return $translation;
}
/**

catch
committed
* Sets up a container with a cache tags invalidator.
*

catch
committed
* @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_validator
* The cache tags invalidator.
*
* @return \Symfony\Component\DependencyInjection\ContainerInterface|\PHPUnit\Framework\MockObject\MockObject

catch
committed
* The container with the cache tags invalidator service.
*/

catch
committed
protected function getContainerWithCacheTagsInvalidator(CacheTagsInvalidatorInterface $cache_tags_validator) {

Lee Rowlands
committed
$container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->any())
->method('get')

catch
committed
->with('cache_tags.invalidator')

Alex Pott
committed
->willReturn($cache_tags_validator);
\Drupal::setContainer($container);
return $container;
}

Alex Pott
committed
/**
* Returns a stub class resolver.
*
* @return \Drupal\Core\DependencyInjection\ClassResolverInterface|\PHPUnit\Framework\MockObject\MockObject

Alex Pott
committed
* The class resolver stub.
*/
protected function getClassResolverStub() {

Lee Rowlands
committed
$class_resolver = $this->createMock('Drupal\Core\DependencyInjection\ClassResolverInterface');

Alex Pott
committed
$class_resolver->expects($this->any())
->method('getInstanceFromDefinition')
->willReturnCallback(function ($class) {

Alex Pott
committed
if (is_subclass_of($class, 'Drupal\Core\DependencyInjection\ContainerInjectionInterface')) {
return $class::create(new ContainerBuilder());

Alex Pott
committed
}
else {
return new $class();
}

Alex Pott
committed
return $class_resolver;
}