More updates to stop using dev or alpha or beta versions.
[yaffs-website] / web / core / tests / Drupal / Tests / Core / Form / FormTestBase.php
1 <?php
2
3 namespace Drupal\Tests\Core\Form;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Form\FormBuilder;
7 use Drupal\Core\Form\FormInterface;
8 use Drupal\Core\Form\FormState;
9 use Drupal\Core\Form\FormStateInterface;
10 use Drupal\Tests\UnitTestCase;
11 use Symfony\Component\HttpFoundation\Request;
12 use Symfony\Component\HttpFoundation\RequestStack;
13
14 /**
15  * Provides a base class for testing form functionality.
16  *
17  * @see \Drupal\Core\Form\FormBuilder
18  */
19 abstract class FormTestBase extends UnitTestCase {
20
21   /**
22    * The form builder being tested.
23    *
24    * @var \Drupal\Core\Form\FormBuilderInterface
25    */
26   protected $formBuilder;
27
28   /**
29    * @var \Drupal\Core\Form\FormValidatorInterface|\PHPUnit_Framework_MockObject_MockObject
30    */
31   protected $formValidator;
32
33   /**
34    * @var \Drupal\Core\Form\FormSubmitterInterface|\PHPUnit_Framework_MockObject_MockObject
35    */
36   protected $formSubmitter;
37
38   /**
39    * The mocked URL generator.
40    *
41    * @var \Drupal\Core\Routing\UrlGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
42    */
43   protected $urlGenerator;
44
45   /**
46    * The mocked module handler.
47    *
48    * @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
49    */
50   protected $moduleHandler;
51
52   /**
53    * The form cache.
54    *
55    * @var \Drupal\Core\Form\FormCacheInterface|\PHPUnit_Framework_MockObject_MockObject
56    */
57   protected $formCache;
58
59   /**
60    * The cache backend to use.
61    *
62    * @var \Drupal\Core\Cache\CacheBackendInterface|\PHPUnit_Framework_MockObject_MockObject
63    */
64   protected $cache;
65
66   /**
67    * The current user.
68    *
69    * @var \Drupal\Core\Session\AccountInterface|\PHPUnit_Framework_MockObject_MockObject
70    */
71   protected $account;
72
73   /**
74    * The controller resolver.
75    *
76    * @var \Drupal\Core\Controller\ControllerResolverInterface|\PHPUnit_Framework_MockObject_MockObject
77    */
78   protected $controllerResolver;
79
80   /**
81    * The CSRF token generator.
82    *
83    * @var \Drupal\Core\Access\CsrfTokenGenerator|\PHPUnit_Framework_MockObject_MockObject
84    */
85   protected $csrfToken;
86
87   /**
88    * The request.
89    *
90    * @var \Symfony\Component\HttpFoundation\Request
91    */
92   protected $request;
93
94   /**
95    * The request stack.
96    *
97    * @var \Symfony\Component\HttpFoundation\RequestStack
98    */
99   protected $requestStack;
100
101   /**
102    * The class results.
103    *
104    * @var \Drupal\Core\DependencyInjection\ClassResolverInterface|\PHPUnit_Framework_MockObject_MockObject
105    */
106   protected $classResolver;
107
108   /**
109    * The element info manager.
110    *
111    * @var \Drupal\Core\Render\ElementInfoManagerInterface
112    */
113   protected $elementInfo;
114
115   /**
116    * The event dispatcher.
117    *
118    * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject
119    */
120   protected $eventDispatcher;
121
122   /**
123    * @var \Drupal\Core\StringTranslation\TranslationInterface|\PHPUnit_Framework_MockObject_MockObject
124    */
125   protected $translationManager;
126
127   /**
128    * @var \Drupal\Core\DrupalKernelInterface|\PHPUnit_Framework_MockObject_MockObject
129    */
130   protected $kernel;
131
132   /**
133    * @var \PHPUnit_Framework_MockObject_MockObject|\Psr\Log\LoggerInterface
134    */
135   protected $logger;
136
137   /**
138    * The mocked theme manager.
139    *
140    * @var \Drupal\Core\Theme\ThemeManagerInterface|\PHPUnit_Framework_MockObject_MockObject
141    */
142   protected $themeManager;
143
144   /**
145    * {@inheritdoc}
146    */
147   protected function setUp() {
148     parent::setUp();
149
150     // Add functions to the global namespace for testing.
151     require_once __DIR__ . '/fixtures/form_base_test.inc';
152
153     $this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
154
155     $this->formCache = $this->getMock('Drupal\Core\Form\FormCacheInterface');
156     $this->cache = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
157     $this->urlGenerator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface');
158
159     $this->classResolver = $this->getClassResolverStub();
160
161     $this->elementInfo = $this->getMockBuilder('\Drupal\Core\Render\ElementInfoManagerInterface')
162       ->disableOriginalConstructor()
163       ->getMock();
164     $this->elementInfo->expects($this->any())
165       ->method('getInfo')
166       ->will($this->returnCallback([$this, 'getInfo']));
167
168     $this->csrfToken = $this->getMockBuilder('Drupal\Core\Access\CsrfTokenGenerator')
169       ->disableOriginalConstructor()
170       ->getMock();
171     $this->kernel = $this->getMockBuilder('\Drupal\Core\DrupalKernel')
172       ->disableOriginalConstructor()
173       ->getMock();
174     $this->account = $this->getMock('Drupal\Core\Session\AccountInterface');
175     $this->themeManager = $this->getMock('Drupal\Core\Theme\ThemeManagerInterface');
176     $this->request = new Request();
177     $this->eventDispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
178     $this->requestStack = new RequestStack();
179     $this->requestStack->push($this->request);
180     $this->logger = $this->getMock('Drupal\Core\Logger\LoggerChannelInterface');
181     $form_error_handler = $this->getMock('Drupal\Core\Form\FormErrorHandlerInterface');
182     $this->formValidator = $this->getMockBuilder('Drupal\Core\Form\FormValidator')
183       ->setConstructorArgs([$this->requestStack, $this->getStringTranslationStub(), $this->csrfToken, $this->logger, $form_error_handler])
184       ->setMethods(NULL)
185       ->getMock();
186     $this->formSubmitter = $this->getMockBuilder('Drupal\Core\Form\FormSubmitter')
187       ->setConstructorArgs([$this->requestStack, $this->urlGenerator])
188       ->setMethods(['batchGet', 'drupalInstallationAttempted'])
189       ->getMock();
190     $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
191
192     $this->formBuilder = new FormBuilder($this->formValidator, $this->formSubmitter, $this->formCache, $this->moduleHandler, $this->eventDispatcher, $this->requestStack, $this->classResolver, $this->elementInfo, $this->themeManager, $this->csrfToken);
193   }
194
195   /**
196    * {@inheritdoc}
197    */
198   protected function tearDown() {
199     Html::resetSeenIds();
200     (new FormState())->clearErrors();
201   }
202
203   /**
204    * Provides a mocked form object.
205    *
206    * @param string $form_id
207    *   The form ID to be used.
208    * @param mixed $expected_form
209    *   (optional) If provided, the expected form response for buildForm() to
210    *   return. Defaults to NULL.
211    * @param int $count
212    *   (optional) The number of times the form is expected to be built. Defaults
213    *   to 1.
214    *
215    * @return \PHPUnit_Framework_MockObject_MockObject|\Drupal\Core\Form\FormInterface
216    *   The mocked form object.
217    */
218   protected function getMockForm($form_id, $expected_form = NULL, $count = 1) {
219     $form = $this->getMock('Drupal\Core\Form\FormInterface');
220     $form->expects($this->once())
221       ->method('getFormId')
222       ->will($this->returnValue($form_id));
223
224     if ($expected_form) {
225       $form->expects($this->exactly($count))
226         ->method('buildForm')
227         ->will($this->returnValue($expected_form));
228     }
229     return $form;
230   }
231
232   /**
233    * Simulates a form submission within a request, bypassing submitForm().
234    *
235    * Calling submitForm() will reset the form builder, if two forms were on the
236    * same page, they will be submitted simultaneously.
237    *
238    * @param string $form_id
239    *   The unique string identifying the form.
240    * @param \Drupal\Core\Form\FormInterface $form_arg
241    *   The form object.
242    * @param \Drupal\Core\Form\FormStateInterface $form_state
243    *   The current state of the form.
244    * @param bool $programmed
245    *   Whether $form_state->setProgrammed() should be passed TRUE or not. If it
246    *   is not set to TRUE, you must provide additional data in $form_state for
247    *   the submission to take place.
248    *
249    * @return array
250    *   The built form.
251    */
252   protected function simulateFormSubmission($form_id, FormInterface $form_arg, FormStateInterface $form_state, $programmed = TRUE) {
253     $input = $form_state->getUserInput();
254     $input['op'] = 'Submit';
255     $form_state
256       ->setUserInput($input)
257       ->setProgrammed($programmed)
258       ->setSubmitted();
259     return $this->formBuilder->buildForm($form_arg, $form_state);
260   }
261
262   /**
263    * Asserts that the expected form structure is found in a form for a given key.
264    *
265    * @param array $expected_form
266    *   The expected form structure.
267    * @param array $actual_form
268    *   The actual form.
269    * @param string|null $form_key
270    *   (optional) The form key to look in. Otherwise the entire form will be
271    *   compared.
272    */
273   protected function assertFormElement(array $expected_form, array $actual_form, $form_key = NULL) {
274     $expected_element = $form_key ? $expected_form[$form_key] : $expected_form;
275     $actual_element = $form_key ? $actual_form[$form_key] : $actual_form;
276     $this->assertSame(array_intersect_key($expected_element, $actual_element), $expected_element);
277   }
278
279   /**
280    * A stub method returning properties for the defined element type.
281    *
282    * @param string $type
283    *   The machine name of an element type plugin.
284    *
285    * @return array
286    *   An array with dummy values to be used in tests. Defaults to an empty
287    *   array.
288    */
289   public function getInfo($type) {
290     $types['hidden'] = [
291       '#input' => TRUE,
292     ];
293     $types['token'] = [
294       '#input' => TRUE,
295     ];
296     $types['value'] = [
297       '#input' => TRUE,
298     ];
299     $types['radios'] = [
300       '#input' => TRUE,
301     ];
302     $types['textfield'] = [
303       '#input' => TRUE,
304     ];
305     $types['submit'] = [
306       '#input' => TRUE,
307       '#name' => 'op',
308       '#is_button' => TRUE,
309     ];
310     if (!isset($types[$type])) {
311       $types[$type] = [];
312     }
313     return $types[$type];
314   }
315
316 }