ConfigFormTestBase.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\KernelTests;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Core\Form\FormState;
  5. /**
  6. * Full generic test suite for any form that data with the configuration system.
  7. *
  8. * @see UserAdminSettingsFormTest
  9. * For a full working implementation.
  10. */
  11. abstract class ConfigFormTestBase extends KernelTestBase {
  12. /**
  13. * Form ID to use for testing.
  14. *
  15. * @var \Drupal\Core\Form\FormInterface
  16. */
  17. protected $form;
  18. /**
  19. * Values to use for testing.
  20. *
  21. * Contains details for form key, configuration object name, and config key.
  22. * Example:
  23. * @code
  24. * array(
  25. * 'user_mail_cancel_confirm_body' => array(
  26. * '#value' => $this->randomString(),
  27. * '#config_name' => 'user.mail',
  28. * '#config_key' => 'cancel_confirm.body',
  29. * ),
  30. * );
  31. * @endcode
  32. *
  33. * @var array
  34. */
  35. protected $values;
  36. /**
  37. * Submit the system_config_form ensure the configuration has expected values.
  38. */
  39. public function testConfigForm() {
  40. // Programmatically submit the given values.
  41. $values = [];
  42. foreach ($this->values as $form_key => $data) {
  43. $values[$form_key] = $data['#value'];
  44. }
  45. $form_state = (new FormState())->setValues($values);
  46. \Drupal::formBuilder()->submitForm($this->form, $form_state);
  47. // Check that the form returns an error when expected, and vice versa.
  48. $errors = $form_state->getErrors();
  49. $valid_form = empty($errors);
  50. $args = [
  51. '%values' => print_r($values, TRUE),
  52. '%errors' => $valid_form ? t('None') : implode(' ', $errors),
  53. ];
  54. $this->assertTrue($valid_form, new FormattableMarkup('Input values: %values<br/>Validation handler errors: %errors', $args));
  55. foreach ($this->values as $data) {
  56. $this->assertEqual($data['#value'], $this->config($data['#config_name'])->get($data['#config_key']));
  57. }
  58. }
  59. }