UnitTestCase.php 8.9 KB

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