3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
29 * Include configuration
31 define('CIVICRM_SETTINGS_PATH', __DIR__
. '/civicrm.settings.dist.php');
32 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__
. '/civicrm.settings.local.php');
33 define('CIVICRM_WEBTEST', 1);
35 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH
)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH
;
38 require_once CIVICRM_SETTINGS_PATH
;
41 * Base class for CiviCRM Selenium tests
43 * Common functions for unit tests
46 class CiviSeleniumTestCase
extends PHPUnit_Extensions_SeleniumTestCase
{
48 // Current logged-in user
49 protected $loggedInAs = NULL;
54 * Because we are overriding the parent class constructor, we
55 * need to show the same arguments as exist in the constructor of
56 * PHPUnit_Framework_TestCase, since
57 * PHPUnit_Framework_TestSuite::createTest() creates a
58 * ReflectionClass of the Test class and checks the constructor
59 * of that class to decide how to set up the test.
63 * @param string $dataName
64 * @param array $browser
66 public function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
67 parent
::__construct($name, $data, $dataName, $browser);
68 $this->loggedInAs
= NULL;
70 require_once 'CiviSeleniumSettings.php';
71 $this->settings
= new CiviSeleniumSettings();
72 if (property_exists($this->settings
, 'serverStartupTimeOut') && $this->settings
->serverStartupTimeOut
) {
73 global $CiviSeleniumTestCase_polled;
74 if (!$CiviSeleniumTestCase_polled) {
75 $CiviSeleniumTestCase_polled = TRUE;
76 CRM_Utils_Network
::waitForServiceStartup(
77 $this->drivers
[0]->getHost(),
78 $this->drivers
[0]->getPort(),
79 $this->settings
->serverStartupTimeOut
85 require_once 'CRM/Core/ClassLoader.php';
86 CRM_Core_ClassLoader
::singleton()->register();
88 // also initialize a connection to the db
89 // FIXME: not necessary for most tests, consider moving into functions that need this
90 $config = CRM_Core_Config
::singleton();
93 protected function setUp() {
94 $this->setBrowser($this->settings
->browser
);
95 // Make sure that below strings have path separator at the end
96 $this->setBrowserUrl($this->settings
->sandboxURL
);
97 $this->sboxPath
= $this->settings
->sandboxPATH
;
98 if (property_exists($this->settings
, 'rcHost') && $this->settings
->rcHost
) {
99 $this->setHost($this->settings
->rcHost
);
101 if (property_exists($this->settings
, 'rcPort') && $this->settings
->rcPort
) {
102 $this->setPort($this->settings
->rcPort
);
106 protected function prepareTestSession() {
107 $result = parent
::prepareTestSession();
109 // Set any cookies required by local installation
110 // Note: considered doing this in setUp(), but the Selenium session wasn't yet initialized.
111 if (property_exists($this->settings
, 'cookies')) {
112 // We don't really care about this page, but it seems we need
113 // to open a page before setting a cookie.
114 $this->open($this->sboxPath
);
115 $this->waitForPageToLoad($this->getTimeoutMsec());
116 $this->setCookies($this->settings
->cookies
);
122 * @param array $cookies
123 * Each item is an Array with keys:
125 * - value: string; note that RFC's don't define particular encoding scheme, so
126 * you must pick one yourself and pre-encode; does not allow values with
127 * commas, semicolons, or whitespace
128 * - path: string; default: '/'
129 * - max_age: int; default: 1 week (7*24*60*60)
131 protected function setCookies($cookies) {
132 foreach ($cookies as $cookie) {
133 if (!isset($cookie['path'])) {
134 $cookie['path'] = '/';
136 if (!isset($cookie['max_age'])) {
137 $cookie['max_age'] = 7 * 24 * 60 * 60;
139 $this->deleteCookie($cookie['name'], $cookie['path']);
140 $optionExprs = array();
141 foreach ($cookie as $key => $value) {
142 if ($key != 'name' && $key != 'value') {
143 $optionExprs[] = "$key=$value";
146 $this->createCookie("{$cookie['name']}={$cookie['value']}", implode(', ', $optionExprs));
150 protected function tearDown() {
154 * Authenticate as drupal user
155 * @param $user : (str) the key 'user' or 'admin', or a literal username
156 * @param $pass : (str) if $user is a literal username and not 'user' or 'admin', supply the password
158 public function webtestLogin($user = 'user', $pass = NULL) {
159 // If already logged in as correct user, do nothing
160 if ($this->loggedInAs
=== $user) {
163 // If we are logged in as a different user, log out first
164 if ($this->loggedInAs
) {
165 $this->webtestLogout();
167 $this->open("{$this->sboxPath}user");
168 // Lookup username & password if not supplied
170 if ($pass === NULL) {
171 $pass = $user == 'admin' ?
$this->settings
->adminPassword
: $this->settings
->password
;
172 $username = $user == 'admin' ?
$this->settings
->adminUsername
: $this->settings
->username
;
174 // Make sure login form is available
175 $this->waitForElementPresent('edit-submit');
176 $this->type('edit-name', $username);
177 $this->type('edit-pass', $pass);
178 $this->click('edit-submit');
179 $this->waitForPageToLoad($this->getTimeoutMsec());
180 $this->loggedInAs
= $user;
183 public function webtestLogout() {
184 if ($this->loggedInAs
) {
185 $this->open($this->sboxPath
. "user/logout");
186 $this->waitForPageToLoad($this->getTimeoutMsec());
188 $this->loggedInAs
= NULL;
192 * Open an internal path beginning with 'civicrm/'
195 * omit the 'civicrm/' it will be added for you.
196 * @param string|array $args
197 * optional url arguments.
199 * Page element to wait for - using this is recommended to ensure the document is fully loaded.
201 * Although it doesn't seem to do much now, using this function is recommended for
202 * opening all civi pages, and using the $args param is also strongly encouraged
203 * This will make it much easier to run webtests in other CMSs in the future
205 public function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
206 // Construct full url with args
207 // This could be extended in future to work with other CMS style urls
209 if (is_array($args)) {
211 foreach ($args as $key => $val) {
212 $url .= $sep . $key . '=' . $val;
220 $this->open("{$this->sboxPath}civicrm/$url");
221 $this->waitForPageToLoad($this->getTimeoutMsec());
222 $this->checkForErrorsOnPage();
224 $this->waitForElementPresent($waitFor);
229 * Click on a link or button
230 * Wait for the page to load
231 * Wait for an element to be present
233 * @param string $waitFor
234 * @param bool $waitForPageLoad
236 public function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
237 $this->click($element);
238 // conditional wait for page load e.g for ajax form save
239 if ($waitForPageLoad) {
240 $this->waitForPageToLoad($this->getTimeoutMsec());
241 $this->checkForErrorsOnPage();
244 $this->waitForElementPresent($waitFor);
249 * Click a link or button and wait for an ajax dialog to load
250 * @param string $element
251 * @param string $waitFor
253 public function clickPopupLink($element, $waitFor = NULL) {
254 $this->clickAjaxLink($element, 'css=.ui-dialog');
256 $this->waitForElementPresent($waitFor);
261 * Click a link or button and wait for ajax content to load or refresh
262 * @param string $element
263 * @param string $waitFor
265 public function clickAjaxLink($element, $waitFor = NULL) {
266 $this->click($element);
268 $this->waitForElementPresent($waitFor);
270 $this->waitForAjaxContent();
274 * Force a link to open full-page, even if it would normally open in a popup
275 * @note: works with links only, not buttons
276 * @param string $element
277 * @param string $waitFor
279 public function clickLinkSuppressPopup($element, $waitFor = 'civicrm-footer') {
280 $link = $this->getAttribute($element . '@href');
282 $this->waitForPageToLoad($this->getTimeoutMsec());
284 $this->waitForElementPresent($waitFor);
289 * Wait for all ajax snippets to finish loading
291 public function waitForAjaxContent() {
292 $this->waitForElementNotPresent('css=.blockOverlay');
293 // Some ajax calls happen in pairs (e.g. submit a popup form then refresh the underlying content)
294 // So we'll wait a sec and recheck to see if any more stuff is loading
296 if ($this->isElementPresent('css=.blockOverlay')) {
297 $this->waitForAjaxContent();
302 * Call the API on the local server
303 * (kind of defeats the point of a webtest - see CRM-11889)
309 public function webtest_civicrm_api($entity, $action, $params) {
310 if (!isset($params['version'])) {
311 $params['version'] = 3;
314 $result = civicrm_api($entity, $action, $params);
315 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
320 * Call the API on the remote server
321 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
325 * @param array $params
328 public function rest_civicrm_api($entity, $action, $params = array()) {
332 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
336 // Naughty sidestep of civi's security checks
337 'header' => "X-Requested-With: XMLHttpRequest",
340 $ctx = stream_context_create($request);
341 $result = file_get_contents($url, FALSE, $ctx);
342 return json_decode($result, TRUE);
346 * @param string $option_group_name
350 public function webtestGetFirstValueForOptionGroup($option_group_name) {
351 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
352 'option_group_name' => $option_group_name,
362 public function webtestGetValidCountryID() {
364 if (is_null($_country_id)) {
365 $config_backend = $this->webtestGetConfig('countryLimit');
366 $_country_id = current($config_backend);
376 public function webtestGetValidEntityID($entity) {
377 // michaelmcandrew: would like to use getvalue but there is a bug
378 // for e.g. group where option.limit not working at the moment CRM-9110
379 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
380 if (!empty($result['values'])) {
381 return current(array_keys($result['values']));
391 public function webtestGetConfig($field) {
392 static $_config_backend;
393 if (is_null($_config_backend)) {
394 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
395 'current_domain' => 1,
397 'return' => 'config_backend',
399 $_config_backend = unserialize($result);
401 return $_config_backend[$field];
405 * Ensures the required CiviCRM components are enabled
408 public function enableComponents($components) {
409 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
410 $enabledComponents = $this->getSelectOptions("enableComponents-t");
412 foreach ((array) $components as $comp) {
413 if (!in_array($comp, $enabledComponents)) {
414 $this->addSelection("enableComponents-f", "label=$comp");
415 $this->click("//option[@value='$comp']");
421 $this->clickLink("_qf_Component_next-bottom");
422 $this->checkCRMAlert("Saved");
427 * Add a contact with the given first and last names and either a given email
428 * (when specified), a random email (when true) or no email (when unspecified or null).
430 * @param string $fname
431 * Contact’s first name.
432 * @param string $lname
433 * Contact’s last name.
434 * @param mixed $email
435 * Contact’s email (when string) or random email (when true) or no email (when null).
436 * @param string $contactSubtype
438 * @return string|null
439 * either a string with the (either generated or provided) email or null (if no email)
441 public function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
442 $args = 'reset=1&ct=Individual';
443 if ($contactSubtype) {
444 $args .= "&cst={$contactSubtype}";
446 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
447 $this->type('first_name', $fname);
448 $this->type('last_name', $lname);
449 if ($email === TRUE) {
450 $email = substr(sha1(rand()), 0, 7) . '@example.org';
453 $this->type('email_1_email', $email);
455 $this->clickLink('_qf_Contact_upload_view-bottom');
460 * @param string $householdName
463 * @return null|string
465 public function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
466 $this->openCiviPage("contact/add", "reset=1&ct=Household");
467 $this->click('household_name');
468 $this->type('household_name', $householdName);
470 if ($email === TRUE) {
471 $email = substr(sha1(rand()), 0, 7) . '@example.org';
474 $this->type('email_1_email', $email);
477 $this->clickLink('_qf_Contact_upload_view');
482 * @param string $organizationName
484 * @param null $contactSubtype
486 * @return null|string
488 public function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
489 $args = 'reset=1&ct=Organization';
490 if ($contactSubtype) {
491 $args .= "&cst={$contactSubtype}";
493 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
494 $this->click('organization_name');
495 $this->type('organization_name', $organizationName);
497 if ($email === TRUE) {
498 $email = substr(sha1(rand()), 0, 7) . '@example.org';
501 $this->type('email_1_email', $email);
503 $this->clickLink('_qf_Contact_upload_view');
509 * @param string $fieldName
511 public function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
512 $this->select2($fieldName, $sortName);
513 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
519 public function webtestOrganisationAutocomplete($sortName) {
520 $this->clickAt("//*[@id='contact_id']/../div/a");
521 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
522 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
523 $this->type("//*[@id='select2-drop']/div/input", $sortName);
524 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
525 $this->waitForElementPresent("//*[@class='select2-result-label']");
526 $this->clickAt("//*[@class='select2-results']/li[1]");
527 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
531 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
532 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
533 * 3. Examples of $strToTime arguments -
534 * webtestFillDate('start_date',"now")
535 * webtestFillDate('start_date',"10 September 2000")
536 * webtestFillDate('start_date',"+1 day")
537 * webtestFillDate('start_date',"+1 week")
538 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
539 * webtestFillDate('start_date',"next Thursday")
540 * webtestFillDate('start_date',"last Monday")
541 * @param $dateElement
542 * @param null $strToTimeArgs
544 public function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
545 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
547 $year = date('Y', $timeStamp);
548 // -1 ensures month number is inline with calender widget's month
549 $mon = date('n', $timeStamp) - 1;
550 $day = date('j', $timeStamp);
552 $this->click("{$dateElement}_display");
553 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
554 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
555 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
556 $this->click("link=$day");
560 * 1. set both date and time.
561 * @param $dateElement
562 * @param null $strToTimeArgs
564 public function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
565 $this->webtestFillDate($dateElement, $strToTimeArgs);
567 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
568 $hour = date('h', $timeStamp);
569 $min = date('i', $timeStamp);
570 $meri = date('A', $timeStamp);
572 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
576 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
578 * @param array $expected
579 * Array of key/value pairs (like Status/Registered) to be checked.
580 * @param string $xpathPrefix
581 * Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath.
582 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
583 * @param string $tableId
584 * Pass in the id attribute of a table to be verified if you want to only check a specific table.
587 public function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
590 $tableLocator = "[@id='$tableId']";
592 foreach ($expected as $label => $value) {
594 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
595 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
598 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
599 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
605 * Types text into a ckEditor rich text field in a form
607 * @param string $fieldName
608 * Form field name (as assigned by PHP buildForm class).
609 * @param string $text
610 * Text to type into the field.
611 * @param string $editor
612 * Which text editor (valid values are 'CKEditor', 'TinyMCE').
614 * @param bool $compressed
615 * @throws \PHPUnit_Framework_AssertionFailedError
617 public function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor', $compressed = FALSE) {
618 // make sure cursor focuses on the field
619 $this->fireEvent($fieldName, 'focus');
620 if ($editor == 'CKEditor') {
622 $this->click("{$fieldName}-plain");
624 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
625 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
627 elseif ($editor == 'TinyMCE') {
628 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
629 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
632 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
634 $this->selectFrame('relative=top');
638 * Types option label and name into a table of multiple choice options
639 * (for price set fields of type select, radio, or checkbox)
640 * TODO: extend for custom field multiple choice table input
642 * @param array $options
643 * Form field name (as assigned by PHP buildForm class).
644 * @param array $validateStrings
645 * Appends label and name strings to this array so they can be validated later.
649 public function addMultipleChoiceOptions($options, &$validateStrings) {
650 foreach ($options as $oIndex => $oValue) {
651 $validateStrings[] = $oValue['label'];
652 $validateStrings[] = $oValue['amount'];
653 if (!empty($oValue['membership_type_id'])) {
654 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
656 if (!empty($oValue['financial_type_id'])) {
657 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
659 $this->type("option_label_{$oIndex}", $oValue['label']);
660 $this->type("option_amount_{$oIndex}", $oValue['amount']);
661 $this->click('link=another choice');
666 * Use a contact EntityRef field to add a new contact
667 * @param string $field
669 * @param string $contactType
671 * Array of contact attributes (id, names, email)
673 public function createDialogContact($field = 'contact_id', $contactType = 'Individual') {
674 $selectId = 's2id_' . $this->getAttribute($field . '@id');
675 $this->clickAt("xpath=//div[@id='$selectId']/a");
676 $this->clickAjaxLink("xpath=//li[@class='select2-no-results']//a[contains(text(), 'New $contactType')]", '_qf_Edit_next');
678 $name = substr(sha1(rand()), 0, rand(6, 8));
680 if ($contactType == 'Individual') {
681 $params['first_name'] = "$name $contactType";
682 $params['last_name'] = substr(sha1(rand()), 0, rand(5, 9));
685 $params[strtolower($contactType) . '_name'] = "$name $contactType";
687 foreach ($params as $param => $val) {
688 $this->type($param, $val);
690 $this->type('email-Primary', $params['email'] = "{$name}@example.com");
691 $this->clickAjaxLink('_qf_Edit_next');
693 $this->waitForText("xpath=//div[@id='$selectId']", "$name");
695 $params['sort_name'] = $contactType == 'Individual' ?
$params['last_name'] . ', ' . $params['first_name'] : "$name $contactType";
696 $params['display_name'] = $contactType == 'Individual' ?
$params['first_name'] . ' ' . $params['last_name'] : $params['sort_name'];
697 $params['id'] = $this->getValue($field);
702 * @deprecated in favor of createDialogContact
703 * @param string $fname
704 * @param string $lname
705 * @param string $email
707 * @param string $selectId
709 * @param string $prefix
711 public function webtestNewDialogContact(
712 $fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
713 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
714 // 4 - Individual profile
715 // 5 - Organization profile
716 // 6 - Household profile
717 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
718 $this->clickAt("xpath=//div[@id='$selectId']/a");
719 $this->clickPopupLink("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]", '_qf_Edit_next');
723 $this->type('first_name', $fname);
724 $this->type('last_name', $lname);
728 $this->type('organization_name', $fname);
732 $this->type('household_name', $fname);
736 $this->type('email-Primary', $email);
737 $this->clickAjaxLink('_qf_Edit_next');
739 // Is new contact created?
741 $this->waitForText("xpath=//div[@id='$selectId']", "$lname, $fname");
744 $this->waitForText("xpath=//div[@id='$selectId']", "$fname");
749 * Generic function to check that strings are present in the page
751 * @strings array array of strings or a single string
756 public function assertStringsPresent($strings) {
757 foreach ((array) $strings as $string) {
758 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
763 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
765 * @url string url to parse or retrieve current url if null
769 * returns an associative array containing any of the various components
770 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
771 * http://php.net/manual/en/function.parse-url.php
773 public function parseURL($url = NULL) {
775 $url = $this->getLocation();
778 $elements = parse_url($url);
779 if (!empty($elements['query'])) {
780 $elements['queryString'] = array();
781 parse_str($elements['query'], $elements['queryString']);
787 * Returns a single argument from the url query
792 public function urlArg($arg, $url = NULL) {
793 $elements = $this->parseURL($url);
794 return isset($elements['queryString'][$arg]) ?
$elements['queryString'][$arg] : NULL;
798 * Define a payment processor for use by a webtest. Default is to create Dummy processor
799 * which is useful for testing online public forms (online contribution pages and event registration)
801 * @param string $processorName
802 * Name assigned to new processor.
803 * @param string $processorType
804 * Name for processor type (e.g. PayPal, Dummy, etc.).
805 * @param array $processorSettings
806 * Array of fieldname => value for required settings for the processor.
808 * @param string $financialAccount
809 * @throws PHPUnit_Framework_AssertionFailedError
812 public function webtestAddPaymentProcessor($processorName = 'Test Processor', $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
813 if (!$processorName) {
814 $this->fail("webTestAddPaymentProcessor requires $processorName.");
816 // Ensure we are logged in as admin before we proceed
817 $this->webtestLogin('admin');
819 if ($processorName === 'Test Processor') {
820 // Use the default test processor, no need to create a new one
821 $this->openCiviPage('admin/paymentProcessor', 'action=update&id=1&reset=1', '_qf_PaymentProcessor_cancel-bottom');
822 $this->check('is_default');
823 $this->select('financial_account_id', "label={$financialAccount}");
824 $this->clickLink('_qf_PaymentProcessor_next-bottom');
828 if ($processorType == 'Dummy') {
829 $processorSettings = array(
830 'user_name' => 'dummy',
831 'url_site' => 'http://dummy.com',
832 'test_user_name' => 'dummytest',
833 'test_url_site' => 'http://dummytest.com',
836 elseif ($processorType == 'AuthNet') {
837 // FIXME: we 'll need to make a new separate account for testing
838 $processorSettings = array(
839 'test_user_name' => '5ULu56ex',
840 'test_password' => '7ARxW575w736eF5p',
843 elseif ($processorType == 'Google_Checkout') {
844 // FIXME: we 'll need to make a new separate account for testing
845 $processorSettings = array(
846 'test_user_name' => '559999327053114',
847 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
850 elseif ($processorType == 'PayPal') {
851 $processorSettings = array(
852 'test_user_name' => '559999327053114',
853 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
854 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
857 elseif ($processorType == 'PayPal_Standard') {
858 $processorSettings = array(
859 'test_user_name' => 'V18ki@9r5Bf.org',
862 elseif (empty($processorSettings)) {
863 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
865 $pid = CRM_Core_DAO
::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
867 $this->fail("$processorType processortype not found.");
869 $this->openCiviPage('admin/paymentProcessor', 'action=add&reset=1&pp=' . $pid, 'name');
870 $this->type('name', $processorName);
871 $this->select('financial_account_id', "label={$financialAccount}");
872 foreach ($processorSettings as $f => $v) {
877 $this->clickLink('_qf_PaymentProcessor_next-bottom');
879 $this->waitForTextPresent($processorName);
881 // Get payment processor id
882 $paymentProcessorLink = $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href");
883 return $this->urlArg('id', $paymentProcessorLink);
886 public function webtestAddCreditCardDetails() {
887 $this->waitForElementPresent('credit_card_type');
888 $this->select('credit_card_type', 'label=Visa');
889 $this->type('credit_card_number', '4807731747657838');
890 $this->type('cvv2', '123');
891 $this->select('credit_card_exp_date[M]', 'label=Feb');
892 $this->select('credit_card_exp_date[Y]', 'label=2019');
896 * @param null $firstName
897 * @param null $middleName
898 * @param null $lastName
902 public function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
908 $middleName = 'Apple';
912 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
915 $this->type('billing_first_name', $firstName);
916 $this->type('billing_middle_name', $middleName);
917 $this->type('billing_last_name', $lastName);
919 $this->type('billing_street_address-5', '234 Lincoln Ave');
920 $this->type('billing_city-5', 'San Bernadino');
921 $this->select2('billing_country_id-5', 'United States');
922 $this->select2('billing_state_province_id-5', 'California');
923 $this->type('billing_postal_code-5', '93245');
925 return array($firstName, $middleName, $lastName);
929 * @param $fieldLocator
930 * @param null $filePath
932 * @return null|string
934 public function webtestAttachFile($fieldLocator, $filePath = NULL) {
936 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
937 $fp = @fopen
($filePath, 'w');
938 fwrite($fp, 'Test file created by selenium test.');
942 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
944 $this->attachFile($fieldLocator, "file://{$filePath}");
952 * @param null $filePath
954 * @return null|string
956 public function webtestCreateCSV($headers, $rows, $filePath = NULL) {
958 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
961 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
963 foreach ($rows as $row) {
965 foreach ($headers as $field => $header) {
966 $temp[$field] = isset($row[$field]) ?
'"' . $row[$field] . '"' : '""';
968 $data .= implode(', ', $temp) . "\r\n";
971 $fp = @fopen
($filePath, 'w');
975 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
981 * Create new relationship type w/ user specified params or default.
983 * @param array $params
984 * array of required params.
987 * array of saved params values.
989 public function webtestAddRelationshipType($params = array()) {
990 $this->openCiviPage("admin/reltype", "reset=1&action=add");
992 //build the params if not passed.
993 if (!is_array($params) ||
empty($params)) {
995 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
996 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
997 'contact_types_a' => 'Individual',
998 'contact_types_b' => 'Individual',
999 'description' => 'Test Relationship Type Description',
1002 //make sure we have minimum required params.
1003 if (!isset($params['label_a_b']) ||
empty($params['label_a_b'])) {
1004 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
1007 //start the form fill.
1008 $this->type('label_a_b', $params['label_a_b']);
1009 $this->type('label_b_a', $params['label_b_a']);
1010 $this->select('contact_types_a', "value={$params['contact_type_a']}");
1011 $this->select('contact_types_b', "value={$params['contact_type_b']}");
1012 $this->type('description', $params['description']);
1015 $this->click('_qf_RelationshipType_next-bottom');
1016 $this->waitForPageToLoad($this->getTimeoutMsec());
1019 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
1020 "Status message didn't show up after saving!"
1023 $this->openCiviPage("admin/reltype", "reset=1");
1025 //validate data on selector.
1027 if (isset($data['description'])) {
1028 unset($data['description']);
1030 $this->assertStringsPresent($data);
1036 * Create new online contribution page w/ user specified params or defaults.
1037 * FIXME: this function take an absurd number of params - very unwieldy :(
1041 * @param null $pageTitle
1042 * @param array $processor
1043 * @param bool $amountSection
1044 * @param bool $payLater
1045 * @param bool $onBehalf
1046 * @param bool $pledges
1047 * @param bool $recurring
1048 * @param bool $membershipTypes
1049 * @param int $memPriceSetId
1050 * @param bool $friend
1051 * @param int $profilePreId
1052 * @param int $profilePostId
1053 * @param bool $premiums
1054 * @param bool $widget
1056 * @param bool $isAddPaymentProcessor
1057 * @param bool $isPcpApprovalNeeded
1058 * @param bool $isSeparatePayment
1059 * @param bool $honoreeSection
1060 * @param bool $allowOtherAmount
1061 * @param bool $isConfirmEnabled
1062 * @param string $financialType
1063 * @param bool $fixedAmount
1064 * @param bool $membershipsRequired
1067 * of newly created online contribution page.
1069 public function webtestAddContributionPage(
1073 $processor = array('Test Processor' => 'Dummy'),
1074 $amountSection = TRUE,
1079 $membershipTypes = TRUE,
1080 $memPriceSetId = NULL,
1087 $isAddPaymentProcessor = TRUE,
1088 $isPcpApprovalNeeded = FALSE,
1089 $isSeparatePayment = FALSE,
1090 $honoreeSection = TRUE,
1091 $allowOtherAmount = TRUE,
1092 $isConfirmEnabled = TRUE,
1093 $financialType = 'Donation',
1094 $fixedAmount = TRUE,
1095 $membershipsRequired = TRUE
1098 $hash = substr(sha1(rand()), 0, 7);
1101 $pageTitle = 'Donate Online ' . $hash;
1105 $rand = 2 * rand(2, 50);
1108 // Create a new payment processor if requested
1109 if ($isAddPaymentProcessor) {
1110 while (list($processorName, $processorType) = each($processor)) {
1111 $this->webtestAddPaymentProcessor($processorName, $processorType);
1115 // go to the New Contribution Page page
1116 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
1118 // fill in step 1 (Title and Settings)
1119 $this->type('title', $pageTitle);
1121 //to select financial type
1122 $this->select('financial_type_id', "label={$financialType}");
1125 $this->click('is_organization');
1126 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
1127 $this->type('for_organization', "On behalf $hash");
1129 if ($onBehalf == 'required') {
1130 $this->click('CIVICRM_QFID_2_4');
1132 elseif ($onBehalf == 'optional') {
1133 $this->click('CIVICRM_QFID_1_2');
1137 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1138 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1140 $this->type('goal_amount', 10 * $rand);
1142 // FIXME: handle Start/End Date/Time
1143 if ($honoreeSection) {
1144 $this->click('honor_block_is_active');
1145 $this->type('honor_block_title', "Honoree Section Title $hash");
1146 $this->type('honor_block_text', "Honoree Introductory Message $hash");
1147 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1148 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1149 $this->waitForElementPresent("//*[@class='select2-result-label']");
1150 $this->clickAt("//*[@class='select2-results']/li[1]");
1153 // is confirm enabled? it starts out enabled, so uncheck it if false
1154 if (!$isConfirmEnabled) {
1155 $this->click("id=is_confirm_enabled");
1159 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1161 // Get contribution page id
1162 $pageId = $this->urlArg('id');
1164 // fill in step 2 (Processor, Pay Later, Amounts)
1165 if (!empty($processor)) {
1167 while (list($processorName) = each($processor)) {
1168 // select newly created processor
1169 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1170 $this->assertTrue($this->isTextPresent($processorName));
1171 $this->check($xpath);
1175 if ($amountSection && !$memPriceSetId) {
1177 $this->click('is_pay_later');
1178 $this->type('pay_later_text', "Pay later label $hash");
1179 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1183 $this->click('is_pledge_active');
1184 $this->click('pledge_frequency_unit[week]');
1185 $this->click('is_pledge_interval');
1186 $this->type('initial_reminder_day', 3);
1187 $this->type('max_reminders', 2);
1188 $this->type('additional_reminder_day', 1);
1190 elseif ($recurring) {
1191 $this->click('is_recur');
1192 $this->click("is_recur_interval");
1193 $this->click("is_recur_installments");
1195 if ($allowOtherAmount) {
1197 $this->click('is_allow_other_amount');
1199 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1200 //$this->type('min_amount', $rand / 2);
1201 //$this->type('max_amount', $rand * 10);
1203 if ($fixedAmount ||
!$allowOtherAmount) {
1204 $this->type('label_1', "Label $hash");
1205 $this->type('value_1', "$rand");
1207 $this->click('CIVICRM_QFID_1_4');
1210 $this->click('amount_block_is_active');
1213 $this->click('_qf_Amount_next');
1214 $this->waitForElementPresent('_qf_Amount_next-bottom');
1215 $this->waitForPageToLoad($this->getTimeoutMsec());
1216 $text = "'Amount' information has been saved.";
1217 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1219 if ($memPriceSetId ||
(($membershipTypes === TRUE) ||
(is_array($membershipTypes) && !empty($membershipTypes)))) {
1220 // go to step 3 (memberships)
1221 $this->click('link=Memberships');
1222 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1224 // fill in step 3 (Memberships)
1225 $this->click('member_is_active');
1226 $this->waitForElementPresent('displayFee');
1227 $this->type('new_title', "Title - New Membership $hash");
1228 $this->type('renewal_title', "Title - Renewals $hash");
1230 if ($memPriceSetId) {
1231 $this->click('member_price_set_id');
1232 $this->select('member_price_set_id', "value={$memPriceSetId}");
1235 if ($membershipTypes === TRUE) {
1236 $membershipTypes = array(array('id' => 2));
1239 // FIXME: handle Introductory Message - New Memberships/Renewals
1240 foreach ($membershipTypes as $mType) {
1241 $this->click("membership_type_{$mType['id']}");
1242 if (array_key_exists('default', $mType)) {
1245 if (array_key_exists('auto_renew', $mType)) {
1246 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1249 if ($membershipsRequired) {
1250 $this->click('is_required');
1252 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1253 $this->click('CIVICRM_QFID_2_4');
1254 if ($isSeparatePayment) {
1255 $this->click('is_separate_payment');
1258 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1259 $text = "'MembershipBlock' information has been saved.";
1260 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1263 // go to step 4 (thank-you and receipting)
1264 $this->click('link=Receipt');
1265 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1268 $this->type('thankyou_title', "Thank-you Page Title $hash");
1269 // FIXME: handle Thank-you Message/Page Footer
1270 $this->type('receipt_from_name', "Receipt From Name $hash");
1271 $this->type('receipt_from_email', "$hash@example.org");
1272 $this->type('receipt_text', "Receipt Message $hash");
1273 $this->type('cc_receipt', "$hash@example.net");
1274 $this->type('bcc_receipt', "$hash@example.com");
1276 $this->click('_qf_ThankYou_next');
1277 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1278 $this->waitForPageToLoad($this->getTimeoutMsec());
1279 $text = "'ThankYou' information has been saved.";
1280 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1283 // fill in step 5 (Tell a Friend)
1284 $this->click('link=Tell a Friend');
1285 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1286 $this->click('tf_is_active');
1287 $this->type('tf_title', "TaF Title $hash");
1288 $this->type('intro', "TaF Introduction $hash");
1289 $this->type('suggested_message', "TaF Suggested Message $hash");
1290 $this->type('general_link', "TaF Info Page Link $hash");
1291 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1292 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1294 //$this->click('_qf_Contribute_next');
1295 $this->click('_qf_Contribute_next-bottom');
1296 $this->waitForPageToLoad($this->getTimeoutMsec());
1297 $text = "'Friend' information has been saved.";
1298 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1301 if ($profilePreId ||
$profilePostId) {
1302 // fill in step 6 (Include Profiles)
1303 $this->click('css=li#tab_custom a');
1304 $this->waitForElementPresent('_qf_Custom_next-bottom');
1306 if ($profilePreId) {
1307 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1310 if ($profilePostId) {
1311 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1314 $this->click('_qf_Custom_next-bottom');
1315 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1317 $this->waitForPageToLoad($this->getTimeoutMsec());
1318 $text = "'Custom' information has been saved.";
1319 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1323 // fill in step 7 (Premiums)
1324 $this->click('link=Premiums');
1325 $this->waitForElementPresent('_qf_Premium_next-bottom');
1326 $this->click('premiums_active');
1327 $this->type('premiums_intro_title', "Prem Title $hash");
1328 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1329 $this->type('premiums_contact_email', "$hash@example.info");
1330 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1331 $this->click('premiums_display_min_contribution');
1332 $this->type('premiums_nothankyou_label', 'No thank-you');
1333 $this->click('_qf_Premium_next');
1334 $this->waitForElementPresent('_qf_Premium_next-bottom');
1336 $this->waitForPageToLoad($this->getTimeoutMsec());
1337 $text = "'Premium' information has been saved.";
1338 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1342 // fill in step 8 (Widget Settings)
1343 $this->click('link=Widgets');
1344 $this->waitForElementPresent('_qf_Widget_next-bottom');
1346 $this->click('is_active');
1347 $this->type('url_logo', "URL to Logo Image $hash");
1348 $this->type('button_title', "Button Title $hash");
1349 // Type About text in ckEditor (fieldname, text to type, editor)
1350 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1352 $this->click('_qf_Widget_next');
1353 $this->waitForElementPresent('_qf_Widget_next-bottom');
1355 $this->waitForPageToLoad($this->getTimeoutMsec());
1356 $text = "'Widget' information has been saved.";
1357 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1361 // fill in step 9 (Enable Personal Campaign Pages)
1362 $this->click('link=Personal Campaigns');
1363 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1364 $this->click('pcp_active');
1365 if (!$isPcpApprovalNeeded) {
1366 $this->click('is_approval_needed');
1368 $this->type('notify_email', "$hash@example.name");
1369 $this->select('supporter_profile_id', 'value=2');
1370 $this->type('tellfriend_limit', 7);
1371 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1373 $this->click('_qf_Contribute_next-bottom');
1374 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1375 $this->waitForPageToLoad($this->getTimeoutMsec());
1376 $text = "'Pcp' information has been saved.";
1377 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1384 * Update default strict rule.
1386 * @param string $contactType
1387 * @param array $fields
1388 * Fields to be set for strict rule.
1389 * @param int $threshold
1390 * Rule's threshold value.
1392 public function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1393 // set default strict rule.
1395 if ($contactType == 'Organization') {
1398 elseif ($contactType == 'Household') {
1402 // Default dedupe fields for each Contact type.
1403 if (empty($fields)) {
1404 $fields = array('civicrm_email.email' => 10);
1405 if ($contactType == 'Organization') {
1407 'civicrm_contact.organization_name' => 10,
1408 'civicrm_email.email' => 10,
1411 elseif ($contactType == 'Household') {
1413 'civicrm_contact.household_name' => 10,
1414 'civicrm_email.email' => 10,
1419 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1422 foreach ($fields as $field => $weight) {
1423 $this->select("where_{$count}", "value={$field}");
1424 $this->type("length_{$count}", '');
1425 $this->type("weight_{$count}", $weight);
1430 $this->type('threshold', $threshold);
1432 $this->click('_qf_DedupeRules_next-bottom');
1433 $this->waitForPageToLoad($this->getTimeoutMsec());
1437 for ($i = $count; $i <= 4; $i++
) {
1438 $this->select("where_{$i}", 'label=- none -');
1439 $this->type("length_{$i}", '');
1440 $this->type("weight_{$i}", '');
1443 $this->type('threshold', $threshold);
1446 $this->click('_qf_DedupeRules_next-bottom');
1447 $this->waitForPageToLoad($this->getTimeoutMsec());
1451 * @param string $period_type
1452 * @param int $duration_interval
1453 * @param string $duration_unit
1454 * @param string $auto_renew
1458 public function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1459 $membershipTitle = substr(sha1(rand()), 0, 7);
1460 $membershipOrg = $membershipTitle . ' memorg';
1461 $this->webtestAddOrganization($membershipOrg, TRUE);
1463 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1464 $memTypeParams = array(
1465 'membership_type' => $title,
1466 'member_of_contact' => $membershipOrg,
1467 'financial_type' => 2,
1468 'period_type' => $period_type,
1471 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1473 $this->type('name', $memTypeParams['membership_type']);
1475 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1476 // select the radio first since the element id changes after membership org search results are loaded
1477 switch ($auto_renew) {
1479 $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')]");
1483 $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')]");
1487 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1488 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')]")) {
1489 $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')]");
1494 $this->select2('member_of_contact_id', $membershipTitle);
1496 $this->type('minimum_fee', '100');
1497 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1499 $this->type('duration_interval', $duration_interval);
1500 $this->select('duration_unit', "label={$duration_unit}");
1502 $this->select('period_type', "value={$period_type}");
1504 $this->click('_qf_MembershipType_upload-bottom');
1505 $this->waitForElementPresent('link=Add Membership Type');
1506 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1508 return $memTypeParams;
1512 * @param null $groupName
1513 * @param null $parentGroupName
1515 * @return null|string
1517 public function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1518 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1522 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1524 $this->type('title', $groupName);
1527 $this->type('description', 'Adding new group.');
1529 // check Access Control
1530 $this->click('group_type[1]');
1532 // check Mailing List
1533 $this->click('group_type[2]');
1535 // select Visibility as Public Pages
1536 $this->select('visibility', 'value=Public Pages');
1538 // select parent group
1539 if ($parentGroupName) {
1540 $this->select('parents', "*$parentGroupName");
1544 $this->clickLink('_qf_Edit_upload-bottom');
1546 // Is status message correct?
1547 $this->waitForText('crm-notification-container', "$groupName");
1552 * @param string $activityType
1556 public function WebtestAddActivity($activityType = "Meeting") {
1557 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1558 // We're using Quick Add block on the main page for this.
1559 $firstName1 = substr(sha1(rand()), 0, 7);
1560 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1561 $firstName2 = substr(sha1(rand()), 0, 7);
1562 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1564 $this->click("css=li#tab_activity a");
1566 // waiting for the activity dropdown to show up
1567 $this->waitForElementPresent("other_activity");
1569 // Select the activity type from the activity dropdown
1570 $this->select("other_activity", "label=Meeting");
1572 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1573 $this->waitForElementPresent("s2id_target_contact_id");
1575 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__
);
1577 // Typing contact's name into the field (using typeKeys(), not type()!)...
1578 $this->select2("assignee_contact_id", $firstName1, TRUE);
1580 // ...and verifying if the page contains properly formatted display name for chosen contact.
1581 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__
);
1583 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1584 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1585 // For simple input fields we can use field id as selector
1586 $this->type("subject", $subject);
1587 $this->type("location", "Some location needs to be put in this field.");
1589 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1591 // Setting duration.
1592 $this->type("duration", "30");
1594 // Putting in details.
1595 $this->type("details", "Really brief details information.");
1597 // Making sure that status is set to Scheduled (using value, not label).
1598 $this->select("status_id", "value=1");
1600 // Setting priority.
1601 $this->select("priority_id", "value=1");
1603 // Scheduling follow-up.
1604 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1605 $this->select("followup_activity_type_id", "value=1");
1606 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1607 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1610 $this->click("_qf_Activity_upload-bottom");
1611 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1613 // Is status message correct?
1614 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1616 $this->waitForElementPresent("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1618 // click through to the Activity view screen
1619 $this->clickLinkSuppressPopup("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']", '_qf_Activity_cancel-bottom');
1621 // parse URL to grab the activity id
1622 // pass id back to any other tests that call this class
1623 return $this->urlArg('id');
1629 public static function checkDoLocalDBTest() {
1630 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1631 CIVICRM_WEBTEST_LOCAL_DB
1633 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1640 * Generic function to compare expected values after an api call to retrieved
1643 * @param string $daoName
1644 * DAO Name of object we're evaluating.
1647 * @param array $match
1648 * Associative array of field name => expected value. Empty if asserting
1649 * that a DELETE occurred
1650 * @param bool $delete
1651 * are we checking that a DELETE action occurred?
1653 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
1654 if (self
::checkDoLocalDBTest()) {
1655 CiviDBAssert
::assertDBState($this, $daoName, $id, $match, $delete);
1660 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1661 * @param string $daoName
1662 * @param string $searchValue
1663 * @param string $returnColumn
1664 * @param string $searchColumn
1665 * @param string $message
1667 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1668 if (self
::checkDoLocalDBTest()) {
1669 CiviDBAssert
::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1674 * Request a record from the DB by searchColumn+searchValue. Success if returnColumn value is NULL.
1675 * @param string $daoName
1676 * @param string $searchValue
1677 * @param string $returnColumn
1678 * @param string $searchColumn
1679 * @param string $message
1681 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1682 if (self
::checkDoLocalDBTest()) {
1683 CiviDBAssert
::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1688 * Request a record from the DB by id. Success if row not found.
1689 * @param string $daoName
1691 * @param string $message
1693 public function assertDBRowNotExist($daoName, $id, $message) {
1694 if (self
::checkDoLocalDBTest()) {
1695 CiviDBAssert
::assertDBRowNotExist($this, $daoName, $id, $message);
1700 * Compare all values in a single retrieved DB record to an array of expected values
1701 * @param string $daoName
1702 * @param array $searchParams
1703 * @param $expectedValues
1705 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1706 if (self
::checkDoLocalDBTest()) {
1707 CiviDBAssert
::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1714 * @param string $message
1716 public function assertType($expected, $actual, $message = '') {
1717 $this->assertInternalType($expected, $actual, $message);
1721 * Add new Financial Account
1722 * @param $financialAccountTitle
1723 * @param bool $financialAccountDescription
1724 * @param bool $accountingCode
1725 * @param bool $firstName
1726 * @param bool $financialAccountType
1727 * @param bool $taxDeductible
1728 * @param bool $isActive
1729 * @param bool $isTax
1730 * @param bool $taxRate
1731 * @param bool $isDefault
1733 public function _testAddFinancialAccount(
1734 $financialAccountTitle,
1735 $financialAccountDescription = FALSE,
1736 $accountingCode = FALSE,
1738 $financialAccountType = FALSE,
1739 $taxDeductible = FALSE,
1746 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1748 $this->click("link=Add Financial Account");
1749 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1751 // Financial Account Name
1752 $this->type('name', $financialAccountTitle);
1754 // Financial Description
1755 if ($financialAccountDescription) {
1756 $this->type('description', $financialAccountDescription);
1760 if ($accountingCode) {
1761 $this->type('accounting_code', $accountingCode);
1764 // Autofill Organization
1766 $this->webtestOrganisationAutocomplete($firstName);
1769 // Financial Account Type
1770 if ($financialAccountType) {
1771 $this->select('financial_account_type_id', "label={$financialAccountType}");
1774 // Is Tax Deductible
1775 if ($taxDeductible) {
1776 $this->check('is_deductible');
1779 $this->uncheck('is_deductible');
1783 $this->check('is_active');
1786 $this->uncheck('is_active');
1790 $this->check('is_tax');
1793 $this->uncheck('is_tax');
1797 $this->type('tax_rate', $taxRate);
1802 $this->check('is_default');
1805 $this->uncheck('is_default');
1807 $this->click('_qf_FinancialAccount_next-botttom');
1811 * Edit Financial Account
1812 * @param $editfinancialAccount
1813 * @param bool $financialAccountTitle
1814 * @param bool $financialAccountDescription
1815 * @param bool $accountingCode
1816 * @param bool $firstName
1817 * @param bool $financialAccountType
1818 * @param bool $taxDeductible
1819 * @param bool $isActive
1820 * @param bool $isTax
1821 * @param bool $taxRate
1822 * @param bool $isDefault
1824 public function _testEditFinancialAccount(
1825 $editfinancialAccount,
1826 $financialAccountTitle = FALSE,
1827 $financialAccountDescription = FALSE,
1828 $accountingCode = FALSE,
1830 $financialAccountType = FALSE,
1831 $taxDeductible = FALSE,
1838 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1841 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']");
1842 $this->clickLink("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1844 // Change Financial Account Name
1845 if ($financialAccountTitle) {
1846 $this->type('name', $financialAccountTitle);
1849 // Financial Description
1850 if ($financialAccountDescription) {
1851 $this->type('description', $financialAccountDescription);
1855 if ($accountingCode) {
1856 $this->type('accounting_code', $accountingCode);
1859 // Autofill Edit Organization
1861 $this->webtestOrganisationAutocomplete($firstName);
1864 // Financial Account Type
1865 if ($financialAccountType) {
1866 $this->select('financial_account_type_id', "label={$financialAccountType}");
1869 // Is Tax Deductible
1870 if ($taxDeductible) {
1871 $this->check('is_deductible');
1874 $this->uncheck('is_deductible');
1879 $this->check('is_tax');
1882 $this->uncheck('is_tax');
1887 $this->type('tax_rate', $taxRate);
1892 $this->check('is_default');
1895 $this->uncheck('is_default');
1900 $this->check('is_active');
1903 $this->uncheck('is_active');
1905 $this->click('_qf_FinancialAccount_next-botttom');
1906 $this->waitForElementPresent('link=Add Financial Account');
1910 * Delete Financial Account
1911 * @param $financialAccountTitle
1913 public function _testDeleteFinancialAccount($financialAccountTitle) {
1914 $this->click("xpath=//table/tbody//tr/td[1]/div[text()='{$financialAccountTitle}']/../../td[9]/span/a[text()='Delete']");
1915 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1916 $this->click('_qf_FinancialAccount_next-botttom');
1917 $this->waitForElementPresent('link=Add Financial Account');
1918 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1922 * Verify data after ADD and EDIT
1923 * @param $verifyData
1925 public function _assertFinancialAccount($verifyData) {
1926 foreach ($verifyData as $key => $expectedValue) {
1927 $actualValue = $this->getValue($key);
1928 if ($key == 'parent_financial_account') {
1929 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1932 $this->assertEquals($expectedValue, $actualValue);
1938 * @param $verifySelectFieldData
1940 public function _assertSelectVerify($verifySelectFieldData) {
1941 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1942 $actualvalue = $this->getSelectedLabel($key);
1943 $this->assertEquals($expectedvalue, $actualvalue);
1948 * @param $financialType
1949 * @param string $option
1951 public function addeditFinancialType($financialType, $option = 'new') {
1952 $this->openCiviPage("admin/financial/financialType", "reset=1");
1954 if ($option == 'Delete') {
1955 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]");
1956 $this->waitForElementPresent("css=span.btn-slide-active");
1957 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]/ul/li[2]/a");
1958 $this->waitForElementPresent("_qf_FinancialType_next");
1959 $this->click("_qf_FinancialType_next");
1960 $this->waitForElementPresent("newFinancialType");
1961 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1964 if ($option == 'new') {
1965 $this->click("link=Add Financial Type");
1968 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[oldname]']/../../td[7]/span/a[text()='Edit']");
1970 $this->waitForElementPresent("name");
1971 $this->type('name', $financialType['name']);
1972 if ($option == 'new') {
1973 $this->type('description', $financialType['name'] . ' description');
1976 if ($financialType['is_reserved']) {
1977 $this->check('is_reserved');
1980 $this->uncheck('is_reserved');
1983 if ($financialType['is_deductible']) {
1984 $this->check('is_deductible');
1987 $this->uncheck('is_deductible');
1990 $this->click('_qf_FinancialType_next');
1991 if ($option == 'new') {
1992 $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.";
1995 $text = "The financial type \"{$financialType['name']}\" has been updated.";
1997 $this->checkCRMAlert($text);
2001 * Give the specified permissions
2002 * Note: this function logs in as 'admin' (logging out if necessary)
2003 * @param $permission
2005 public function changePermissions($permission) {
2006 $this->webtestLogin('admin');
2007 $this->open("{$this->sboxPath}admin/people/permissions");
2008 $this->waitForElementPresent('edit-submit');
2009 foreach ((array) $permission as $perm) {
2010 $this->check($perm);
2012 $this->click('edit-submit');
2013 $this->waitForPageToLoad($this->getTimeoutMsec());
2014 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
2018 * @param $profileTitle
2019 * @param $profileFields
2021 public function addProfile($profileTitle, $profileFields) {
2022 $this->openCiviPage('admin/uf/group', "reset=1");
2024 $this->clickLink('link=Add Profile', '_qf_Group_cancel-bottom');
2025 $this->type('title', $profileTitle);
2026 $this->clickLink('_qf_Group_next-bottom');
2028 $this->waitForText('crm-notification-container', "Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now.");
2030 foreach ($profileFields as $field) {
2031 $this->waitForElementPresent('field_name_0');
2032 $this->click("id=field_name_0");
2033 $this->select("id=field_name_0", "label=" . $field['type']);
2034 $this->waitForElementPresent('field_name_1');
2035 $this->click("id=field_name_1");
2036 $this->select("id=field_name_1", "label=" . $field['name']);
2037 $this->waitForElementPresent('label');
2038 $this->type("id=label", $field['label']);
2039 $this->click("id=_qf_Field_next_new-top");
2040 $this->waitForElementPresent("xpath=//select[@id='field_name_1'][@style='display: none;']");
2041 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
2046 * @param string $name
2051 * @param $financialType
2053 public function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
2054 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
2055 $this->type("name", $name);
2056 $this->type("sku", $sku);
2057 $this->click("CIVICRM_QFID_noImage_16");
2058 $this->type("min_contribution", $amount);
2059 $this->type("price", $price);
2060 $this->type("cost", $cost);
2061 if ($financialType) {
2062 $this->select("financial_type_id", "label={$financialType}");
2064 $this->click("_qf_ManagePremiums_upload-bottom");
2065 $this->waitForPageToLoad($this->getTimeoutMsec());
2070 * @param $financialAccount
2072 public function addPaymentInstrument($label, $financialAccount) {
2073 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
2074 $this->type("label", $label);
2075 $this->select("financial_account_id", "value=$financialAccount");
2076 $this->click("_qf_Options_next-bottom");
2077 $this->waitForPageToLoad($this->getTimeoutMsec());
2081 * Ensure we have a default mailbox set up for CiviMail
2083 public function setupDefaultMailbox() {
2084 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
2085 // Check if it hasn't already been set up
2086 if (!$this->getSelectedValue('protocol')) {
2087 $this->type('name', 'Test Domain');
2088 $this->select('protocol', "IMAP");
2089 $this->type('server', 'localhost');
2090 $this->type('domain', 'example.com');
2091 $this->clickLink('_qf_MailSettings_next-top');
2096 * Determine the default time-out in milliseconds.
2098 * @return string, timeout expressed in milliseconds
2100 public function getTimeoutMsec() {
2101 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
2102 $timeout = ($this->settings
&& @$this->settings
->timeout
) ?
($this->settings
->timeout
* 1000) : 30000;
2103 return (string) $timeout; // don't know why, but all our old code used a string
2108 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
2111 * @param array $customSets
2112 * Custom sets i.e entity wise sets want to be created and checked.
2113 * e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
2114 * 'triggerElement' => $triggerElement))
2115 * array $triggerElement: the element which is responsible for custom group to load
2117 * which uses the entity info as its selection value
2118 * @param array $pageUrl
2119 * The url which on which the ajax custom group load takes place.
2120 * @param string $beforeTriggering
2123 public function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
2124 // FIXME: Testing a theory that these failures have something to do with permissions
2125 $this->webtestLogin('admin');
2127 //add the custom set
2128 $return = $this->addCustomGroupField($customSets);
2130 // FIXME: Hack to ensure caches are properly cleared
2132 $userName = $this->loggedInAs
;
2133 $this->webtestLogout();
2134 $this->webtestLogin($userName);
2137 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
2139 // FIXME: Try to find out what the heck is going on with these tests
2140 $this->waitForAjaxContent();
2141 $this->checkForErrorsOnPage();
2143 foreach ($return as $values) {
2144 foreach ($values as $entityType => $customData) {
2145 //initiate necessary variables
2146 list($entity, $entityData) = explode('_', $entityType);
2147 $elementType = CRM_Utils_Array
::value('type', $customData['triggerElement'], 'select');
2148 $elementName = CRM_Utils_Array
::value('name', $customData['triggerElement']);
2149 if (is_callable($beforeTriggering)) {
2150 call_user_func($beforeTriggering);
2152 if ($elementType == 'select') {
2153 //reset the select box, so triggering of ajax only happens
2154 //WRT input of value in this function
2155 $this->select($elementName, "index=0");
2157 if (!empty($entityData)) {
2158 if ($elementType == 'select') {
2159 $this->select($elementName, "label=regexp:{$entityData}");
2161 elseif ($elementType == 'checkbox') {
2162 $val = explode(',', $entityData);
2163 foreach ($val as $v) {
2164 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2165 $this->check($checkId);
2168 elseif ($elementType == 'select2') {
2169 $this->select2($elementName, $entityData);
2172 // FIXME: Try to find out what the heck is going on with these tests
2173 $this->waitForAjaxContent();
2174 $this->checkForErrorsOnPage();
2176 //checking for proper custom data which is loading through ajax
2177 $this->waitForElementPresent("css=.custom-group-{$customData['cgtitle']}");
2178 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2179 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2185 * @param $customSets
2189 public function addCustomGroupField($customSets) {
2191 foreach ($customSets as $customSet) {
2192 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2194 //fill custom group title
2195 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2196 $this->click("title");
2197 $this->type("title", $customGroupTitle);
2199 //custom group extends
2200 $this->click("extends_0");
2201 $this->select("extends_0", "value={$customSet['entity']}");
2202 if (!empty($customSet['subEntity'])) {
2203 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2207 $this->uncheck('collapse_display');
2210 $this->click('_qf_Group_next-bottom');
2212 //Is custom group created?
2213 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2215 $gid = $this->urlArg('gid');
2216 $this->waitForTextPresent("{$customGroupTitle} - New Field");
2218 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2219 $this->waitForElementPresent('label');
2220 $this->type('label', $fieldLabel);
2221 $this->click('_qf_Field_done-bottom');
2223 $this->waitForText('crm-notification-container', $fieldLabel);
2224 $this->waitForAjaxContent();
2226 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2228 "{$customSet['entity']}_{$customSet['subEntity']}" => array(
2229 'cgtitle' => $customGroupTitle,
2231 'triggerElement' => $customSet['triggerElement'],
2235 // Go home for a sec to give time for caches to clear
2236 $this->openCiviPage('');
2242 * Type and select first occurance of autocomplete
2245 * @param bool $multiple
2246 * @param bool $xpath
2248 public function select2($fieldName, $label, $multiple = FALSE, $xpath = FALSE) {
2249 // In the case of chainSelect, wait for options to load
2250 $this->waitForElementNotPresent('css=select.loading');
2252 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2253 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2254 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2255 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2256 $this->waitForElementPresent("//*[@class='select2-result-label']");
2257 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2261 $this->clickAt($fieldName);
2264 $this->clickAt("//*[@id='$fieldName']/../div/a");
2266 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2267 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2268 $this->type("//*[@id='select2-drop']/div/input", $label);
2269 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
2270 $this->waitForElementPresent("//*[@class='select2-result-label']");
2271 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2273 // Wait a sec for select2 to update the original element
2278 * Select multiple options
2282 public function multiselect2($fieldid, $params) {
2283 // In the case of chainSelect, wait for options to load
2284 $this->waitForElementNotPresent('css=select.loading');
2285 foreach ($params as $value) {
2286 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2287 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2288 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2289 $this->assertElementContainsText("xpath=//*[@id='$fieldid']/preceding-sibling::div[1]/", $value);
2291 // Wait a sec for select2 to update the original element
2296 * Check for unobtrusive status message as set by CRM.status
2299 public function checkCRMStatus($text = NULL) {
2300 $this->waitForElementPresent("css=.crm-status-box-outer.status-success");
2302 $this->assertElementContainsText("css=.crm-status-box-outer.status-success", $text);
2307 * Check for obtrusive status message as set by CRM.alert
2309 * @param string $type
2311 public function checkCRMAlert($text, $type = 'success') {
2312 $this->waitForElementPresent("css=div.ui-notify-message.$type");
2313 $this->waitForText("css=div.ui-notify-message.$type", $text);
2314 // We got the message, now let's close it so the webtest doesn't get confused by lots of open alerts
2315 $this->click('css=.ui-notify-cross');
2319 * Enable or disable Pop-ups via Display Preferences
2320 * @param bool $enabled
2322 public function enableDisablePopups($enabled = TRUE) {
2323 $this->openCiviPage('admin/setting/preferences/display', 'reset=1');
2324 $isChecked = $this->isChecked('ajaxPopupsEnabled');
2325 if (($isChecked && !$enabled) ||
(!$isChecked && $enabled)) {
2326 $this->click('ajaxPopupsEnabled');
2329 $this->assertChecked('ajaxPopupsEnabled');
2332 $this->assertNotChecked('ajaxPopupsEnabled');
2334 $this->clickLink("_qf_Display_next-bottom");
2338 * Attempt to get information about what went wrong if we encounter an error when loading a page
2340 public function checkForErrorsOnPage() {
2341 foreach (array('Access denied', 'Page not found') as $err) {
2342 if ($this->isElementPresent("xpath=//h1[contains(., '$err')]")) {
2343 $this->fail("'$err' encountered at " . $this->getLocation() . "\nwhile logged in as '{$this->loggedInAs}'");
2346 if ($this->isElementPresent("xpath=//span[text()='Sorry but we are not able to provide this at the moment.']")) {
2347 $msg = '"Fatal Error" encountered at ' . $this->getLocation();
2348 if ($this->isElementPresent('css=div.crm-section.crm-error-message')) {
2349 $msg .= "\nError Message: " . $this->getText('css=div.crm-section.crm-error-message');