UnitTestCase.php 9.0 KB

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