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