Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing tests that use email submission #356

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 7 additions & 8 deletions dev/FunctionalTest.php
Expand Up @@ -12,7 +12,7 @@
* $this->get("your/url");
*
* // Submit a form on the page that you get in response
* $this->submitForm("MyForm_ID", array("Email" => "invalid email ^&*&^"));
* $this->post("your/url/Form, array("Email" => "invalid email ^&*&^"));
*
* // Validate the content that is returned
* $this->assertExactMatchBySelector("#MyForm_ID p.error", array("That email address is invalid."));
Expand Down Expand Up @@ -105,24 +105,23 @@ function post($url, $data, $headers = null, $session = null, $body = null, $cook
if($this->autoFollowRedirection && is_object($response) && $response->getHeader('Location')) $response = $this->mainSession->followRedirection();
return $response;
}

/**
* Submit the form with the given HTML ID, filling it out with the given data.
* Acts on the most recent response.
*
* Any data parameters have to be present in the form, with exact form field name
* and values, otherwise they are removed from the submission.
*
*
* Caution: Parameter names have to be formatted
* as they are in the form submission, not as they are interpreted by PHP.
* 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.
* @param Array $data Map of GET/POST data.
* @return SS_HTTPResponse
*/
function submitForm($formID, $button = null, $data = array()) {
Expand All @@ -131,7 +130,7 @@ function submitForm($formID, $button = null, $data = array()) {
if($this->autoFollowRedirection && is_object($response) && $response->getHeader('Location')) $response = $this->mainSession->followRedirection();
return $response;
}

/**
* Return the most recent content
*/
Expand Down
46 changes: 7 additions & 39 deletions dev/TestSession.php
Expand Up @@ -62,52 +62,39 @@ function post($url, $data, $headers = null, $session = null, $body = null, $cook
if(!$this->lastResponse) user_error("Director::test($url) returned null", E_USER_WARNING);
return $this->lastResponse;
}

/**
* Submit the form with the given HTML ID, filling it out with the given data.
* Acts on the most recent response.
*
* Any data parameters have to be present in the form, with exact form field name
* and values, otherwise they are removed from the submission.
*
*
* Caution: Parameter names have to be formatted
* as they are in the form submission, not as they are interpreted by PHP.
* 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.
* @param Array $data Map of GET/POST data.
* @return SS_HTTPResponse
*/
function submitForm($formID, $button = null, $data = array()) {
$page = $this->lastPage();
$page = $this->lastResponse;
if($page) {
$form = $page->getFormById($formID);
if (!$form) {
user_error("TestSession::submitForm failed to find the form {$formID}");
}

foreach($data as $k => $v) {
$form->setField(new SimpleByName($k), $v);
}

if($button) $submission = $form->submitButton(new SimpleByName($button));
else $submission = $form->submit();

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

$postVars = array();
parse_str($submission->_encode(), $postVars);
return $this->post($url, $postVars);

return $this->post($url, array_merge($data, array($button => 1)));
} else {
user_error("TestSession::submitForm called when there is no form loaded. Visit the page with the form first", E_USER_WARNING);
}
}

/**
* If the last request was a 3xx response, then follow the redirection
*/
Expand Down Expand Up @@ -146,25 +133,6 @@ function cssParser() {
return new CSSContentParser($this->lastContent());
}


/**
* Get the last response as a SimplePage object
*/
function lastPage() {
require_once("thirdparty/simpletest/http.php");
require_once("thirdparty/simpletest/page.php");
require_once("thirdparty/simpletest/form.php");

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

return $page;
}
}

/**
* Get the current session, as a Session object
*/
Expand Down
2 changes: 1 addition & 1 deletion forms/EmailField.php
Expand Up @@ -43,7 +43,7 @@ function validate($validator) {
"validation"
);
return false;
} else{
} else {
return true;
}
}
Expand Down
40 changes: 31 additions & 9 deletions forms/gridfield/GridFieldExportButton.php
Expand Up @@ -6,9 +6,6 @@

