3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 define('CIVICRM_WEBTEST', 1);
31 * Base class for CiviCRM Selenium tests
33 * Common functions for unit tests
36 class CiviSeleniumTestCase
extends PHPUnit_Extensions_SeleniumTestCase
{
38 // Current logged-in user
39 protected $loggedInAs = NULL;
41 private $settingCache;
46 * Because we are overriding the parent class constructor, we
47 * need to show the same arguments as exist in the constructor of
48 * PHPUnit_Framework_TestCase, since
49 * PHPUnit_Framework_TestSuite::createTest() creates a
50 * ReflectionClass of the Test class and checks the constructor
51 * of that class to decide how to set up the test.
55 * @param string $dataName
56 * @param array $browser
58 public function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
59 parent
::__construct($name, $data, $dataName, $browser);
60 $this->loggedInAs
= NULL;
62 $this->settings
= new CiviSeleniumSettings();
63 if (property_exists($this->settings
, 'serverStartupTimeOut') && $this->settings
->serverStartupTimeOut
) {
64 global $CiviSeleniumTestCase_polled;
65 if (!$CiviSeleniumTestCase_polled) {
66 $CiviSeleniumTestCase_polled = TRUE;
67 CRM_Utils_Network
::waitForServiceStartup(
68 $this->drivers
[0]->getHost(),
69 $this->drivers
[0]->getPort(),
70 $this->settings
->serverStartupTimeOut
76 require_once 'CRM/Core/ClassLoader.php';
77 CRM_Core_ClassLoader
::singleton()->register();
79 // also initialize a connection to the db
80 // FIXME: not necessary for most tests, consider moving into functions that need this
81 $config = CRM_Core_Config
::singleton();
84 protected function setUp() {
85 $this->setBrowser($this->settings
->browser
);
86 // Make sure that below strings have path separator at the end
87 $this->setBrowserUrl($this->settings
->sandboxURL
);
88 $this->sboxPath
= $this->settings
->sandboxPATH
;
89 if (property_exists($this->settings
, 'rcHost') && $this->settings
->rcHost
) {
90 $this->setHost($this->settings
->rcHost
);
92 if (property_exists($this->settings
, 'rcPort') && $this->settings
->rcPort
) {
93 $this->setPort($this->settings
->rcPort
);
95 $this->settingCache
= array();
101 protected function prepareTestSession() {
102 $result = parent
::prepareTestSession();
104 // Set any cookies required by local installation
105 // Note: considered doing this in setUp(), but the Selenium session wasn't yet initialized.
106 if (property_exists($this->settings
, 'cookies')) {
107 // We don't really care about this page, but it seems we need
108 // to open a page before setting a cookie.
109 $this->open($this->sboxPath
);
110 $this->waitForPageToLoad($this->getTimeoutMsec());
111 $this->setCookies($this->settings
->cookies
);
117 * @param array $cookies
118 * Each item is an Array with keys:
120 * - value: string; note that RFC's don't define particular encoding scheme, so
121 * you must pick one yourself and pre-encode; does not allow values with
122 * commas, semicolons, or whitespace
123 * - path: string; default: '/'
124 * - max_age: int; default: 1 week (7*24*60*60)
126 protected function setCookies($cookies) {
127 foreach ($cookies as $cookie) {
128 if (!isset($cookie['path'])) {
129 $cookie['path'] = '/';
131 if (!isset($cookie['max_age'])) {
132 $cookie['max_age'] = 7 * 24 * 60 * 60;
134 $this->deleteCookie($cookie['name'], $cookie['path']);
135 $optionExprs = array();
136 foreach ($cookie as $key => $value) {
137 if ($key != 'name' && $key != 'value') {
138 $optionExprs[] = "$key=$value";
141 $this->createCookie("{$cookie['name']}={$cookie['value']}", implode(', ', $optionExprs));
145 protected function tearDown() {
149 * Authenticate as drupal user.
150 * @param $user : (str) the key 'user' or 'admin', or a literal username
151 * @param $pass : (str) if $user is a literal username and not 'user' or 'admin', supply the password
153 public function webtestLogin($user = 'user', $pass = NULL) {
154 // If already logged in as correct user, do nothing
155 if ($this->loggedInAs
=== $user) {
158 // If we are logged in as a different user, log out first
159 if ($this->loggedInAs
) {
160 $this->webtestLogout();
162 $this->open("{$this->sboxPath}user");
163 // Lookup username & password if not supplied
165 if ($pass === NULL) {
166 $pass = $user == 'admin' ?
$this->settings
->adminPassword
: $this->settings
->password
;
167 $username = $user == 'admin' ?
$this->settings
->adminUsername
: $this->settings
->username
;
169 // Make sure login form is available
170 $this->waitForElementPresent('edit-submit');
171 $this->type('edit-name', $username);
172 $this->type('edit-pass', $pass);
173 $this->click('edit-submit');
174 $this->waitForPageToLoad($this->getTimeoutMsec());
175 $this->loggedInAs
= $user;
178 public function webtestLogout() {
179 if ($this->loggedInAs
) {
180 $this->open($this->sboxPath
. "user/logout");
181 $this->waitForPageToLoad($this->getTimeoutMsec());
183 $this->loggedInAs
= NULL;
187 * Open an internal path beginning with 'civicrm/'
190 * omit the 'civicrm/' it will be added for you.
191 * @param string|array $args
192 * optional url arguments.
194 * Page element to wait for - using this is recommended to ensure the document is fully loaded.
196 * Although it doesn't seem to do much now, using this function is recommended for
197 * opening all civi pages, and using the $args param is also strongly encouraged
198 * This will make it much easier to run webtests in other CMSs in the future
200 public function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
201 // Construct full url with args
202 // This could be extended in future to work with other CMS style urls
204 if (is_array($args)) {
206 foreach ($args as $key => $val) {
207 $url .= $sep . $key . '=' . $val;
215 $this->open("{$this->sboxPath}civicrm/$url");
216 $this->waitForPageToLoad($this->getTimeoutMsec());
217 $this->checkForErrorsOnPage();
219 $this->waitForElementPresent($waitFor);
224 * Click on a link or button.
225 * Wait for the page to load
226 * Wait for an element to be present
228 * @param string $waitFor
229 * @param bool $waitForPageLoad
231 public function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
232 $this->click($element);
233 // conditional wait for page load e.g for ajax form save
234 if ($waitForPageLoad) {
235 $this->waitForPageToLoad($this->getTimeoutMsec());
236 $this->checkForErrorsOnPage();
239 $this->waitForElementPresent($waitFor);
244 * Click a link or button and wait for an ajax dialog to load.
245 * @param string $element
246 * @param string $waitFor
248 public function clickPopupLink($element, $waitFor = NULL) {
249 $this->clickAjaxLink($element, 'css=.ui-dialog');
251 $this->waitForElementPresent($waitFor);
256 * Click a link or button and wait for ajax content to load or refresh.
257 * @param string $element
258 * @param string $waitFor
260 public function clickAjaxLink($element, $waitFor = NULL) {
261 $this->click($element);
263 $this->waitForElementPresent($waitFor);
265 $this->waitForAjaxContent();
269 * Force a link to open full-page, even if it would normally open in a popup
270 * @note: works with links only, not buttons
271 * @param string $element
272 * @param string $waitFor
274 public function clickLinkSuppressPopup($element, $waitFor = 'civicrm-footer') {
275 $link = $this->getAttribute($element . '@href');
277 $this->waitForPageToLoad($this->getTimeoutMsec());
279 $this->waitForElementPresent($waitFor);
284 * Wait for all ajax snippets to finish loading.
286 public function waitForAjaxContent() {
287 $this->waitForElementNotPresent('css=.blockOverlay');
288 // Some ajax calls happen in pairs (e.g. submit a popup form then refresh the underlying content)
289 // So we'll wait a sec and recheck to see if any more stuff is loading
291 if ($this->isElementPresent('css=.blockOverlay')) {
292 $this->waitForAjaxContent();
297 * Call the API on the local server.
298 * (kind of defeats the point of a webtest - see CRM-11889)
304 public function webtest_civicrm_api($entity, $action, $params) {
305 if (!isset($params['version'])) {
306 $params['version'] = 3;
309 $result = civicrm_api($entity, $action, $params);
310 $this->assertAPISuccess($result);
315 * Call the API on the remote server using the AJAX endpoint.
320 * @param array $params
323 public function rest_civicrm_api($entity, $action, $params = array()) {
331 setTimeout(function(){
332 CRM.api3("@entity", "@action", @params).then(function(a){
333 cj("<textarea>").css("display", "none").prop("id","crmajax@reqId").val(JSON.stringify(a)).appendTo("body");
338 '@entity' => $entity,
339 '@action' => $action,
340 '@params' => json_encode($params),
343 $js = strtr($jsCmd, $jsArgs);
344 $this->runScript($js);
345 $this->waitForElementPresent("crmajax{$reqId}");
346 $result = json_decode($this->getValue("crmajax{$reqId}"), TRUE);
347 $this->runScript("cj('#crmajax{$reqId}').remove();");
352 * @param string $option_group_name
356 public function webtestGetFirstValueForOptionGroup($option_group_name) {
357 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
358 'option_group_name' => $option_group_name,
368 public function webtestGetValidCountryID() {
370 if (is_null($_country_id)) {
371 $_country_id = Civi
::settings()->get('defaultContactCountry');
381 public function webtestGetValidEntityID($entity) {
382 // michaelmcandrew: would like to use getvalue but there is a bug
383 // for e.g. group where option.limit not working at the moment CRM-9110
384 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
385 if (!empty($result['values'])) {
386 return current(array_keys($result['values']));
392 * @param string $field
395 public function webtestGetSetting($field) {
396 if (!isset($this->settingCache
[$field])) {
397 $result = $this->webtest_civicrm_api("Setting", "getsingle", array(
400 $this->settingCache
[$field] = $result[$field];
402 return $this->settingCache
[$field];
406 * override this since the built in function doesn't work with the new phpunit.
407 * @param string $element
408 * @param string $text
410 public function waitForText($element, $text) {
411 $this->waitForTextPresent($text);
412 $this->assertElementContainsText($element, $text);
416 * Ensures the required CiviCRM components are enabled.
419 public function enableComponents($components) {
420 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
421 $enabledComponents = $this->getSelectOptions("enableComponents-t");
423 foreach ((array) $components as $comp) {
424 if (!in_array($comp, $enabledComponents)) {
425 $this->addSelection("enableComponents-f", "label=$comp");
426 $this->click("//option[@value='$comp']");
432 $this->clickLink("_qf_Component_next-bottom");
433 $this->checkCRMAlert("Saved");
438 * Ensures the required currencies are enabled.
441 public function enableCurrency($currencies) {
442 $this->openCiviPage("admin/setting/localization", "reset=1", "_qf_Localization_next-bottom");
443 $enabledCurrency = $this->getSelectOptions("currencyLimit-t");
444 foreach ($enabledCurrency as $k => $val) {
445 $enabledCurrency[$k] = substr($val, 0, 3);
448 foreach ((array) $currencies as $curr) {
449 if (!in_array($curr, $enabledCurrency)) {
450 $this->addSelection("currencyLimit-f", "value=$curr");
451 $this->click("//option[@value='$curr']");
457 $this->clickLink("_qf_Localization_next-bottom");
462 * Add a contact with the given first and last names and either a given email.
463 * (when specified), a random email (when true) or no email (when unspecified or null).
465 * @param string $fname
466 * Contact’s first name.
467 * @param string $lname
468 * Contact’s last name.
469 * @param mixed $email
470 * Contact’s email (when string) or random email (when true) or no email (when null).
471 * @param string $contactSubtype
473 * @return string|null
474 * either a string with the (either generated or provided) email or null (if no email)
476 public function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
477 $args = 'reset=1&ct=Individual';
478 if ($contactSubtype) {
479 $args .= "&cst={$contactSubtype}";
481 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
482 $this->type('first_name', $fname);
483 $this->type('last_name', $lname);
484 if ($email === TRUE) {
485 $email = substr(sha1(rand()), 0, 7) . '@example.org';
488 $this->type('email_1_email', $email);
490 $this->clickLink('_qf_Contact_upload_view-bottom');
495 * @param string $householdName
498 * @return null|string
500 public function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
501 $this->openCiviPage("contact/add", "reset=1&ct=Household");
502 $this->click('household_name');
503 $this->type('household_name', $householdName);
505 if ($email === TRUE) {
506 $email = substr(sha1(rand()), 0, 7) . '@example.org';
509 $this->type('email_1_email', $email);
512 $this->clickLink('_qf_Contact_upload_view');
517 * @param string $organizationName
519 * @param null $contactSubtype
521 * @return null|string
523 public function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
524 $args = 'reset=1&ct=Organization';
525 if ($contactSubtype) {
526 $args .= "&cst={$contactSubtype}";
528 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
529 $this->click('organization_name');
530 $this->type('organization_name', $organizationName);
532 if ($email === TRUE) {
533 $email = substr(sha1(rand()), 0, 7) . '@example.org';
536 $this->type('email_1_email', $email);
538 $this->clickLink('_qf_Contact_upload_view');
544 * @param string $fieldName
546 public function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
547 $this->select2($fieldName, $sortName);
548 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
554 public function webtestOrganisationAutocomplete($sortName) {
555 $this->clickAt("//*[@id='contact_id']/../div/a");
556 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
557 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
558 $this->type("//*[@id='select2-drop']/div/input", $sortName);
559 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
560 $this->waitForElementPresent("//*[@class='select2-result-label']");
561 $this->clickAt("//*[@class='select2-results']/li[1]");
562 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
566 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
567 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
568 * 3. Examples of $strToTime arguments -
569 * webtestFillDate('start_date',"now")
570 * webtestFillDate('start_date',"10 September 2000")
571 * webtestFillDate('start_date',"+1 day")
572 * webtestFillDate('start_date',"+1 week")
573 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
574 * webtestFillDate('start_date',"next Thursday")
575 * webtestFillDate('start_date',"last Monday")
576 * @param $dateElement
577 * @param null $strToTimeArgs
579 public function webtestFillDate($dateElement, $strToTimeArgs = NULL, $multiselect = FALSE) {
580 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
582 $year = date('Y', $timeStamp);
583 // -1 ensures month number is inline with calender widget's month
584 $mon = date('n', $timeStamp) - 1;
585 $day = date('j', $timeStamp);
588 $this->click("xpath=//input[starts-with(@id, '{$dateElement}_display_')]");
590 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
591 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
592 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
593 $this->click("link=$day");
597 * 1. set both date and time.
598 * @param $dateElement
599 * @param null $strToTimeArgs
601 public function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
602 $this->webtestFillDate($dateElement, $strToTimeArgs);
604 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
605 $hour = date('h', $timeStamp);
606 $min = date('i', $timeStamp);
607 $meri = date('A', $timeStamp);
609 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
613 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
615 * @param array $expected
616 * Array of key/value pairs (like Status/Registered) to be checked.
617 * @param string $xpathPrefix
618 * Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath.
619 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
620 * @param string $tableId
621 * Pass in the id attribute of a table to be verified if you want to only check a specific table.
624 public function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
627 $tableLocator = "[@id='$tableId']";
629 foreach ($expected as $label => $value) {
630 //assertContains() accepts param as string
633 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
634 $this->assertElementContainsText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", $value);
637 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
638 $this->assertElementContainsText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", $value);
644 * Types text into a ckEditor rich text field in a form.
646 * @param string $fieldName
647 * Form field name (as assigned by PHP buildForm class).
648 * @param string $text
649 * Text to type into the field.
650 * @param string $editor
651 * Which text editor (valid values are 'CKEditor', 'TinyMCE').
653 * @param bool $compressed
654 * @throws \PHPUnit_Framework_AssertionFailedError
656 public function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor', $compressed = FALSE) {
657 // make sure cursor focuses on the field
658 $this->fireEvent($fieldName, 'focus');
659 if ($editor == 'CKEditor') {
661 $this->click("xpath=//textarea[@id='{$fieldName}']/../div[1]");
663 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
664 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
666 elseif ($editor == 'TinyMCE') {
667 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
668 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
671 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
673 $this->selectFrame('relative=top');
677 * Types option label and name into a table of multiple choice options.
678 * (for price set fields of type select, radio, or checkbox)
679 * TODO: extend for custom field multiple choice table input
681 * @param array $options
682 * Form field name (as assigned by PHP buildForm class).
683 * @param array $validateStrings
684 * Appends label and name strings to this array so they can be validated later.
688 public function addMultipleChoiceOptions($options, &$validateStrings) {
689 foreach ($options as $oIndex => $oValue) {
690 $validateStrings[] = $oValue['label'];
691 $validateStrings[] = $oValue['amount'];
692 if (!empty($oValue['membership_type_id'])) {
693 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
695 if (!empty($oValue['financial_type_id'])) {
696 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
698 $this->type("option_label_{$oIndex}", $oValue['label']);
699 $this->type("option_amount_{$oIndex}", $oValue['amount']);
700 $this->click('link=add another choice');
705 * Use a contact EntityRef field to add a new contact.
706 * @param string $field
708 * @param string $contactType
710 * Array of contact attributes (id, names, email)
712 public function createDialogContact($field = 'contact_id', $contactType = 'Individual') {
713 $selectId = 's2id_' . $this->getAttribute($field . '@id');
714 $this->clickAt("xpath=//div[@id='$selectId']/a");
715 $this->clickAjaxLink("xpath=//li[@class='select2-no-results']//a[contains(text(), 'New $contactType')]", '_qf_Edit_next');
717 $name = substr(sha1(rand()), 0, rand(6, 8));
719 if ($contactType == 'Individual') {
720 $params['first_name'] = "$name $contactType";
721 $params['last_name'] = substr(sha1(rand()), 0, rand(5, 9));
724 $params[strtolower($contactType) . '_name'] = "$name $contactType";
726 foreach ($params as $param => $val) {
727 $this->type($param, $val);
729 $this->type('email-Primary', $params['email'] = "{$name}@example.com");
730 $this->clickAjaxLink('_qf_Edit_next');
732 $this->waitForText("xpath=//div[@id='$selectId']", "$name");
734 $params['sort_name'] = $contactType == 'Individual' ?
$params['last_name'] . ', ' . $params['first_name'] : "$name $contactType";
735 $params['display_name'] = $contactType == 'Individual' ?
$params['first_name'] . ' ' . $params['last_name'] : $params['sort_name'];
736 $params['id'] = $this->getValue($field);
741 * @deprecated in favor of createDialogContact
742 * @param string $fname
743 * @param string $lname
744 * @param string $email
746 * @param string $selectId
748 * @param string $prefix
750 public function webtestNewDialogContact(
751 $fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
752 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
753 // 4 - Individual profile
754 // 5 - Organization profile
755 // 6 - Household profile
756 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
757 $this->clickAt("xpath=//div[@id='$selectId']/a");
758 $this->clickPopupLink("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]", '_qf_Edit_next');
762 $this->type('first_name', $fname);
763 $this->type('last_name', $lname);
767 $this->type('organization_name', $fname);
771 $this->type('household_name', $fname);
775 $this->type('email-Primary', $email);
776 $this->clickAjaxLink('_qf_Edit_next');
778 // Is new contact created?
780 $this->waitForText("xpath=//div[@id='$selectId']", "$lname, $fname");
783 $this->waitForText("xpath=//div[@id='$selectId']", "$fname");
788 * Generic function to check that strings are present in the page.
790 * @strings array array of strings or a single string
795 public function assertStringsPresent($strings) {
796 foreach ((array) $strings as $string) {
797 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
802 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
804 * @url string url to parse or retrieve current url if null
808 * returns an associative array containing any of the various components
809 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
810 * http://php.net/manual/en/function.parse-url.php
812 public function parseURL($url = NULL) {
814 $url = $this->getLocation();
817 $elements = parse_url($url);
818 if (!empty($elements['query'])) {
819 $elements['queryString'] = array();
820 parse_str($elements['query'], $elements['queryString']);
826 * Returns a single argument from the url query.
831 public function urlArg($arg, $url = NULL) {
832 $elements = $this->parseURL($url);
833 return isset($elements['queryString'][$arg]) ?
$elements['queryString'][$arg] : NULL;
837 * Define a payment processor for use by a webtest. Default is to create Dummy processor
838 * which is useful for testing online public forms (online contribution pages and event registration)
840 * @param string $processorName
841 * Name assigned to new processor.
842 * @param string $processorType
843 * Name for processor type (e.g. PayPal, Dummy, etc.).
844 * @param array $processorSettings
845 * Array of fieldname => value for required settings for the processor.
847 * @param string $financialAccount
848 * @throws PHPUnit_Framework_AssertionFailedError
851 public function webtestAddPaymentProcessor($processorName = 'Test Processor', $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
852 if (!$processorName) {
853 $this->fail("webTestAddPaymentProcessor requires $processorName.");
855 // Ensure we are logged in as admin before we proceed
856 $this->webtestLogin('admin');
858 if ($processorName === 'Test Processor') {
859 // Use the default test processor, no need to create a new one
860 $this->openCiviPage('admin/paymentProcessor', 'action=update&id=1&reset=1', '_qf_PaymentProcessor_cancel-bottom');
861 $this->check('is_default');
862 $this->select('financial_account_id', "label={$financialAccount}");
863 $this->clickLink('_qf_PaymentProcessor_next-bottom');
867 if ($processorType == 'Dummy') {
868 $processorSettings = array(
869 'user_name' => 'dummy',
870 'url_site' => 'http://dummy.com',
871 'test_user_name' => 'dummytest',
872 'test_url_site' => 'http://dummytest.com',
875 elseif ($processorType == 'AuthNet') {
876 // FIXME: we 'll need to make a new separate account for testing
877 $processorSettings = array(
878 //dummy live username/password are passed to bypass processor validation on live credential
879 'user_name' => '3HcY62mY',
880 'password' => '69943NrwaQA92b8J',
881 'test_user_name' => '5ULu56ex',
882 'password' => '7ARxW575w736eF5p',
883 'test_password' => '7ARxW575w736eF5p',
886 elseif ($processorType == 'PayPal') {
887 $processorSettings = array(
888 'test_user_name' => '559999327053114',
889 'user_name' => '559999327053114',
890 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
891 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
892 'password' => 'R2zv2g60-A7GXKJYl0nR0g',
893 'signature' => 'R2zv2g60-A7GXKJYl0nR0g',
896 elseif ($processorType == 'PayPal_Standard') {
897 $processorSettings = array(
898 'user_name' => 'V18ki@9r5Bf.org',
899 'test_user_name' => 'V18ki@9r5Bf.org',
902 elseif (empty($processorSettings)) {
903 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
905 $pid = CRM_Core_DAO
::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
907 $this->fail("$processorType processortype not found.");
909 $this->openCiviPage('admin/paymentProcessor', 'action=add&reset=1&pp=' . $pid, 'name');
910 $this->type('name', $processorName);
911 $this->select('financial_account_id', "label={$financialAccount}");
912 foreach ($processorSettings as $f => $v) {
917 $this->clickLink('_qf_PaymentProcessor_next-bottom');
919 $this->waitForTextPresent($processorName);
921 // Get payment processor id
922 $paymentProcessorLink = $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href");
923 return $this->urlArg('id', $paymentProcessorLink);
926 public function webtestAddCreditCardDetails() {
927 $this->waitForElementPresent('credit_card_type');
928 $this->select('credit_card_type', 'label=Visa');
929 $this->type('credit_card_number', '4807731747657838');
930 $this->type('cvv2', '123');
931 $this->select('credit_card_exp_date[M]', 'label=Feb');
932 $this->select('credit_card_exp_date[Y]', 'label=2019');
936 * @param null $firstName
937 * @param null $middleName
938 * @param null $lastName
942 public function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
948 $middleName = 'Apple';
952 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
955 $this->type('billing_first_name', $firstName);
956 $this->type('billing_middle_name', $middleName);
957 $this->type('billing_last_name', $lastName);
959 $this->type('billing_street_address-5', '234 Lincoln Ave');
960 $this->type('billing_city-5', 'San Bernadino');
961 $this->select2('billing_country_id-5', 'UNITED STATES');
962 $this->select2('billing_state_province_id-5', 'California');
963 $this->type('billing_postal_code-5', '93245');
965 return array($firstName, $middleName, $lastName);
969 * @param $fieldLocator
970 * @param null $filePath
972 * @return null|string
974 public function webtestAttachFile($fieldLocator, $filePath = NULL) {
976 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
977 $fp = @fopen
($filePath, 'w');
978 fwrite($fp, 'Test file created by selenium test.');
982 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
984 $this->attachFile($fieldLocator, "file://{$filePath}");
992 * @param null $filePath
994 * @return null|string
996 public function webtestCreateCSV($headers, $rows, $filePath = NULL) {
998 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
1001 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
1003 foreach ($rows as $row) {
1005 foreach ($headers as $field => $header) {
1006 $temp[$field] = isset($row[$field]) ?
'"' . $row[$field] . '"' : '""';
1008 $data .= implode(', ', $temp) . "\r\n";
1011 $fp = @fopen
($filePath, 'w');
1012 @fwrite
($fp, $data);
1015 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
1021 * Create new relationship type w/ user specified params or default.
1023 * @param array $params
1024 * array of required params.
1027 * array of saved params values.
1029 public function webtestAddRelationshipType($params = array()) {
1030 $this->openCiviPage("admin/reltype", "reset=1&action=add");
1032 //build the params if not passed.
1033 if (!is_array($params) ||
empty($params)) {
1035 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
1036 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
1037 'contact_types_a' => 'Individual',
1038 'contact_types_b' => 'Individual',
1039 'description' => 'Test Relationship Type Description',
1042 //make sure we have minimum required params.
1043 if (!isset($params['label_a_b']) ||
empty($params['label_a_b'])) {
1044 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
1047 //start the form fill.
1048 $this->type('label_a_b', $params['label_a_b']);
1049 $this->type('label_b_a', $params['label_b_a']);
1050 $this->select('contact_types_a', "value={$params['contact_type_a']}");
1051 $this->select('contact_types_b', "value={$params['contact_type_b']}");
1052 $this->type('description', $params['description']);
1055 $this->click('_qf_RelationshipType_next-bottom');
1056 $this->waitForPageToLoad($this->getTimeoutMsec());
1059 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
1060 "Status message didn't show up after saving!"
1063 $this->openCiviPage("admin/reltype", "reset=1");
1065 //validate data on selector.
1067 if (isset($data['description'])) {
1068 unset($data['description']);
1070 $this->assertStringsPresent($data);
1076 * Create new online contribution page w/ user specified params or defaults.
1077 * FIXME: this function take an absurd number of params - very unwieldy :(
1081 * @param null $pageTitle
1082 * @param array $processor
1083 * @param bool $amountSection
1084 * @param bool $payLater
1085 * @param bool $onBehalf
1086 * @param bool $pledges
1087 * @param bool $recurring
1088 * @param bool $membershipTypes
1089 * @param int $memPriceSetId
1090 * @param bool $friend
1091 * @param int $profilePreId
1092 * @param int $profilePostId
1093 * @param bool $premiums
1094 * @param bool $widget
1096 * @param bool $isAddPaymentProcessor
1097 * @param bool $isPcpApprovalNeeded
1098 * @param bool $isSeparatePayment
1099 * @param bool $honoreeSection
1100 * @param bool $allowOtherAmount
1101 * @param bool $isConfirmEnabled
1102 * @param string $financialType
1103 * @param bool $fixedAmount
1104 * @param bool $membershipsRequired
1107 * of newly created online contribution page.
1109 public function webtestAddContributionPage(
1113 $processor = array('Test Processor' => 'Dummy'),
1114 $amountSection = TRUE,
1119 $membershipTypes = TRUE,
1120 $memPriceSetId = NULL,
1127 $isAddPaymentProcessor = TRUE,
1128 $isPcpApprovalNeeded = FALSE,
1129 $isSeparatePayment = FALSE,
1130 $honoreeSection = TRUE,
1131 $allowOtherAmount = TRUE,
1132 $isConfirmEnabled = TRUE,
1133 $financialType = 'Donation',
1134 $fixedAmount = TRUE,
1135 $membershipsRequired = TRUE
1138 $hash = substr(sha1(rand()), 0, 7);
1141 $pageTitle = 'Donate Online ' . $hash;
1145 $rand = 2 * rand(2, 50);
1148 // Create a new payment processor if requested
1149 if ($isAddPaymentProcessor) {
1150 while (list($processorName, $processorType) = each($processor)) {
1151 $this->webtestAddPaymentProcessor($processorName, $processorType);
1155 // go to the New Contribution Page page
1156 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
1158 // fill in step 1 (Title and Settings)
1159 $this->type('title', $pageTitle);
1161 //to select financial type
1162 $this->select('financial_type_id', "label={$financialType}");
1165 $this->click('is_organization');
1166 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
1167 $this->type('for_organization', "On behalf $hash");
1169 if ($onBehalf == 'required') {
1170 $this->click('CIVICRM_QFID_2_4');
1172 elseif ($onBehalf == 'optional') {
1173 $this->click('CIVICRM_QFID_1_2');
1177 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1178 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1180 $this->type('goal_amount', 10 * $rand);
1182 // FIXME: handle Start/End Date/Time
1183 if ($honoreeSection) {
1184 $this->click('honor_block_is_active');
1185 $this->type('honor_block_title', "Honoree Section Title $hash");
1186 $this->type('honor_block_text', "Honoree Introductory Message $hash");
1187 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1188 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1189 $this->waitForElementPresent("//*[@class='select2-result-label']");
1190 $this->clickAt("//*[@class='select2-results']/li[1]");
1193 // is confirm enabled? it starts out enabled, so uncheck it if false
1194 if (!$isConfirmEnabled) {
1195 $this->click("id=is_confirm_enabled");
1199 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1201 // Get contribution page id
1202 $pageId = $this->urlArg('id');
1204 // fill in step 2 (Processor, Pay Later, Amounts)
1205 if (!empty($processor)) {
1207 while (list($processorName) = each($processor)) {
1208 // select newly created processor
1209 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1210 $this->assertTrue($this->isTextPresent($processorName));
1211 $this->check($xpath);
1215 if ($amountSection && !$memPriceSetId) {
1217 $this->click('is_pay_later');
1218 $this->type('pay_later_text', "Pay later label $hash");
1219 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1223 $this->click('is_pledge_active');
1224 $this->click('pledge_frequency_unit[week]');
1225 $this->click('is_pledge_interval');
1226 $this->type('initial_reminder_day', 3);
1227 $this->type('max_reminders', 2);
1228 $this->type('additional_reminder_day', 1);
1230 elseif ($recurring) {
1231 $this->click('is_recur');
1232 $this->click("is_recur_interval");
1233 $this->click("is_recur_installments");
1235 if ($allowOtherAmount) {
1237 $this->click('is_allow_other_amount');
1239 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1240 //$this->type('min_amount', $rand / 2);
1241 //$this->type('max_amount', $rand * 10);
1243 if ($fixedAmount ||
!$allowOtherAmount) {
1244 $this->type('label_1', "Label $hash");
1245 $this->type('value_1', "$rand");
1247 $this->click('CIVICRM_QFID_1_4');
1250 $this->click('amount_block_is_active');
1253 $this->click('_qf_Amount_next');
1254 $this->waitForElementPresent('_qf_Amount_next-bottom');
1255 $this->waitForPageToLoad($this->getTimeoutMsec());
1256 $text = "'Amount' information has been saved.";
1257 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1259 if ($memPriceSetId ||
(($membershipTypes === TRUE) ||
(is_array($membershipTypes) && !empty($membershipTypes)))) {
1260 // go to step 3 (memberships)
1261 $this->click('link=Memberships');
1262 $this->waitForElementPresent('_qf_MembershipBlock_submit_savenext');
1264 // fill in step 3 (Memberships)
1265 $this->click('member_is_active');
1266 $this->waitForElementPresent('displayFee');
1267 $this->type('new_title', "Title - New Membership $hash");
1268 $this->type('renewal_title', "Title - Renewals $hash");
1270 if ($memPriceSetId) {
1271 $this->click('member_price_set_id');
1272 $this->select('member_price_set_id', "value={$memPriceSetId}");
1275 if ($membershipTypes === TRUE) {
1276 $membershipTypes = array(array('id' => 2, 'name' => 'Student', 'default' => 1));
1279 // FIXME: handle Introductory Message - New Memberships/Renewals
1280 foreach ($membershipTypes as $mType) {
1281 $this->click("membership_type_{$mType['id']}");
1282 if (array_key_exists('default', $mType)) {
1283 $this->click("xpath=//label[text() = '$mType[name]']/parent::td/parent::tr/td[2]/input");
1285 if (array_key_exists('auto_renew', $mType)) {
1286 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1289 if ($membershipsRequired) {
1290 $this->click('is_required');
1292 if ($isSeparatePayment) {
1293 $this->click('is_separate_payment');
1296 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1297 $text = "'MembershipBlock' information has been saved.";
1298 $this->isTextPresent($text);
1301 // go to step 4 (thank-you and receipting)
1302 $this->click('link=Receipt');
1303 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1306 $this->type('thankyou_title', "Thank-you Page Title $hash");
1307 // FIXME: handle Thank-you Message/Page Footer
1308 $this->type('receipt_from_name', "Receipt From Name $hash");
1309 $this->type('receipt_from_email', "$hash@example.org");
1310 $this->type('receipt_text', "Receipt Message $hash");
1311 $this->type('cc_receipt', "$hash@example.net");
1312 $this->type('bcc_receipt', "$hash@example.com");
1314 $this->click('_qf_ThankYou_next');
1315 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1316 $this->waitForPageToLoad($this->getTimeoutMsec());
1317 $text = "'ThankYou' information has been saved.";
1318 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1321 // fill in step 5 (Tell a Friend)
1322 $this->click('link=Tell a Friend');
1323 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1324 $this->click('tf_is_active');
1325 $this->type('tf_title', "TaF Title $hash");
1326 $this->type('intro', "TaF Introduction $hash");
1327 $this->type('suggested_message', "TaF Suggested Message $hash");
1328 $this->type('general_link', "TaF Info Page Link $hash");
1329 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1330 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1332 //$this->click('_qf_Contribute_next');
1333 $this->click('_qf_Contribute_next-bottom');
1334 $this->waitForPageToLoad($this->getTimeoutMsec());
1335 $text = "'Friend' information has been saved.";
1336 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1339 if ($profilePreId ||
$profilePostId) {
1340 // fill in step 6 (Include Profiles)
1341 $this->click('css=li#tab_custom a');
1342 $this->waitForElementPresent('_qf_Custom_next-bottom');
1344 if ($profilePreId) {
1345 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1348 if ($profilePostId) {
1349 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1352 $this->click('_qf_Custom_next-bottom');
1353 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1355 $this->waitForPageToLoad($this->getTimeoutMsec());
1356 $text = "'Custom' information has been saved.";
1357 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1361 // fill in step 7 (Premiums)
1362 $this->click('link=Premiums');
1363 $this->waitForElementPresent('_qf_Premium_next-bottom');
1364 $this->click('premiums_active');
1365 $this->type('premiums_intro_title', "Prem Title $hash");
1366 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1367 $this->type('premiums_contact_email', "$hash@example.info");
1368 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1369 $this->click('premiums_display_min_contribution');
1370 $this->type('premiums_nothankyou_label', 'No thank-you');
1371 $this->click('_qf_Premium_next');
1372 $this->waitForElementPresent('_qf_Premium_next-bottom');
1374 $this->waitForPageToLoad($this->getTimeoutMsec());
1375 $text = "'Premium' information has been saved.";
1376 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1377 $this->openCiviPage("admin/contribute/premium", "reset=1&action=update&id={$pageId}");
1378 $this->waitForAjaxContent();
1379 $this->waitForElementPresent('_qf_Premium_cancel-bottom');
1380 $this->click("xpath=//div[@class='messages status no-popup']/a[text()='add one']");
1381 $this->waitForElementPresent('_qf_AddProduct_cancel-bottom');
1382 $this->select('product_id', "value=1");
1383 $this->select('financial_type_id', "value=1");
1384 $this->click('_qf_AddProduct_next-bottom');
1385 $this->waitForElementPresent('_qf_Premium_cancel-bottom');
1386 $this->click('_qf_Premium_next-bottom');
1387 $this->waitForPageToLoad($this->getTimeoutMsec());
1391 // fill in step 8 (Widget Settings)
1392 $this->click('link=Widgets');
1393 $this->waitForElementPresent('_qf_Widget_next-bottom');
1394 $this->click('is_active');
1395 $this->type('url_logo', "URL to Logo Image $hash");
1396 $this->type('button_title', "Button Title $hash");
1397 // Type About text in ckEditor (fieldname, text to type, editor)
1398 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1400 $this->click('_qf_Widget_next');
1401 $this->waitForElementPresent('_qf_Widget_next-bottom');
1403 $this->waitForPageToLoad($this->getTimeoutMsec());
1404 $text = "'Widget' information has been saved.";
1405 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1409 // fill in step 9 (Enable Personal Campaign Pages)
1410 $this->click('link=Personal Campaigns');
1411 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1412 $this->click('pcp_active');
1413 if (!$isPcpApprovalNeeded) {
1414 $this->click('is_approval_needed');
1416 $this->type('notify_email', "$hash@example.name");
1417 $this->select('supporter_profile_id', 'value=2');
1418 $this->type('tellfriend_limit', 7);
1419 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1421 $this->click('_qf_Contribute_next-bottom');
1422 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1423 $this->waitForPageToLoad($this->getTimeoutMsec());
1424 $text = "'Pcp' information has been saved.";
1425 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1432 * Update default strict rule.
1434 * @param string $contactType
1435 * @param array $fields
1436 * Fields to be set for strict rule.
1437 * @param int $threshold
1438 * Rule's threshold value.
1440 public function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1441 // set default strict rule.
1443 if ($contactType == 'Organization') {
1446 elseif ($contactType == 'Household') {
1450 // Default dedupe fields for each Contact type.
1451 if (empty($fields)) {
1452 $fields = array('civicrm_email.email' => 10);
1453 if ($contactType == 'Organization') {
1455 'civicrm_contact.organization_name' => 10,
1456 'civicrm_email.email' => 10,
1459 elseif ($contactType == 'Household') {
1461 'civicrm_contact.household_name' => 10,
1462 'civicrm_email.email' => 10,
1467 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1470 foreach ($fields as $field => $weight) {
1471 $this->select("where_{$count}", "value={$field}");
1472 $this->type("length_{$count}", '');
1473 $this->type("weight_{$count}", $weight);
1478 $this->type('threshold', $threshold);
1480 $this->click('_qf_DedupeRules_next-bottom');
1481 $this->waitForPageToLoad($this->getTimeoutMsec());
1485 for ($i = $count; $i <= 4; $i++
) {
1486 $this->select("where_{$i}", 'label=- none -');
1487 $this->type("length_{$i}", '');
1488 $this->type("weight_{$i}", '');
1491 $this->type('threshold', $threshold);
1494 $this->click('_qf_DedupeRules_next-bottom');
1495 $this->waitForPageToLoad($this->getTimeoutMsec());
1499 * @param string $period_type
1500 * @param int $duration_interval
1501 * @param string $duration_unit
1502 * @param string $auto_renew
1503 * @param int $minimumFee
1504 * @param string $financialType
1508 public function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no', $minimumFee = 100, $financialType = 'Member Dues') {
1509 $membershipTitle = substr(sha1(rand()), 0, 7);
1510 $membershipOrg = $membershipTitle . ' memorg';
1511 $this->webtestAddOrganization($membershipOrg, TRUE);
1513 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1514 $memTypeParams = array(
1515 'membership_type' => $title,
1516 'member_of_contact' => $membershipOrg,
1517 'financial_type' => $financialType,
1518 'period_type' => $period_type,
1521 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1523 $this->type('name', $memTypeParams['membership_type']);
1525 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1526 // select the radio first since the element id changes after membership org search results are loaded
1527 switch ($auto_renew) {
1529 $this->click("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'Give option, but not required')]");
1533 $this->click("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'Auto-renew required')]");
1537 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1538 if ($this->isElementPresent("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'No auto-renew option')]")) {
1539 $this->click("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'No auto-renew option')]");
1544 $this->select2('member_of_contact_id', $membershipTitle);
1546 $this->type('minimum_fee', $minimumFee);
1547 $this->select('financial_type_id', "label={$memTypeParams['financial_type']}");
1549 $this->type('duration_interval', $duration_interval);
1550 $this->select('duration_unit', "label={$duration_unit}");
1551 $this->waitForElementPresent('period_type');
1552 $this->select('period_type', "value={$period_type}");
1554 $this->click('_qf_MembershipType_upload-bottom');
1555 $this->waitForElementPresent('link=Add Membership Type');
1556 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1558 return $memTypeParams;
1562 * @param null $groupName
1563 * @param null $parentGroupName
1565 * @return null|string
1567 public function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1568 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1572 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1574 $this->type('title', $groupName);
1577 $this->type('description', 'Adding new group.');
1579 // check Access Control
1580 $this->click('group_type[1]');
1582 // check Mailing List
1583 $this->click('group_type[2]');
1585 // select Visibility as Public Pages
1586 $this->select('visibility', 'value=Public Pages');
1588 // select parent group
1589 if ($parentGroupName) {
1590 $this->select('parents', "*$parentGroupName");
1594 $this->clickLink('_qf_Edit_upload-bottom');
1596 // Is status message correct?
1597 $this->waitForText('crm-notification-container', "The Group '$groupName' has been saved.");
1602 * @param string $activityType
1606 public function WebtestAddActivity($activityType = "Meeting") {
1607 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1608 // We're using Quick Add block on the main page for this.
1609 $firstName1 = substr(sha1(rand()), 0, 7);
1610 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1611 $firstName2 = substr(sha1(rand()), 0, 7);
1612 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1614 $this->click("css=li#tab_activity a");
1616 // waiting for the activity dropdown to show up
1617 $this->waitForElementPresent("other_activity");
1619 // Select the activity type from the activity dropdown
1620 $this->select("other_activity", "label=Meeting");
1622 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1623 $this->waitForElementPresent("s2id_target_contact_id");
1625 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__
);
1627 // Typing contact's name into the field (using typeKeys(), not type()!)...
1628 $this->select2("assignee_contact_id", $firstName1, TRUE);
1630 // ...and verifying if the page contains properly formatted display name for chosen contact.
1631 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__
);
1633 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1634 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1635 // For simple input fields we can use field id as selector
1636 $this->type("subject", $subject);
1637 $this->type("location", "Some location needs to be put in this field.");
1639 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1641 // Setting duration.
1642 $this->type("duration", "30");
1644 // Putting in details.
1645 $this->type("details", "Really brief details information.");
1647 // Making sure that status is set to Scheduled (using value, not label).
1648 $this->select("status_id", "value=1");
1650 // Setting priority.
1651 $this->select("priority_id", "value=1");
1653 // Scheduling follow-up.
1654 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1655 $this->select("followup_activity_type_id", "value=1");
1656 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1657 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1660 $this->click("_qf_Activity_upload-bottom");
1661 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1663 // Is status message correct?
1664 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1666 $this->waitForElementPresent("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1668 // click through to the Activity view screen
1669 $this->clickLinkSuppressPopup("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']", '_qf_Activity_cancel-bottom');
1671 // parse URL to grab the activity id
1672 // pass id back to any other tests that call this class
1673 return $this->urlArg('id');
1679 public static function checkDoLocalDBTest() {
1680 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1681 CIVICRM_WEBTEST_LOCAL_DB
1683 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1690 * Generic function to compare expected values after an api call to retrieved.
1693 * @param string $daoName
1694 * DAO Name of object we're evaluating.
1697 * @param array $match
1698 * Associative array of field name => expected value. Empty if asserting
1699 * that a DELETE occurred
1700 * @param bool $delete
1701 * are we checking that a DELETE action occurred?
1703 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
1704 if (self
::checkDoLocalDBTest()) {
1705 CiviDBAssert
::assertDBState($this, $daoName, $id, $match, $delete);
1710 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1711 * @param string $daoName
1712 * @param string $searchValue
1713 * @param string $returnColumn
1714 * @param string $searchColumn
1715 * @param string $message
1717 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1718 if (self
::checkDoLocalDBTest()) {
1719 CiviDBAssert
::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1724 * Request a record from the DB by searchColumn+searchValue. Success if returnColumn value is NULL.
1725 * @param string $daoName
1726 * @param string $searchValue
1727 * @param string $returnColumn
1728 * @param string $searchColumn
1729 * @param string $message
1731 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1732 if (self
::checkDoLocalDBTest()) {
1733 CiviDBAssert
::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1738 * Request a record from the DB by id. Success if row not found.
1739 * @param string $daoName
1741 * @param string $message
1743 public function assertDBRowNotExist($daoName, $id, $message) {
1744 if (self
::checkDoLocalDBTest()) {
1745 CiviDBAssert
::assertDBRowNotExist($this, $daoName, $id, $message);
1750 * Compare all values in a single retrieved DB record to an array of expected values.
1751 * @param string $daoName
1752 * @param array $searchParams
1753 * @param $expectedValues
1755 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1756 if (self
::checkDoLocalDBTest()) {
1757 CiviDBAssert
::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1764 * @param string $message
1766 public function assertType($expected, $actual, $message = '') {
1767 $this->assertInternalType($expected, $actual, $message);
1771 * Add new Financial Account.
1772 * @param $financialAccountTitle
1773 * @param bool $financialAccountDescription
1774 * @param bool $accountingCode
1775 * @param bool $firstName
1776 * @param bool $financialAccountType
1777 * @param bool $taxDeductible
1778 * @param bool $isActive
1779 * @param bool $isTax
1780 * @param bool $taxRate
1781 * @param bool $isDefault
1783 public function _testAddFinancialAccount(
1784 $financialAccountTitle,
1785 $financialAccountDescription = FALSE,
1786 $accountingCode = FALSE,
1788 $financialAccountType = FALSE,
1789 $taxDeductible = FALSE,
1796 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1798 $this->click("link=Add Financial Account");
1799 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1801 // Financial Account Name
1802 $this->type('name', $financialAccountTitle);
1804 // Financial Description
1805 if ($financialAccountDescription) {
1806 $this->type('description', $financialAccountDescription);
1810 if ($accountingCode) {
1811 $this->type('accounting_code', $accountingCode);
1814 // Autofill Organization
1816 $this->webtestOrganisationAutocomplete($firstName);
1819 // Financial Account Type
1820 if ($financialAccountType) {
1821 $this->select('financial_account_type_id', "label={$financialAccountType}");
1824 // Is Tax Deductible
1825 if ($taxDeductible) {
1826 $this->check('is_deductible');
1829 $this->uncheck('is_deductible');
1833 $this->check('is_active');
1836 $this->uncheck('is_active');
1840 $this->check('is_tax');
1843 $this->uncheck('is_tax');
1847 $this->type('tax_rate', $taxRate);
1852 $this->check('is_default');
1855 $this->uncheck('is_default');
1857 $this->click('_qf_FinancialAccount_next-botttom');
1861 * Edit Financial Account.
1862 * @param $editfinancialAccount
1863 * @param bool $financialAccountTitle
1864 * @param bool $financialAccountDescription
1865 * @param bool $accountingCode
1866 * @param bool $firstName
1867 * @param bool $financialAccountType
1868 * @param bool $taxDeductible
1869 * @param bool $isActive
1870 * @param bool $isTax
1871 * @param bool $taxRate
1872 * @param bool $isDefault
1874 public function _testEditFinancialAccount(
1875 $editfinancialAccount,
1876 $financialAccountTitle = FALSE,
1877 $financialAccountDescription = FALSE,
1878 $accountingCode = FALSE,
1880 $financialAccountType = FALSE,
1881 $taxDeductible = FALSE,
1888 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1891 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']");
1892 $this->clickLink("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1894 // Change Financial Account Name
1895 if ($financialAccountTitle) {
1896 $this->type('name', $financialAccountTitle);
1899 // Financial Description
1900 if ($financialAccountDescription) {
1901 $this->type('description', $financialAccountDescription);
1905 if ($accountingCode) {
1906 $this->type('accounting_code', $accountingCode);
1909 // Autofill Edit Organization
1911 $this->webtestOrganisationAutocomplete($firstName);
1914 // Financial Account Type
1915 if ($financialAccountType) {
1916 $this->select('financial_account_type_id', "label={$financialAccountType}");
1919 // Is Tax Deductible
1920 if ($taxDeductible) {
1921 $this->check('is_deductible');
1924 $this->uncheck('is_deductible');
1929 $this->check('is_tax');
1932 $this->uncheck('is_tax');
1937 $this->type('tax_rate', $taxRate);
1942 $this->check('is_default');
1945 $this->uncheck('is_default');
1950 $this->check('is_active');
1953 $this->uncheck('is_active');
1955 $this->click('_qf_FinancialAccount_next-botttom');
1956 $this->waitForElementPresent('link=Add Financial Account');
1960 * Delete Financial Account.
1961 * @param $financialAccountTitle
1963 public function _testDeleteFinancialAccount($financialAccountTitle) {
1964 $this->click("xpath=//table/tbody//tr/td[1]/div[text()='{$financialAccountTitle}']/../../td[9]/span/a[text()='Delete']");
1965 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1966 $this->click('_qf_FinancialAccount_next-botttom');
1967 $this->waitForElementPresent('link=Add Financial Account');
1968 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1972 * Verify data after ADD and EDIT.
1973 * @param $verifyData
1975 public function _assertFinancialAccount($verifyData) {
1976 foreach ($verifyData as $key => $expectedValue) {
1977 $actualValue = $this->getValue($key);
1978 if ($key == 'parent_financial_account') {
1979 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1982 $this->assertEquals($expectedValue, $actualValue);
1988 * @param $verifySelectFieldData
1990 public function _assertSelectVerify($verifySelectFieldData) {
1991 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1992 $actualvalue = $this->getSelectedLabel($key);
1993 $this->assertEquals($expectedvalue, $actualvalue);
1998 * @param $financialType
1999 * @param string $option
2001 public function addeditFinancialType($financialType, $option = 'new') {
2002 $this->openCiviPage("admin/financial/financialType", "reset=1");
2004 if ($option == 'Delete') {
2005 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]");
2006 $this->waitForElementPresent("css=span.btn-slide-active");
2007 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]/ul/li[2]/a");
2008 $this->waitForElementPresent("_qf_FinancialType_next");
2009 $this->click("_qf_FinancialType_next");
2010 $this->waitForElementPresent("newFinancialType");
2011 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
2014 if ($option == 'new') {
2015 $this->click("link=Add Financial Type");
2018 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[oldname]']/../../td[7]/span/a[text()='Edit']");
2020 $this->waitForElementPresent("name");
2021 $this->type('name', $financialType['name']);
2022 if ($option == 'new') {
2023 $this->type('description', $financialType['name'] . ' description');
2026 if ($financialType['is_reserved']) {
2027 $this->check('is_reserved');
2030 $this->uncheck('is_reserved');
2033 if ($financialType['is_deductible']) {
2034 $this->check('is_deductible');
2037 $this->uncheck('is_deductible');
2040 $this->click('_qf_FinancialType_next');
2041 if ($option == 'new') {
2042 $text = "Your Financial \"{$financialType['name']}\" Type has been created, along with a corresponding income account \"{$financialType['name']}\". That income account, along with standard financial accounts \"Accounts Receivable\", \"Banking Fees\" and \"Premiums\" have been linked to the financial type. You may edit or replace those relationships here.";
2045 $text = "The financial type \"{$financialType['name']}\" has been updated.";
2047 $this->checkCRMAlert($text);
2051 * Give the specified permissions.
2052 * Note: this function logs in as 'admin' (logging out if necessary)
2053 * @param $permission
2055 public function changePermissions($permission) {
2056 $this->webtestLogin('admin');
2057 $this->open("{$this->sboxPath}admin/people/permissions");
2058 $this->waitForElementPresent('edit-submit');
2059 foreach ((array) $permission as $perm) {
2060 $this->check($perm);
2062 $this->click('edit-submit');
2063 $this->waitForPageToLoad($this->getTimeoutMsec());
2064 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
2068 * @param $profileTitle
2069 * @param $profileFields
2071 public function addProfile($profileTitle, $profileFields) {
2072 $this->openCiviPage('admin/uf/group', "reset=1");
2074 $this->clickLink('link=Add Profile', '_qf_Group_cancel-bottom');
2075 $this->type('title', $profileTitle);
2076 $this->clickLink('_qf_Group_next-bottom');
2078 $this->waitForText('crm-notification-container', "Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now.");
2080 foreach ($profileFields as $field) {
2081 $this->waitForElementPresent('field_name_0');
2082 $this->click("id=field_name_0");
2083 $this->select("id=field_name_0", "label=" . $field['type']);
2084 $this->waitForElementPresent('field_name_1');
2085 $this->click("id=field_name_1");
2086 $this->select("id=field_name_1", "label=" . $field['name']);
2087 $this->waitForElementPresent('label');
2088 $this->type("id=label", $field['label']);
2089 $this->click("id=_qf_Field_next_new-top");
2090 $this->waitForElementPresent("xpath=//select[@id='field_name_1'][@style='display: none;']");
2091 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
2096 * @param string $name
2101 * @param $financialType
2103 public function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
2104 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
2105 $this->type("name", $name);
2106 $this->type("sku", $sku);
2107 $this->click("CIVICRM_QFID_noImage_16");
2108 $this->type("min_contribution", $amount);
2109 $this->type("price", $price);
2110 $this->type("cost", $cost);
2111 if ($financialType) {
2112 $this->select("financial_type_id", "label={$financialType}");
2114 $this->click("_qf_ManagePremiums_upload-bottom");
2115 $this->waitForPageToLoad($this->getTimeoutMsec());
2120 * @param $financialAccount
2122 public function addPaymentInstrument($label, $financialAccount) {
2123 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
2124 $this->type("label", $label);
2125 $this->type("value", "value" . $label);
2126 $this->select("financial_account_id", "value=$financialAccount");
2127 $this->click("_qf_Options_next-bottom");
2128 $this->waitForPageToLoad($this->getTimeoutMsec());
2132 * Ensure we have a default mailbox set up for CiviMail.
2134 public function setupDefaultMailbox() {
2135 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
2136 // Check if it hasn't already been set up
2137 if (!$this->getSelectedValue('protocol')) {
2138 $this->type('name', 'Test Domain');
2139 $this->select('protocol', "IMAP");
2140 $this->type('server', 'localhost');
2141 $this->type('domain', 'example.com');
2142 $this->clickLink('_qf_MailSettings_next-top');
2147 * Determine the default time-out in milliseconds.
2149 * @return string, timeout expressed in milliseconds
2151 public function getTimeoutMsec() {
2152 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
2153 $timeout = ($this->settings
&& @$this->settings
->timeout
) ?
($this->settings
->timeout
* 1000) : 30000;
2154 return (string) $timeout; // don't know why, but all our old code used a string
2159 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
2162 * @param array $customSets
2163 * Custom sets i.e entity wise sets want to be created and checked.
2164 * e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
2165 * 'triggerElement' => $triggerElement))
2166 * array $triggerElement: the element which is responsible for custom group to load
2168 * which uses the entity info as its selection value
2169 * @param array $pageUrl
2170 * The url which on which the ajax custom group load takes place.
2171 * @param string $beforeTriggering
2174 public function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
2175 // FIXME: Testing a theory that these failures have something to do with permissions
2176 $this->webtestLogin('admin');
2178 //add the custom set
2179 $return = $this->addCustomGroupField($customSets);
2181 // FIXME: Hack to ensure caches are properly cleared
2183 $userName = $this->loggedInAs
;
2184 $this->webtestLogout();
2185 $this->webtestLogin($userName);
2188 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
2190 // FIXME: Try to find out what the heck is going on with these tests
2191 $this->waitForAjaxContent();
2192 $this->checkForErrorsOnPage();
2194 foreach ($return as $values) {
2195 foreach ($values as $entityType => $customData) {
2196 //initiate necessary variables
2197 list($entity, $entityData) = explode('_', $entityType);
2198 $elementType = CRM_Utils_Array
::value('type', $customData['triggerElement'], 'select');
2199 $elementName = CRM_Utils_Array
::value('name', $customData['triggerElement']);
2200 if (is_callable($beforeTriggering)) {
2201 call_user_func($beforeTriggering);
2203 if ($elementType == 'select') {
2204 //reset the select box, so triggering of ajax only happens
2205 //WRT input of value in this function
2206 $this->select($elementName, "index=0");
2208 if (!empty($entityData)) {
2209 if ($elementType == 'select') {
2210 $this->select($elementName, "label=regexp:{$entityData}");
2212 elseif ($elementType == 'checkbox') {
2213 $val = explode(',', $entityData);
2214 foreach ($val as $v) {
2215 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2216 $this->check($checkId);
2219 elseif ($elementType == 'select2') {
2220 $this->select2($elementName, $entityData);
2223 // FIXME: Try to find out what the heck is going on with these tests
2224 $this->waitForAjaxContent();
2225 $this->checkForErrorsOnPage();
2227 //checking for proper custom data which is loading through ajax
2228 $this->waitForElementPresent("css=.custom-group-{$customData['cgtitle']}");
2229 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2230 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2236 * @param $customSets
2240 public function addCustomGroupField($customSets) {
2242 foreach ($customSets as $customSet) {
2243 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2245 //fill custom group title
2246 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2247 $this->click("title");
2248 $this->type("title", $customGroupTitle);
2250 //custom group extends
2251 $this->click("extends_0");
2252 $this->select("extends_0", "value={$customSet['entity']}");
2253 if (!empty($customSet['subEntity'])) {
2254 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2258 $this->uncheck('collapse_display');
2261 $this->click('_qf_Group_next-bottom');
2263 //Is custom group created?
2264 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2266 $gid = $this->urlArg('gid');
2267 $this->waitForTextPresent("{$customGroupTitle} - New Field");
2269 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2270 $this->waitForElementPresent('label');
2271 $this->type('label', $fieldLabel);
2272 $this->click('_qf_Field_done-bottom');
2274 $this->waitForText('crm-notification-container', $fieldLabel);
2275 $this->waitForAjaxContent();
2277 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2279 "{$customSet['entity']}_{$customSet['subEntity']}" => array(
2280 'cgtitle' => $customGroupTitle,
2282 'triggerElement' => $customSet['triggerElement'],
2286 // Go home for a sec to give time for caches to clear
2287 $this->openCiviPage('');
2293 * Type and select first occurrence of autocomplete.
2296 * @param string $labels
2297 * @param bool $multiple
2298 * @param bool $xpath
2300 public function select2($fieldName, $labels, $multiple = FALSE, $xpath = FALSE) {
2301 // In the case of chainSelect, wait for options to load
2302 $this->waitForElementNotPresent('css=select.loading');
2304 foreach ((array) $labels as $label) {
2305 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2306 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2307 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2308 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2309 $this->waitForElementPresent("//*[@class='select2-result-label']");
2310 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2315 $this->clickAt($fieldName);
2318 $this->clickAt("//*[@id='$fieldName']/../div/a");
2320 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2321 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2322 $this->type("//*[@id='select2-drop']/div/input", $labels);
2323 $this->typeKeys("//*[@id='select2-drop']/div/input", $labels);
2324 $this->waitForElementPresent("//*[@class='select2-result-label']");
2325 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2327 // Wait a sec for select2 to update the original element
2332 * Select multiple options.
2335 * @param $isDate if multiple date is to be selected from datepicker
2337 public function multiselect2($fieldId, $options, $isDate = FALSE) {
2338 // In the case of chainSelect, wait for options to load
2339 $this->waitForElementNotPresent('css=select.loading');
2340 foreach ($options as $value) {
2342 $this->clickAt("xpath=//*[@id='$fieldId']/../div/ul//li/input");
2343 $this->webtestFillDate($fieldId, $value, TRUE);
2346 $this->clickAt("xpath=//*[@id='$fieldId']/../div/ul//li/input");
2347 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2348 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2349 $this->assertElementContainsText("xpath=//*[@id='$fieldId']/preceding-sibling::div[1]/", $value);
2352 // Wait a sec for select2 to update the original element
2357 * Check for unobtrusive status message as set by CRM.status
2360 public function checkCRMStatus($text = NULL) {
2361 $this->waitForElementPresent("css=.crm-status-box-outer.status-success");
2363 $this->assertElementContainsText("css=.crm-status-box-outer.status-success", $text);
2368 * Check for obtrusive status message as set by CRM.alert
2370 * @param string $type
2372 public function checkCRMAlert($text, $type = 'success') {
2373 $this->waitForElementPresent("css=div.ui-notify-message.$type");
2374 $this->waitForText("css=div.ui-notify-message.$type", $text);
2375 // We got the message, now let's close it so the webtest doesn't get confused by lots of open alerts
2376 $this->click('css=.ui-notify-cross');
2380 * Enable or disable Pop-ups via Display Preferences
2381 * @param bool $enabled
2383 public function enableDisablePopups($enabled = TRUE) {
2384 $this->openCiviPage('admin/setting/preferences/display', 'reset=1');
2385 $isChecked = $this->isChecked('ajaxPopupsEnabled');
2386 if (($isChecked && !$enabled) ||
(!$isChecked && $enabled)) {
2387 $this->click('ajaxPopupsEnabled');
2390 $this->assertChecked('ajaxPopupsEnabled');
2393 $this->assertNotChecked('ajaxPopupsEnabled');
2395 $this->clickLink("_qf_Display_next-bottom");
2399 * Attempt to get information about what went wrong if we encounter an error when loading a page.
2401 public function checkForErrorsOnPage() {
2402 foreach (array('Access denied', 'Page not found') as $err) {
2403 if ($this->isElementPresent("xpath=//h1[contains(., '$err')]")) {
2404 $this->fail("'$err' encountered at " . $this->getLocation() . "\nwhile logged in as '{$this->loggedInAs}'");
2407 if ($this->isElementPresent("xpath=//span[text()='Sorry but we are not able to provide this at the moment.']")) {
2408 $msg = '"Fatal Error" encountered at ' . $this->getLocation();
2409 if ($this->isElementPresent('css=div.crm-section.crm-error-message')) {
2410 $msg .= "\nError Message: " . $this->getText('css=div.crm-section.crm-error-message');
2418 * Contact record (per APIv3).
2420 public function webtestGetLoggedInContact() {
2421 $result = $this->rest_civicrm_api('Contact', 'get', array(
2422 'id' => 'user_contact_id',
2424 $this->assertAPISuccess($result, 'Load logged-in contact');
2425 return CRM_Utils_Array
::first($result['values']);
2428 public function assertAPISuccess($apiResult, $prefix = '') {
2429 if (!empty($prefix)) {
2432 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
2434 if (!empty($apiResult['debug_information'])) {
2435 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
2437 if (!empty($apiResult['trace'])) {
2438 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
2440 $this->assertFalse(civicrm_error($apiResult), $prefix . $errorMessage);
2441 //$this->assertEquals(0, $apiResult['is_error']);
2449 public function webtestStandalonePledgeAdd() {
2450 $this->webtestLogin();
2452 $this->openCiviPage('pledge/add', 'reset=1&context=standalone', '_qf_Pledge_upload');
2454 // create new contact using dialog
2455 $contact = $this->createDialogContact();
2457 $this->type('amount', '100');
2458 $this->type('installments', '10');
2459 $this->select('frequency_unit', 'value=week');
2460 $this->type('frequency_day', '2');
2462 $this->webtestFillDate('acknowledge_date', 'now');
2463 $this->waitForElementPresent('contribution_page_id');
2464 $this->select('contribution_page_id', 'value=3');
2465 $this->waitForAjaxContent();
2468 $this->click('PaymentReminders');
2469 $this->waitForElementPresent('additional_reminder_day');
2470 $this->type('initial_reminder_day', '4');
2471 $this->type('max_reminders', '2');
2472 $this->type('additional_reminder_day', '4');
2474 $this->click('_qf_Pledge_upload-bottom');
2476 $this->waitForText('crm-notification-container', "Pledge has been recorded and the payment schedule has been created.");
2478 // verify if Pledge is created
2479 $this->waitForElementPresent("xpath=//div[@class='view-content']//table//tbody/tr[1]/td[10]/span/a[text()='View']");
2481 //click through to the Pledge view screen
2482 $this->click("xpath=//div[@class='view-content']//table//tbody/tr[1]/td[10]/span/a[text()='View']");
2483 $this->waitForElementPresent('_qf_PledgeView_next-bottom');
2484 $pledgeDate = date('F jS, Y', strtotime('now'));
2486 $this->webtestVerifyTabularData(array(
2487 'Pledge By' => $contact['display_name'],
2488 'Total Pledge Amount' => '$ 100.00',
2489 'To be paid in' => '10 installments of $ 10.00 every 1 week(s)',
2490 'Payments are due on the' => '2 day of the period',
2491 'Pledge Made' => $pledgeDate,
2492 'Financial Type' => 'Donation',
2493 'Pledge Status' => 'Pending',
2494 'Initial Reminder Day' => '4 days prior to schedule date',
2495 'Maximum Reminders Send' => 2,
2496 'Send additional reminders' => '4 days after the last one sent',
2499 $this->clickLink('_qf_PledgeView_next-bottom', "xpath=//div[@class='view-content']//table[@class='selector row-highlight']//tbody/tr[1]/td[1]/a", FALSE);
2500 $this->waitForAjaxContent();
2501 $this->click("xpath=//div[@class='view-content']//table[@class='selector row-highlight']//tbody/tr[1]/td[1]/a");
2502 $this->waitForElementPresent("xpath=//div[@class='view-content']//table//tbody/tr[2]/td/div/table/tbody/tr[2]/td[8]/a[text()='Record Payment']");
2507 * Add a contact via profile
2509 public function webtestAddViaCreateProfile() {
2510 $this->webtestLogin();
2512 $this->openCiviPage('profile/create', 'reset=1&gid=1', '_qf_Edit_next');
2514 $firstName = 'Jo' . substr(sha1(rand()), 0, 4);
2515 $lastName = 'Ad' . substr(sha1(rand()), 0, 7);
2517 //contact details section
2518 //fill in first name
2519 $this->type("first_name", $firstName);
2522 $this->type("last_name", $lastName);
2525 $this->waitForElementPresent('street_address-1');
2526 $this->type("street_address-1", "902C El Camino Way SW");
2527 $this->waitForElementPresent('city-1');
2528 $this->type("city-1", "Dumfries");
2529 $this->type("postal_code-1", "1234");
2530 $this->assertSelected('country-1', "UNITED STATES");
2531 $this->select("state_province-1", "value=1019");
2534 $this->click("_qf_Edit_next");
2535 $this->waitForPageToLoad($this->getTimeoutMsec());
2537 $this->assertElementContainsText('css=.msg-text', "Your information has been saved.");