Skip to content

Commit

Permalink
Merge pull request #10643 from creative-commoners/pulls/5/replace-sim…
Browse files Browse the repository at this point in the history
…pletest

DEP Replace thirdparty simpletest with symfony domcrawler
  • Loading branch information
GuySartorelli authored Feb 7, 2023
2 parents 5236b0a + 9d13f35 commit 0ff7623
Show file tree
Hide file tree
Showing 20 changed files with 89 additions and 6,771 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"sminnee/callbacklist": "^0.1.1",
"symfony/cache": "^6.1",
"symfony/config": "^6.1",
"symfony/dom-crawler": "^6.1",
"symfony/filesystem": "^6.1",
"symfony/mailer": "^6.1",
"symfony/mime": "^6.1",
Expand Down
6 changes: 3 additions & 3 deletions src/Dev/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,12 @@ public function post($url, $data, $headers = null, $session = null, $body = null
* @param string $formID HTML 'id' attribute of a form (loaded through a previous response)
* @param string $button HTML 'name' attribute of the button (NOT the 'id' attribute)
* @param array $data Map of GET/POST data.
* @return HTTPResponse
* @param bool $withSecurityToken Submit with the form's security token if there is one.
*/
public function submitForm($formID, $button = null, $data = [])
public function submitForm(string $formID, string $button = null, array $data = [], bool $withSecurityToken = true): HTTPResponse
{
$this->cssParser = null;
$response = $this->mainSession->submitForm($formID, $button, $data);
$response = $this->mainSession->submitForm($formID, $button, $data, $withSecurityToken);
if ($this->autoFollowRedirection && is_object($response) && $response->getHeader('Location')) {
$response = $this->mainSession->followRedirection();
}
Expand Down
72 changes: 34 additions & 38 deletions src/Dev/TestSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace SilverStripe\Dev;

use Exception;
use InvalidArgumentException;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Cookie_Backend;
use SilverStripe\Control\Director;
Expand All @@ -12,9 +13,7 @@
use SilverStripe\Control\Session;
use SilverStripe\Core\Extensible;
use SilverStripe\Core\Injector\Injector;
use SimpleByName;
use SimplePage;
use SimplePageBuilder;
use Symfony\Component\DomCrawler\Crawler;

/**
* Represents a test usage session of a web-app
Expand Down Expand Up @@ -202,44 +201,54 @@ public function sendRequest($method, $url, $data, $headers = null, $session = nu
* Wrong: array('mycheckboxvalues' => array(1 => 'one', 2 => 'two'))
* Right: array('mycheckboxvalues[1]' => 'one', 'mycheckboxvalues[2]' => 'two')
*
* @see http://www.simpletest.org/en/form_testing_documentation.html
*
* @param string $formID HTML 'id' attribute of a form (loaded through a previous response)
* @param string $button HTML 'name' attribute of the button (NOT the 'id' attribute)
* @param array $data Map of GET/POST data.
* @return HTTPResponse
* @throws Exception
* @param bool $withSecurityToken Submit with the form's security token if there is one.
*/
public function submitForm($formID, $button = null, $data = [])
public function submitForm(string $formID, string $button = null, array $data = [], bool $withSecurityToken = true): HTTPResponse
{
/** @var Crawler $page */
$page = $this->lastPage();
if ($page) {
$form = $page->getFormById($formID);
if (!$form) {
try {
$formCrawler = $page->filterXPath("//form[@id='$formID']");
$form = $formCrawler->form();
} catch (InvalidArgumentException $e) {
user_error("TestSession::submitForm failed to find the form {$formID}");
}

foreach ($data as $k => $v) {
$form->setField(new SimpleByName($k), $v);
foreach ($data as $fieldName => $value) {
if ($form->has($fieldName)) {
$form->get($fieldName)->setValue($value);
}
}

// Add security token to submitted values
if ($withSecurityToken && $form->has('SecurityID')) {
$securityField = $page->filterXPath("//input[@id='{$formID}_SecurityID']");
$form->get('SecurityID')->setValue($securityField->attr('value'));
}

$values = $form->getPhpValues();

// Add button to submitted values
if ($button) {
$submission = $form->submitButton(new SimpleByName($button));
if (!$submission) {
$btnXpath = "//button[@name='$button'] | //input[@name='$button'][@type='button' or @type='submit']";
if (!$formCrawler->children()->filterXPath($btnXpath)->count()) {
throw new Exception("Can't find button '$button' to submit as part of test.");
}
} else {
$submission = $form->submit();
$values[$button] = true;
}

$url = Director::makeRelative($form->getAction()->asString());

$postVars = [];
parse_str($submission->_encode() ?? '', $postVars);
return $this->post($url, $postVars);
return $this->sendRequest(
$form->getMethod(),
Director::makeRelative($form->getUri()),
$values
);
} else {
user_error("TestSession::submitForm called when there is no form loaded."
. " Visit the page with the form first", E_USER_WARNING);
. " Visit the page with the form first", E_USER_WARNING);
}
}

Expand Down Expand Up @@ -313,24 +322,11 @@ public function cssParser()
}

/**
* Get the last response as a SimplePage object
*
* @return SimplePage The response if available
* Get a DOM Crawler for the last response
*/
public function lastPage()
public function lastPage(): Crawler
{
require_once("simpletest/http.php");
require_once("simpletest/page.php");
require_once("simpletest/form.php");

$builder = new SimplePageBuilder();
if ($this->lastResponse) {
$page = &$builder->parse(new TestSession_STResponseWrapper($this->lastResponse));
$builder->free();
unset($builder);

return $page;
}
return new Crawler($this->lastContent(), Director::absoluteURL($this->lastUrl()));
}

/**
Expand Down
78 changes: 0 additions & 78 deletions src/Dev/TestSession_STResponseWrapper.php

This file was deleted.

2 changes: 0 additions & 2 deletions tests/php/Core/Injector/InjectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@
/**
* Tests for the dependency injector
*
* Note that these are SS conversions of the existing Simpletest unit tests
*
* @author [email protected]
* @license BSD License http://silverstripe.org/bsd-license/
*/
Expand Down
4 changes: 1 addition & 3 deletions tests/php/Forms/EmailFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ public function internalCheck($email, $checkText, $expectSuccess)
}

/**
* Check that input type='email' fields are submitted by SimpleTest
*
* @see SimpleTagBuilder::_createInputTag()
* Check that input type='email' fields are submitted
*/
public function testEmailFieldPopulation()
{
Expand Down
61 changes: 50 additions & 11 deletions tests/php/Forms/FormTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ public function testDisableSecurityTokenDoesntAddTokenFormField()
);
}

public function testDisableSecurityTokenAcceptsSubmissionWithoutToken()
public function testDisableSecurityTokenAcceptsSubmissionWithoutToken(): void
{
SecurityToken::enable();
$expectedToken = SecurityToken::inst()->getValue();
Expand Down Expand Up @@ -646,16 +646,55 @@ public function testDisableSecurityTokenAcceptsSubmissionWithoutToken()
count($tokenEls ?? []),
'Token form field added for controller without disableSecurityToken()'
);
$token = (string)$tokenEls[0];
$response = $this->submitForm(
'Form_Form',
null,
[
'Email' => '[email protected]',
'SecurityID' => $token
]
);
$this->assertEquals(200, $response->getStatusCode(), 'Submission succeeds with security token');
}

