UnitTestCase.php 9.9 KB

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