/**
* Adds an "Export list" button to the bottom of a GridField.
*
* WARNING: This is experimental and its API is subject to change. Feel free to use it as long as you are happy of
* refactoring your code in the future.
*/
class GridFieldExportButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler {

Expand Down Expand Up @@ -95,30 +92,55 @@ public function handleExport($gridField, $request = null) {
}

/**
* Export core.
*/
* Generate export fields for CSV.
*
* @param GridField $gridField
* @return array
*/
function generateExportFileData($gridField) {
$separator = $this->csvSeparator;
$csvColumns = ($this->exportColumns) ? $this->exportColumns : singleton($gridField->getModelClass())->summaryFields();
$fileData = '';
$columnData = array();
$fieldItems = new ArrayList();

if($this->csvHasHeader) {
$fileData .= "\"" . implode("\"{$separator}\"", array_values($csvColumns)) . "\"";
$headers = array();

// determine the CSV headers. If a field is callable (anon function) then use the
// source name as the header instead
foreach($csvColumns as $columnSource => $columnHeader) {
$headers[] = (is_callable($columnHeader)) ? $columnSource : $columnHeader;
}

$fileData .= "\"" . implode("\"{$separator}\"", array_values($headers)) . "\"";
$fileData .= "\n";
}

$items = $gridField->getList();

// @todo should GridFieldComponents change behaviour based on whether others are available in the config?
foreach($gridField->getConfig()->getComponents() as $component){
if($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) {
$items = $component->getManipulatedData($gridField, $items);
}
}

foreach($items as $item) {
$columnData = array();
foreach($csvColumns as $columnSource => $columnHeader) {
$value = $item->relField($columnSource);
if(is_callable($columnHeader)) {
if($item->hasMethod($columnSource)) {
$relObj = $item->{$columnSource}();
} else {
$relObj = $item->relObject($columnSource);
}

$value = $columnHeader($relObj);
} else {
$value = $item->relField($columnSource);
}

$value = str_replace(array("\r", "\n"), "\n", $value);
$columnData[] = '"' . str_replace('"', '\"', $value) . '"';
}
Expand All @@ -127,7 +149,7 @@ function generateExportFileData($gridField) {

$item->destroy();
}

return $fileData;
}

Expand Down
3 changes: 0 additions & 3 deletions forms/gridfield/GridFieldPrintButton.php
Expand Up @@ -6,9 +6,6 @@

/**
* Adds an "Print" button to the bottom or top of a GridField.
*
* WARNING: This is experimental and its API is subject to change. Feel free to use it as long as you are happy of
* refactoring your code in the future.
*/
class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler {

Expand Down
41 changes: 21 additions & 20 deletions tests/forms/FormTest.php
Expand Up @@ -193,43 +193,43 @@ public function testFormMethodOverride() {

function testSessionValidationMessage() {
$this->get('FormTest_Controller');

$response = $this->submitForm(
'Form_Form',
null,

$response = $this->post(
'FormTest_Controller/Form',
array(
'Email' => 'invalid',
// leaving out "Required" field
)
);

$this->assertPartialMatchBySelector(
'#Email span.message',
array(
_t('EmailField.VALIDATION', "Please enter an email address.")
'Please enter an email address.'
),
'Formfield validation shows note on field if invalid'
);

$this->assertPartialMatchBySelector(
'#SomeRequiredField span.required',
array(
sprintf(_t('Form.FIELDISREQUIRED').'.','"SomeRequiredField"')
),
'Required fields show a notification on field when left blank'
);

}

function testSessionSuccessMessage() {
$this->get('FormTest_Controller');

$response = $this->submitForm(
'Form_Form',
null,

$response = $this->post(
'FormTest_Controller/Form',
array(
'Email' => 'test@test.com',
'SomeRequiredField' => 'test',
)
);

$this->assertPartialMatchBySelector(
'#Form_Form_error',
array(
Expand Down Expand Up @@ -275,7 +275,7 @@ function testDisableSecurityTokenAcceptsSubmissionWithoutToken() {
SecurityToken::enable();

$response = $this->get('FormTest_ControllerWithSecurityToken');
// can't use submitForm() as it'll automatically insert SecurityID into the POST data

$response = $this->post(
'FormTest_ControllerWithSecurityToken/Form',
array(
Expand All @@ -285,23 +285,24 @@ function testDisableSecurityTokenAcceptsSubmissionWithoutToken() {
)
);
$this->assertEquals(400, $response->getStatusCode(), 'Submission fails without security token');

$response = $this->get('FormTest_ControllerWithSecurityToken');

$tokenEls = $this->cssParser()->getBySelector('#Form_Form_SecurityID');
$this->assertEquals(
1,
count($tokenEls),
1,
count($tokenEls),
'Token form field added for controller without disableSecurityToken()'
);
$token = (string)$tokenEls[0];
$response = $this->submitForm(
'Form_Form',
null,

$response = $this->post(
'FormTest_ControllerWithSecurityToken/Form',
array(
'Email' => 'test@test.com',
'SecurityID' => $token
'SecurityID' => (string)$tokenEls[0]['value']
)
);

$this->assertEquals(200, $response->getStatusCode(), 'Submission suceeds with security token');
}

Expand Down