public function provideFormsSet()
{
return [
'with security token' =>
[
['Form_Form', null, [ 'Email' => '[email protected]' ], true],
200,
'Submission succeeds with security token',
],
'without security token' =>
[
['Form_Form', null, [ 'Email' => '[email protected]' ], false],
200,
'Cannot submit form without security token',
],
'button with wrong name' =>
[
['Form_Form', 'undefined', [ 'Email' => '[email protected]' ], true],
null,
"Can't find button 'undefined' to submit as part of test.",
],
];
}

/**
* @dataProvider provideFormsSet
*/
public function testSubmitFormWithSpecifiedParameters(
array $formData,
?int $statusCode,
string $testMessage
): void {

$this->get('FormTest_ControllerWithSecurityToken');

[ $form, $button, $data, $withSecurityToken ] = [ ...$formData ];

if (is_null($button)) {
$response = $this->submitForm($form, $button, $data, $withSecurityToken);
$this->assertEquals($statusCode, $response->getStatusCode(), $testMessage);
} else {
// Test nonexistent button Exceptions
$this->expectException(\Exception::class);
$this->expectExceptionMessage($testMessage);

$this->submitForm($form, $button, $data, $withSecurityToken);
}
}

public function testStrictFormMethodChecking()
Expand Down
Loading

0 comments on commit 0ff7623

Please sign in to comment.