PageRenderTime 25ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/web/core/tests/Drupal/Tests/UnitTestCase.php

https://gitlab.com/mohamed_hussein/prodt
PHP | 282 lines | 142 code | 23 blank | 117 comment | 5 complexity | e67128560cc7a4ceeb8ecce0eb5b531d MD5 | raw file
  1. <?php
  2. namespace Drupal\Tests;
  3. use Drupal\Component\FileCache\FileCacheFactory;
  4. use Drupal\Component\Utility\NestedArray;
  5. use Drupal\Component\Utility\Random;
  6. use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
  7. use Drupal\Core\DependencyInjection\ContainerBuilder;
  8. use Drupal\Core\StringTranslation\TranslatableMarkup;
  9. use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
  10. use Drupal\Tests\Traits\PhpUnitWarnings;
  11. use Drupal\TestTools\TestVarDumper;
  12. use PHPUnit\Framework\TestCase;
  13. use Symfony\Component\VarDumper\VarDumper;
  14. use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
  15. /**
  16. * Provides a base class and helpers for Drupal unit tests.
  17. *
  18. * Using Symfony's dump() function() in Unit tests will produce output on the
  19. * command line.
  20. *
  21. * @ingroup testing
  22. */
  23. abstract class UnitTestCase extends TestCase {
  24. use PhpUnitWarnings;
  25. use PhpUnitCompatibilityTrait;
  26. use ExpectDeprecationTrait;
  27. /**
  28. * The random generator.
  29. *
  30. * @var \Drupal\Component\Utility\Random
  31. */
  32. protected $randomGenerator;
  33. /**
  34. * The app root.
  35. *
  36. * @var string
  37. */
  38. protected $root;
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public static function setUpBeforeClass() {
  43. parent::setUpBeforeClass();
  44. VarDumper::setHandler(TestVarDumper::class . '::cliHandler');
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. protected function setUp() {
  50. parent::setUp();
  51. // Ensure that an instantiated container in the global state of \Drupal from
  52. // a previous test does not leak into this test.
  53. \Drupal::unsetContainer();
  54. // Ensure that the NullFileCache implementation is used for the FileCache as
  55. // unit tests should not be relying on caches implicitly.
  56. FileCacheFactory::setConfiguration([FileCacheFactory::DISABLE_CACHE => TRUE]);
  57. // Ensure that FileCacheFactory has a prefix.
  58. FileCacheFactory::setPrefix('prefix');
  59. $this->root = dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)), 2);
  60. }
  61. /**
  62. * Generates a unique random string containing letters and numbers.
  63. *
  64. * @param int $length
  65. * Length of random string to generate.
  66. *
  67. * @return string
  68. * Randomly generated unique string.
  69. *
  70. * @see \Drupal\Component\Utility\Random::name()
  71. */
  72. public function randomMachineName($length = 8) {
  73. return $this->getRandomGenerator()->name($length, TRUE);
  74. }
  75. /**
  76. * Gets the random generator for the utility methods.
  77. *
  78. * @return \Drupal\Component\Utility\Random
  79. * The random generator
  80. */
  81. protected function getRandomGenerator() {
  82. if (!is_object($this->randomGenerator)) {
  83. $this->randomGenerator = new Random();
  84. }
  85. return $this->randomGenerator;
  86. }
  87. /**
  88. * Asserts if two arrays are equal by sorting them first.
  89. *
  90. * @param array $expected
  91. * An expected results array.
  92. * @param array $actual
  93. * The actual array value.
  94. * @param string $message
  95. * An optional error message.
  96. *
  97. * @deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Use
  98. * ::assertEquals, ::assertEqualsCanonicalizing, or ::assertSame instead.
  99. *
  100. * @see https://www.drupal.org/node/3136304
  101. */
  102. protected function assertArrayEquals(array $expected, array $actual, $message = NULL) {
  103. @trigger_error(__METHOD__ . "() is deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Use ::assertEquals(), ::assertEqualsCanonicalizing(), or ::assertSame() instead. See https://www.drupal.org/node/3136304", E_USER_DEPRECATED);
  104. ksort($expected);
  105. ksort($actual);
  106. $this->assertEquals($expected, $actual, !empty($message) ? $message : '');
  107. }
  108. /**
  109. * Returns a stub config factory that behaves according to the passed array.
  110. *
  111. * Use this to generate a config factory that will return the desired values
  112. * for the given config names.
  113. *
  114. * @param array $configs
  115. * An associative array of configuration settings whose keys are
  116. * configuration object names and whose values are key => value arrays for
  117. * the configuration object in question. Defaults to an empty array.
  118. *
  119. * @return \PHPUnit\Framework\MockObject\MockBuilder
  120. * A MockBuilder object for the ConfigFactory with the desired return
  121. * values.
  122. */
  123. public function getConfigFactoryStub(array $configs = []) {
  124. $config_get_map = [];
  125. $config_editable_map = [];
  126. // Construct the desired configuration object stubs, each with its own
  127. // desired return map.
  128. foreach ($configs as $config_name => $config_values) {
  129. // Define a closure over the $config_values, which will be used as a
  130. // returnCallback below. This function will mimic
  131. // \Drupal\Core\Config\Config::get and allow using dotted keys.
  132. $config_get = function ($key = '') use ($config_values) {
  133. // Allow to pass in no argument.
  134. if (empty($key)) {
  135. return $config_values;
  136. }
  137. // See if we have the key as is.
  138. if (isset($config_values[$key])) {
  139. return $config_values[$key];
  140. }
  141. $parts = explode('.', $key);
  142. $value = NestedArray::getValue($config_values, $parts, $key_exists);
  143. return $key_exists ? $value : NULL;
  144. };
  145. $immutable_config_object = $this->getMockBuilder('Drupal\Core\Config\ImmutableConfig')
  146. ->disableOriginalConstructor()
  147. ->getMock();
  148. $immutable_config_object->expects($this->any())
  149. ->method('get')
  150. ->willReturnCallback($config_get);
  151. $config_get_map[] = [$config_name, $immutable_config_object];
  152. $mutable_config_object = $this->getMockBuilder('Drupal\Core\Config\Config')
  153. ->disableOriginalConstructor()
  154. ->getMock();
  155. $mutable_config_object->expects($this->any())
  156. ->method('get')
  157. ->willReturnCallback($config_get);
  158. $config_editable_map[] = [$config_name, $mutable_config_object];
  159. }
  160. // Construct a config factory with the array of configuration object stubs
  161. // as its return map.
  162. $config_factory = $this->createMock('Drupal\Core\Config\ConfigFactoryInterface');
  163. $config_factory->expects($this->any())
  164. ->method('get')
  165. ->willReturnMap($config_get_map);
  166. $config_factory->expects($this->any())
  167. ->method('getEditable')
  168. ->willReturnMap($config_editable_map);
  169. return $config_factory;
  170. }
  171. /**
  172. * Returns a stub config storage that returns the supplied configuration.
  173. *
  174. * @param array $configs
  175. * An associative array of configuration settings whose keys are
  176. * configuration object names and whose values are key => value arrays
  177. * for the configuration object in question.
  178. *
  179. * @return \Drupal\Core\Config\StorageInterface
  180. * A mocked config storage.
  181. */
  182. public function getConfigStorageStub(array $configs) {
  183. $config_storage = $this->createMock('Drupal\Core\Config\NullStorage');
  184. $config_storage->expects($this->any())
  185. ->method('listAll')
  186. ->will($this->returnValue(array_keys($configs)));
  187. foreach ($configs as $name => $config) {
  188. $config_storage->expects($this->any())
  189. ->method('read')
  190. ->with($this->equalTo($name))
  191. ->will($this->returnValue($config));
  192. }
  193. return $config_storage;
  194. }
  195. /**
  196. * Returns a stub translation manager that just returns the passed string.
  197. *
  198. * @return \PHPUnit\Framework\MockObject\MockObject|\Drupal\Core\StringTranslation\TranslationInterface
  199. * A mock translation object.
  200. */
  201. public function getStringTranslationStub() {
  202. $translation = $this->createMock('Drupal\Core\StringTranslation\TranslationInterface');
  203. $translation->expects($this->any())
  204. ->method('translate')
  205. ->willReturnCallback(function ($string, array $args = [], array $options = []) use ($translation) {
  206. return new TranslatableMarkup($string, $args, $options, $translation);
  207. });
  208. $translation->expects($this->any())
  209. ->method('translateString')
  210. ->willReturnCallback(function (TranslatableMarkup $wrapper) {
  211. return $wrapper->getUntranslatedString();
  212. });
  213. $translation->expects($this->any())
  214. ->method('formatPlural')
  215. ->willReturnCallback(function ($count, $singular, $plural, array $args = [], array $options = []) use ($translation) {
  216. $wrapper = new PluralTranslatableMarkup($count, $singular, $plural, $args, $options, $translation);
  217. return $wrapper;
  218. });
  219. return $translation;
  220. }
  221. /**
  222. * Sets up a container with a cache tags invalidator.
  223. *
  224. * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_validator
  225. * The cache tags invalidator.
  226. *
  227. * @return \Symfony\Component\DependencyInjection\ContainerInterface|\PHPUnit\Framework\MockObject\MockObject
  228. * The container with the cache tags invalidator service.
  229. */
  230. protected function getContainerWithCacheTagsInvalidator(CacheTagsInvalidatorInterface $cache_tags_validator) {
  231. $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
  232. $container->expects($this->any())
  233. ->method('get')
  234. ->with('cache_tags.invalidator')
  235. ->will($this->returnValue($cache_tags_validator));
  236. \Drupal::setContainer($container);
  237. return $container;
  238. }
  239. /**
  240. * Returns a stub class resolver.
  241. *
  242. * @return \Drupal\Core\DependencyInjection\ClassResolverInterface|\PHPUnit\Framework\MockObject\MockObject
  243. * The class resolver stub.
  244. */
  245. protected function getClassResolverStub() {
  246. $class_resolver = $this->createMock('Drupal\Core\DependencyInjection\ClassResolverInterface');
  247. $class_resolver->expects($this->any())
  248. ->method('getInstanceFromDefinition')
  249. ->willReturnCallback(function ($class) {
  250. if (is_subclass_of($class, 'Drupal\Core\DependencyInjection\ContainerInjectionInterface')) {
  251. return $class::create(new ContainerBuilder());
  252. }
  253. else {
  254. return new $class();
  255. }
  256. });
  257. return $class_resolver;
  258. }
  259. }