UnitTestCase.php 8.9 KB

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