diff --git a/src/Tests/CaptchaBaseWebTestCase.php b/src/Tests/CaptchaBaseWebTestCase.php index 538ef87..4c81aff 100755 --- a/src/Tests/CaptchaBaseWebTestCase.php +++ b/src/Tests/CaptchaBaseWebTestCase.php @@ -229,10 +229,10 @@ abstract class CaptchaBaseWebTestCase extends WebTestBase { protected function getMathCaptchaSolutionFromForm($form_html_id = NULL) { // Get the math challenge. if (!$form_html_id) { - $elements = $this->xpath('//div[@class="form-item form-type-textfield form-item-captcha-response"]/span[@class="field-prefix"]'); + $elements = $this->xpath('//div[contains(@class, "form-item-captcha-response")]/span[@class="field-prefix"]'); } else { - $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//div[@class="form-item form-type-textfield form-item-captcha-response"]/span[@class="field-prefix"]'); + $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//div[contains(@class, "form-item-captcha-response")]/span[@class="field-prefix"]'); } $this->assert('pass', json_encode($elements)); $challenge = (string) $elements[0]; diff --git a/src/Tests/CaptchaTestCase.php b/src/Tests/CaptchaTestCase.php index 12e0cef..7681406 100755 --- a/src/Tests/CaptchaTestCase.php +++ b/src/Tests/CaptchaTestCase.php @@ -7,6 +7,10 @@ namespace Drupal\captcha\Tests; +use Drupal\Core\Field\FieldStorageDefinitionInterface; +use Drupal\field\Entity\FieldConfig; +use Drupal\field\Entity\FieldStorageConfig; + /** * Tests CAPTCHA main test case sensitivity. * @@ -209,4 +213,48 @@ class CaptchaTestCase extends CaptchaBaseWebTestCase { $this->assertCaptchaPresence(TRUE); } + /** + * Tests that the CAPTCHA is not changed on AJAX form rebuilds. + */ + public function testAjaxFormRebuild() { + // Setup captcha point for user edit form. + \Drupal::entityManager()->getStorage('captcha_point')->create([ + 'id' => 'user_form', + 'formId' => 'user_form', + 'status' => TRUE, + 'captchaType' => 'captcha/Math', + ])->save(); + + // Add multiple text field on user edit form. + $field_storage_config = FieldStorageConfig::create([ + 'field_name' => 'field_texts', + 'type' => 'string', + 'entity_type' => 'user', + 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, + ]); + $field_storage_config->save(); + FieldConfig::create([ + 'field_storage' => $field_storage_config, + 'bundle' => 'user', + ])->save(); + entity_get_form_display('user', 'user', 'default')->setComponent('field_texts', [ + 'type' => 'string_textfield', + 'weight' => 10, + ])->save(); + + // Create and login a user. + $user = $this->drupalCreateUser([]); + $this->drupalLogin($user); + + // On edit form, add another item and save. + $this->drupalGet("user/{$user->id()}/edit"); + $this->drupalPostAjaxForm(NULL, [], 'field_texts_add_more'); + $this->drupalPostForm(NULL, [ + 'captcha_response' => $this->getMathCaptchaSolutionFromForm('user-form'), + ], t('Save')); + + // No error. + $this->assertText(t('The changes have been saved.')); + } + }