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
);
109 protected function prepareTestSession() {
110 $result = parent
::prepareTestSession();
112 // Set any cookies required by local installation
113 // Note: considered doing this in setUp(), but the Selenium session wasn't yet initialized.
114 if (property_exists($this->settings
, 'cookies')) {
115 // We don't really care about this page, but it seems we need
116 // to open a page before setting a cookie.
117 $this->open($this->sboxPath
);
118 $this->waitForPageToLoad($this->getTimeoutMsec());
119 $this->setCookies($this->settings
->cookies
);
125 * @param array $cookies
126 * Each item is an Array with keys:
128 * - value: string; note that RFC's don't define particular encoding scheme, so
129 * you must pick one yourself and pre-encode; does not allow values with
130 * commas, semicolons, or whitespace
131 * - path: string; default: '/'
132 * - max_age: int; default: 1 week (7*24*60*60)
134 protected function setCookies($cookies) {
135 foreach ($cookies as $cookie) {
136 if (!isset($cookie['path'])) {
137 $cookie['path'] = '/';
139 if (!isset($cookie['max_age'])) {
140 $cookie['max_age'] = 7 * 24 * 60 * 60;
142 $this->deleteCookie($cookie['name'], $cookie['path']);
143 $optionExprs = array();
144 foreach ($cookie as $key => $value) {
145 if ($key != 'name' && $key != 'value') {
146 $optionExprs[] = "$key=$value";
149 $this->createCookie("{$cookie['name']}={$cookie['value']}", implode(', ', $optionExprs));
153 protected function tearDown() {
157 * Authenticate as drupal user.
158 * @param $user : (str) the key 'user' or 'admin', or a literal username
159 * @param $pass : (str) if $user is a literal username and not 'user' or 'admin', supply the password
161 public function webtestLogin($user = 'user', $pass = NULL) {
162 // If already logged in as correct user, do nothing
163 if ($this->loggedInAs
=== $user) {
166 // If we are logged in as a different user, log out first
167 if ($this->loggedInAs
) {
168 $this->webtestLogout();
170 $this->open("{$this->sboxPath}user");
171 // Lookup username & password if not supplied
173 if ($pass === NULL) {
174 $pass = $user == 'admin' ?
$this->settings
->adminPassword
: $this->settings
->password
;
175 $username = $user == 'admin' ?
$this->settings
->adminUsername
: $this->settings
->username
;
177 // Make sure login form is available
178 $this->waitForElementPresent('edit-submit');
179 $this->type('edit-name', $username);
180 $this->type('edit-pass', $pass);
181 $this->click('edit-submit');
182 $this->waitForPageToLoad($this->getTimeoutMsec());
183 $this->loggedInAs
= $user;
186 public function webtestLogout() {
187 if ($this->loggedInAs
) {
188 $this->open($this->sboxPath
. "user/logout");
189 $this->waitForPageToLoad($this->getTimeoutMsec());
191 $this->loggedInAs
= NULL;
195 * Open an internal path beginning with 'civicrm/'
198 * omit the 'civicrm/' it will be added for you.
199 * @param string|array $args
200 * optional url arguments.
202 * Page element to wait for - using this is recommended to ensure the document is fully loaded.
204 * Although it doesn't seem to do much now, using this function is recommended for
205 * opening all civi pages, and using the $args param is also strongly encouraged
206 * This will make it much easier to run webtests in other CMSs in the future
208 public function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
209 // Construct full url with args
210 // This could be extended in future to work with other CMS style urls
212 if (is_array($args)) {
214 foreach ($args as $key => $val) {
215 $url .= $sep . $key . '=' . $val;
223 $this->open("{$this->sboxPath}civicrm/$url");
224 $this->waitForPageToLoad($this->getTimeoutMsec());
225 $this->checkForErrorsOnPage();
227 $this->waitForElementPresent($waitFor);
232 * Click on a link or button.
233 * Wait for the page to load
234 * Wait for an element to be present
236 * @param string $waitFor
237 * @param bool $waitForPageLoad
239 public function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
240 $this->click($element);
241 // conditional wait for page load e.g for ajax form save
242 if ($waitForPageLoad) {
243 $this->waitForPageToLoad($this->getTimeoutMsec());
244 $this->checkForErrorsOnPage();
247 $this->waitForElementPresent($waitFor);
252 * Click a link or button and wait for an ajax dialog to load.
253 * @param string $element
254 * @param string $waitFor
256 public function clickPopupLink($element, $waitFor = NULL) {
257 $this->clickAjaxLink($element, 'css=.ui-dialog');
259 $this->waitForElementPresent($waitFor);
264 * Click a link or button and wait for ajax content to load or refresh.
265 * @param string $element
266 * @param string $waitFor
268 public function clickAjaxLink($element, $waitFor = NULL) {
269 $this->click($element);
271 $this->waitForElementPresent($waitFor);
273 $this->waitForAjaxContent();
277 * Force a link to open full-page, even if it would normally open in a popup
278 * @note: works with links only, not buttons
279 * @param string $element
280 * @param string $waitFor
282 public function clickLinkSuppressPopup($element, $waitFor = 'civicrm-footer') {
283 $link = $this->getAttribute($element . '@href');
285 $this->waitForPageToLoad($this->getTimeoutMsec());
287 $this->waitForElementPresent($waitFor);
292 * Wait for all ajax snippets to finish loading.
294 public function waitForAjaxContent() {
295 $this->waitForElementNotPresent('css=.blockOverlay');
296 // Some ajax calls happen in pairs (e.g. submit a popup form then refresh the underlying content)
297 // So we'll wait a sec and recheck to see if any more stuff is loading
299 if ($this->isElementPresent('css=.blockOverlay')) {
300 $this->waitForAjaxContent();
305 * Call the API on the local server.
306 * (kind of defeats the point of a webtest - see CRM-11889)
312 public function webtest_civicrm_api($entity, $action, $params) {
313 if (!isset($params['version'])) {
314 $params['version'] = 3;
317 $result = civicrm_api($entity, $action, $params);
318 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
323 * Call the API on the remote server.
324 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
328 * @param array $params
331 public function rest_civicrm_api($entity, $action, $params = array()) {
335 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
339 // Naughty sidestep of civi's security checks
340 'header' => "X-Requested-With: XMLHttpRequest",
343 $ctx = stream_context_create($request);
344 $result = file_get_contents($url, FALSE, $ctx);
345 return json_decode($result, TRUE);
349 * @param string $option_group_name
353 public function webtestGetFirstValueForOptionGroup($option_group_name) {
354 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
355 'option_group_name' => $option_group_name,
365 public function webtestGetValidCountryID() {
367 if (is_null($_country_id)) {
368 $config_backend = $this->webtestGetConfig('countryLimit');
369 $_country_id = current($config_backend);
379 public function webtestGetValidEntityID($entity) {
380 // michaelmcandrew: would like to use getvalue but there is a bug
381 // for e.g. group where option.limit not working at the moment CRM-9110
382 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
383 if (!empty($result['values'])) {
384 return current(array_keys($result['values']));
394 public function webtestGetConfig($field) {
395 static $_config_backend;
396 if (is_null($_config_backend)) {
397 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
398 'current_domain' => 1,
400 'return' => 'config_backend',
402 $_config_backend = unserialize($result);
404 return $_config_backend[$field];
408 * Ensures the required CiviCRM components are enabled.
411 public function enableComponents($components) {
412 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
413 $enabledComponents = $this->getSelectOptions("enableComponents-t");
415 foreach ((array) $components as $comp) {
416 if (!in_array($comp, $enabledComponents)) {
417 $this->addSelection("enableComponents-f", "label=$comp");
418 $this->click("//option[@value='$comp']");
424 $this->clickLink("_qf_Component_next-bottom");
425 $this->checkCRMAlert("Saved");
430 * Add a contact with the given first and last names and either a given email.
431 * (when specified), a random email (when true) or no email (when unspecified or null).
433 * @param string $fname
434 * Contact’s first name.
435 * @param string $lname
436 * Contact’s last name.
437 * @param mixed $email
438 * Contact’s email (when string) or random email (when true) or no email (when null).
439 * @param string $contactSubtype
441 * @return string|null
442 * either a string with the (either generated or provided) email or null (if no email)
444 public function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
445 $args = 'reset=1&ct=Individual';
446 if ($contactSubtype) {
447 $args .= "&cst={$contactSubtype}";
449 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
450 $this->type('first_name', $fname);
451 $this->type('last_name', $lname);
452 if ($email === TRUE) {
453 $email = substr(sha1(rand()), 0, 7) . '@example.org';
456 $this->type('email_1_email', $email);
458 $this->clickLink('_qf_Contact_upload_view-bottom');
463 * @param string $householdName
466 * @return null|string
468 public function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
469 $this->openCiviPage("contact/add", "reset=1&ct=Household");
470 $this->click('household_name');
471 $this->type('household_name', $householdName);
473 if ($email === TRUE) {
474 $email = substr(sha1(rand()), 0, 7) . '@example.org';
477 $this->type('email_1_email', $email);
480 $this->clickLink('_qf_Contact_upload_view');
485 * @param string $organizationName
487 * @param null $contactSubtype
489 * @return null|string
491 public function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
492 $args = 'reset=1&ct=Organization';
493 if ($contactSubtype) {
494 $args .= "&cst={$contactSubtype}";
496 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
497 $this->click('organization_name');
498 $this->type('organization_name', $organizationName);
500 if ($email === TRUE) {
501 $email = substr(sha1(rand()), 0, 7) . '@example.org';
504 $this->type('email_1_email', $email);
506 $this->clickLink('_qf_Contact_upload_view');
512 * @param string $fieldName
514 public function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
515 $this->select2($fieldName, $sortName);
516 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
522 public function webtestOrganisationAutocomplete($sortName) {
523 $this->clickAt("//*[@id='contact_id']/../div/a");
524 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
525 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
526 $this->type("//*[@id='select2-drop']/div/input", $sortName);
527 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
528 $this->waitForElementPresent("//*[@class='select2-result-label']");
529 $this->clickAt("//*[@class='select2-results']/li[1]");
530 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
534 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
535 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
536 * 3. Examples of $strToTime arguments -
537 * webtestFillDate('start_date',"now")
538 * webtestFillDate('start_date',"10 September 2000")
539 * webtestFillDate('start_date',"+1 day")
540 * webtestFillDate('start_date',"+1 week")
541 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
542 * webtestFillDate('start_date',"next Thursday")
543 * webtestFillDate('start_date',"last Monday")
544 * @param $dateElement
545 * @param null $strToTimeArgs
547 public function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
548 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
550 $year = date('Y', $timeStamp);
551 // -1 ensures month number is inline with calender widget's month
552 $mon = date('n', $timeStamp) - 1;
553 $day = date('j', $timeStamp);
555 $this->click("xpath=//input[starts-with(@id, '{$dateElement}_display_')]");
556 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
557 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
558 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
559 $this->click("link=$day");
563 * 1. set both date and time.
564 * @param $dateElement
565 * @param null $strToTimeArgs
567 public function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
568 $this->webtestFillDate($dateElement, $strToTimeArgs);
570 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
571 $hour = date('h', $timeStamp);
572 $min = date('i', $timeStamp);
573 $meri = date('A', $timeStamp);
575 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
579 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
581 * @param array $expected
582 * Array of key/value pairs (like Status/Registered) to be checked.
583 * @param string $xpathPrefix
584 * Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath.
585 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
586 * @param string $tableId
587 * Pass in the id attribute of a table to be verified if you want to only check a specific table.
590 public function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
593 $tableLocator = "[@id='$tableId']";
595 foreach ($expected as $label => $value) {
597 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
598 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
601 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
602 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
608 * Types text into a ckEditor rich text field in a form.
610 * @param string $fieldName
611 * Form field name (as assigned by PHP buildForm class).
612 * @param string $text
613 * Text to type into the field.
614 * @param string $editor
615 * Which text editor (valid values are 'CKEditor', 'TinyMCE').
617 * @param bool $compressed
618 * @throws \PHPUnit_Framework_AssertionFailedError
620 public function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor', $compressed = FALSE) {
621 // make sure cursor focuses on the field
622 $this->fireEvent($fieldName, 'focus');
623 if ($editor == 'CKEditor') {
625 $this->click("{$fieldName}-plain");
627 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
628 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
630 elseif ($editor == 'TinyMCE') {
631 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
632 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
635 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
637 $this->selectFrame('relative=top');
641 * Types option label and name into a table of multiple choice options.
642 * (for price set fields of type select, radio, or checkbox)
643 * TODO: extend for custom field multiple choice table input
645 * @param array $options
646 * Form field name (as assigned by PHP buildForm class).
647 * @param array $validateStrings
648 * Appends label and name strings to this array so they can be validated later.
652 public function addMultipleChoiceOptions($options, &$validateStrings) {
653 foreach ($options as $oIndex => $oValue) {
654 $validateStrings[] = $oValue['label'];
655 $validateStrings[] = $oValue['amount'];
656 if (!empty($oValue['membership_type_id'])) {
657 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
659 if (!empty($oValue['financial_type_id'])) {
660 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
662 $this->type("option_label_{$oIndex}", $oValue['label']);
663 $this->type("option_amount_{$oIndex}", $oValue['amount']);
664 $this->click('link=another choice');
669 * Use a contact EntityRef field to add a new contact.
670 * @param string $field
672 * @param string $contactType
674 * Array of contact attributes (id, names, email)
676 public function createDialogContact($field = 'contact_id', $contactType = 'Individual') {
677 $selectId = 's2id_' . $this->getAttribute($field . '@id');
678 $this->clickAt("xpath=//div[@id='$selectId']/a");
679 $this->clickAjaxLink("xpath=//li[@class='select2-no-results']//a[contains(text(), 'New $contactType')]", '_qf_Edit_next');
681 $name = substr(sha1(rand()), 0, rand(6, 8));
683 if ($contactType == 'Individual') {
684 $params['first_name'] = "$name $contactType";
685 $params['last_name'] = substr(sha1(rand()), 0, rand(5, 9));
688 $params[strtolower($contactType) . '_name'] = "$name $contactType";
690 foreach ($params as $param => $val) {
691 $this->type($param, $val);
693 $this->type('email-Primary', $params['email'] = "{$name}@example.com");
694 $this->clickAjaxLink('_qf_Edit_next');
696 $this->waitForText("xpath=//div[@id='$selectId']", "$name");
698 $params['sort_name'] = $contactType == 'Individual' ?
$params['last_name'] . ', ' . $params['first_name'] : "$name $contactType";
699 $params['display_name'] = $contactType == 'Individual' ?
$params['first_name'] . ' ' . $params['last_name'] : $params['sort_name'];
700 $params['id'] = $this->getValue($field);
705 * @deprecated in favor of createDialogContact
706 * @param string $fname
707 * @param string $lname
708 * @param string $email
710 * @param string $selectId
712 * @param string $prefix
714 public function webtestNewDialogContact(
715 $fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
716 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
717 // 4 - Individual profile
718 // 5 - Organization profile
719 // 6 - Household profile
720 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
721 $this->clickAt("xpath=//div[@id='$selectId']/a");
722 $this->clickPopupLink("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]", '_qf_Edit_next');
726 $this->type('first_name', $fname);
727 $this->type('last_name', $lname);
731 $this->type('organization_name', $fname);
735 $this->type('household_name', $fname);
739 $this->type('email-Primary', $email);
740 $this->clickAjaxLink('_qf_Edit_next');
742 // Is new contact created?
744 $this->waitForText("xpath=//div[@id='$selectId']", "$lname, $fname");
747 $this->waitForText("xpath=//div[@id='$selectId']", "$fname");
752 * Generic function to check that strings are present in the page.
754 * @strings array array of strings or a single string
759 public function assertStringsPresent($strings) {
760 foreach ((array) $strings as $string) {
761 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
766 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
768 * @url string url to parse or retrieve current url if null
772 * returns an associative array containing any of the various components
773 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
774 * http://php.net/manual/en/function.parse-url.php
776 public function parseURL($url = NULL) {
778 $url = $this->getLocation();
781 $elements = parse_url($url);
782 if (!empty($elements['query'])) {
783 $elements['queryString'] = array();
784 parse_str($elements['query'], $elements['queryString']);
790 * Returns a single argument from the url query.
795 public function urlArg($arg, $url = NULL) {
796 $elements = $this->parseURL($url);
797 return isset($elements['queryString'][$arg]) ?
$elements['queryString'][$arg] : NULL;
801 * Define a payment processor for use by a webtest. Default is to create Dummy processor
802 * which is useful for testing online public forms (online contribution pages and event registration)
804 * @param string $processorName
805 * Name assigned to new processor.
806 * @param string $processorType
807 * Name for processor type (e.g. PayPal, Dummy, etc.).
808 * @param array $processorSettings
809 * Array of fieldname => value for required settings for the processor.
811 * @param string $financialAccount
812 * @throws PHPUnit_Framework_AssertionFailedError
815 public function webtestAddPaymentProcessor($processorName = 'Test Processor', $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
816 if (!$processorName) {
817 $this->fail("webTestAddPaymentProcessor requires $processorName.");
819 // Ensure we are logged in as admin before we proceed
820 $this->webtestLogin('admin');
822 if ($processorName === 'Test Processor') {
823 // Use the default test processor, no need to create a new one
824 $this->openCiviPage('admin/paymentProcessor', 'action=update&id=1&reset=1', '_qf_PaymentProcessor_cancel-bottom');
825 $this->check('is_default');
826 $this->select('financial_account_id', "label={$financialAccount}");
827 $this->clickLink('_qf_PaymentProcessor_next-bottom');
831 if ($processorType == 'Dummy') {
832 $processorSettings = array(
833 'user_name' => 'dummy',
834 'url_site' => 'http://dummy.com',
835 'test_user_name' => 'dummytest',
836 'test_url_site' => 'http://dummytest.com',
839 elseif ($processorType == 'AuthNet') {
840 // FIXME: we 'll need to make a new separate account for testing
841 $processorSettings = array(
842 'test_user_name' => '5ULu56ex',
843 'test_password' => '7ARxW575w736eF5p',
846 elseif ($processorType == 'Google_Checkout') {
847 // FIXME: we 'll need to make a new separate account for testing
848 $processorSettings = array(
849 'test_user_name' => '559999327053114',
850 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
853 elseif ($processorType == 'PayPal') {
854 $processorSettings = array(
855 'test_user_name' => '559999327053114',
856 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
857 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
860 elseif ($processorType == 'PayPal_Standard') {
861 $processorSettings = array(
862 'test_user_name' => 'V18ki@9r5Bf.org',
865 elseif (empty($processorSettings)) {
866 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
868 $pid = CRM_Core_DAO
::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
870 $this->fail("$processorType processortype not found.");
872 $this->openCiviPage('admin/paymentProcessor', 'action=add&reset=1&pp=' . $pid, 'name');
873 $this->type('name', $processorName);
874 $this->select('financial_account_id', "label={$financialAccount}");
875 foreach ($processorSettings as $f => $v) {
880 $this->clickLink('_qf_PaymentProcessor_next-bottom');
882 $this->waitForTextPresent($processorName);
884 // Get payment processor id
885 $paymentProcessorLink = $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href");
886 return $this->urlArg('id', $paymentProcessorLink);
889 public function webtestAddCreditCardDetails() {
890 $this->waitForElementPresent('credit_card_type');
891 $this->select('credit_card_type', 'label=Visa');
892 $this->type('credit_card_number', '4807731747657838');
893 $this->type('cvv2', '123');
894 $this->select('credit_card_exp_date[M]', 'label=Feb');
895 $this->select('credit_card_exp_date[Y]', 'label=2019');
899 * @param null $firstName
900 * @param null $middleName
901 * @param null $lastName
905 public function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
911 $middleName = 'Apple';
915 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
918 $this->type('billing_first_name', $firstName);
919 $this->type('billing_middle_name', $middleName);
920 $this->type('billing_last_name', $lastName);
922 $this->type('billing_street_address-5', '234 Lincoln Ave');
923 $this->type('billing_city-5', 'San Bernadino');
924 $this->select2('billing_country_id-5', 'United States');
925 $this->select2('billing_state_province_id-5', 'California');
926 $this->type('billing_postal_code-5', '93245');
928 return array($firstName, $middleName, $lastName);
932 * @param $fieldLocator
933 * @param null $filePath
935 * @return null|string
937 public function webtestAttachFile($fieldLocator, $filePath = NULL) {
939 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
940 $fp = @fopen
($filePath, 'w');
941 fwrite($fp, 'Test file created by selenium test.');
945 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
947 $this->attachFile($fieldLocator, "file://{$filePath}");
955 * @param null $filePath
957 * @return null|string
959 public function webtestCreateCSV($headers, $rows, $filePath = NULL) {
961 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
964 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
966 foreach ($rows as $row) {
968 foreach ($headers as $field => $header) {
969 $temp[$field] = isset($row[$field]) ?
'"' . $row[$field] . '"' : '""';
971 $data .= implode(', ', $temp) . "\r\n";
974 $fp = @fopen
($filePath, 'w');
978 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
984 * Create new relationship type w/ user specified params or default.
986 * @param array $params
987 * array of required params.
990 * array of saved params values.
992 public function webtestAddRelationshipType($params = array()) {
993 $this->openCiviPage("admin/reltype", "reset=1&action=add");
995 //build the params if not passed.
996 if (!is_array($params) ||
empty($params)) {
998 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
999 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
1000 'contact_types_a' => 'Individual',
1001 'contact_types_b' => 'Individual',
1002 'description' => 'Test Relationship Type Description',
1005 //make sure we have minimum required params.
1006 if (!isset($params['label_a_b']) ||
empty($params['label_a_b'])) {
1007 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
1010 //start the form fill.
1011 $this->type('label_a_b', $params['label_a_b']);
1012 $this->type('label_b_a', $params['label_b_a']);
1013 $this->select('contact_types_a', "value={$params['contact_type_a']}");
1014 $this->select('contact_types_b', "value={$params['contact_type_b']}");
1015 $this->type('description', $params['description']);
1018 $this->click('_qf_RelationshipType_next-bottom');
1019 $this->waitForPageToLoad($this->getTimeoutMsec());
1022 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
1023 "Status message didn't show up after saving!"
1026 $this->openCiviPage("admin/reltype", "reset=1");
1028 //validate data on selector.
1030 if (isset($data['description'])) {
1031 unset($data['description']);
1033 $this->assertStringsPresent($data);
1039 * Create new online contribution page w/ user specified params or defaults.
1040 * FIXME: this function take an absurd number of params - very unwieldy :(
1044 * @param null $pageTitle
1045 * @param array $processor
1046 * @param bool $amountSection
1047 * @param bool $payLater
1048 * @param bool $onBehalf
1049 * @param bool $pledges
1050 * @param bool $recurring
1051 * @param bool $membershipTypes
1052 * @param int $memPriceSetId
1053 * @param bool $friend
1054 * @param int $profilePreId
1055 * @param int $profilePostId
1056 * @param bool $premiums
1057 * @param bool $widget
1059 * @param bool $isAddPaymentProcessor
1060 * @param bool $isPcpApprovalNeeded
1061 * @param bool $isSeparatePayment
1062 * @param bool $honoreeSection
1063 * @param bool $allowOtherAmount
1064 * @param bool $isConfirmEnabled
1065 * @param string $financialType
1066 * @param bool $fixedAmount
1067 * @param bool $membershipsRequired
1070 * of newly created online contribution page.
1072 public function webtestAddContributionPage(
1076 $processor = array('Test Processor' => 'Dummy'),
1077 $amountSection = TRUE,
1082 $membershipTypes = TRUE,
1083 $memPriceSetId = NULL,
1090 $isAddPaymentProcessor = TRUE,
1091 $isPcpApprovalNeeded = FALSE,
1092 $isSeparatePayment = FALSE,
1093 $honoreeSection = TRUE,
1094 $allowOtherAmount = TRUE,
1095 $isConfirmEnabled = TRUE,
1096 $financialType = 'Donation',
1097 $fixedAmount = TRUE,
1098 $membershipsRequired = TRUE
1101 $hash = substr(sha1(rand()), 0, 7);
1104 $pageTitle = 'Donate Online ' . $hash;
1108 $rand = 2 * rand(2, 50);
1111 // Create a new payment processor if requested
1112 if ($isAddPaymentProcessor) {
1113 while (list($processorName, $processorType) = each($processor)) {
1114 $this->webtestAddPaymentProcessor($processorName, $processorType);
1118 // go to the New Contribution Page page
1119 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
1121 // fill in step 1 (Title and Settings)
1122 $this->type('title', $pageTitle);
1124 //to select financial type
1125 $this->select('financial_type_id', "label={$financialType}");
1128 $this->click('is_organization');
1129 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
1130 $this->type('for_organization', "On behalf $hash");
1132 if ($onBehalf == 'required') {
1133 $this->click('CIVICRM_QFID_2_4');
1135 elseif ($onBehalf == 'optional') {
1136 $this->click('CIVICRM_QFID_1_2');
1140 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1141 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1143 $this->type('goal_amount', 10 * $rand);
1145 // FIXME: handle Start/End Date/Time
1146 if ($honoreeSection) {
1147 $this->click('honor_block_is_active');
1148 $this->type('honor_block_title', "Honoree Section Title $hash");
1149 $this->type('honor_block_text', "Honoree Introductory Message $hash");
1150 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1151 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1152 $this->waitForElementPresent("//*[@class='select2-result-label']");
1153 $this->clickAt("//*[@class='select2-results']/li[1]");
1156 // is confirm enabled? it starts out enabled, so uncheck it if false
1157 if (!$isConfirmEnabled) {
1158 $this->click("id=is_confirm_enabled");
1162 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1164 // Get contribution page id
1165 $pageId = $this->urlArg('id');
1167 // fill in step 2 (Processor, Pay Later, Amounts)
1168 if (!empty($processor)) {
1170 while (list($processorName) = each($processor)) {
1171 // select newly created processor
1172 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1173 $this->assertTrue($this->isTextPresent($processorName));
1174 $this->check($xpath);
1178 if ($amountSection && !$memPriceSetId) {
1180 $this->click('is_pay_later');
1181 $this->type('pay_later_text', "Pay later label $hash");
1182 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1186 $this->click('is_pledge_active');
1187 $this->click('pledge_frequency_unit[week]');
1188 $this->click('is_pledge_interval');
1189 $this->type('initial_reminder_day', 3);
1190 $this->type('max_reminders', 2);
1191 $this->type('additional_reminder_day', 1);
1193 elseif ($recurring) {
1194 $this->click('is_recur');
1195 $this->click("is_recur_interval");
1196 $this->click("is_recur_installments");
1198 if ($allowOtherAmount) {
1200 $this->click('is_allow_other_amount');
1202 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1203 //$this->type('min_amount', $rand / 2);
1204 //$this->type('max_amount', $rand * 10);
1206 if ($fixedAmount ||
!$allowOtherAmount) {
1207 $this->type('label_1', "Label $hash");
1208 $this->type('value_1', "$rand");
1210 $this->click('CIVICRM_QFID_1_4');
1213 $this->click('amount_block_is_active');
1216 $this->click('_qf_Amount_next');
1217 $this->waitForElementPresent('_qf_Amount_next-bottom');
1218 $this->waitForPageToLoad($this->getTimeoutMsec());
1219 $text = "'Amount' information has been saved.";
1220 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1222 if ($memPriceSetId ||
(($membershipTypes === TRUE) ||
(is_array($membershipTypes) && !empty($membershipTypes)))) {
1223 // go to step 3 (memberships)
1224 $this->click('link=Memberships');
1225 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1227 // fill in step 3 (Memberships)
1228 $this->click('member_is_active');
1229 $this->waitForElementPresent('displayFee');
1230 $this->type('new_title', "Title - New Membership $hash");
1231 $this->type('renewal_title', "Title - Renewals $hash");
1233 if ($memPriceSetId) {
1234 $this->click('member_price_set_id');
1235 $this->select('member_price_set_id', "value={$memPriceSetId}");
1238 if ($membershipTypes === TRUE) {
1239 $membershipTypes = array(array('id' => 2));
1242 // FIXME: handle Introductory Message - New Memberships/Renewals
1243 foreach ($membershipTypes as $mType) {
1244 $this->click("membership_type_{$mType['id']}");
1245 if (array_key_exists('default', $mType)) {
1248 if (array_key_exists('auto_renew', $mType)) {
1249 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1252 if ($membershipsRequired) {
1253 $this->click('is_required');
1255 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1256 $this->click('CIVICRM_QFID_2_4');
1257 if ($isSeparatePayment) {
1258 $this->click('is_separate_payment');
1261 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1262 $text = "'MembershipBlock' information has been saved.";
1263 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1266 // go to step 4 (thank-you and receipting)
1267 $this->click('link=Receipt');
1268 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1271 $this->type('thankyou_title', "Thank-you Page Title $hash");
1272 // FIXME: handle Thank-you Message/Page Footer
1273 $this->type('receipt_from_name', "Receipt From Name $hash");
1274 $this->type('receipt_from_email', "$hash@example.org");
1275 $this->type('receipt_text', "Receipt Message $hash");
1276 $this->type('cc_receipt', "$hash@example.net");
1277 $this->type('bcc_receipt', "$hash@example.com");
1279 $this->click('_qf_ThankYou_next');
1280 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1281 $this->waitForPageToLoad($this->getTimeoutMsec());
1282 $text = "'ThankYou' information has been saved.";
1283 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1286 // fill in step 5 (Tell a Friend)
1287 $this->click('link=Tell a Friend');
1288 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1289 $this->click('tf_is_active');
1290 $this->type('tf_title', "TaF Title $hash");
1291 $this->type('intro', "TaF Introduction $hash");
1292 $this->type('suggested_message', "TaF Suggested Message $hash");
1293 $this->type('general_link', "TaF Info Page Link $hash");
1294 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1295 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1297 //$this->click('_qf_Contribute_next');
1298 $this->click('_qf_Contribute_next-bottom');
1299 $this->waitForPageToLoad($this->getTimeoutMsec());
1300 $text = "'Friend' information has been saved.";
1301 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1304 if ($profilePreId ||
$profilePostId) {
1305 // fill in step 6 (Include Profiles)
1306 $this->click('css=li#tab_custom a');
1307 $this->waitForElementPresent('_qf_Custom_next-bottom');
1309 if ($profilePreId) {
1310 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1313 if ($profilePostId) {
1314 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1317 $this->click('_qf_Custom_next-bottom');
1318 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1320 $this->waitForPageToLoad($this->getTimeoutMsec());
1321 $text = "'Custom' information has been saved.";
1322 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1326 // fill in step 7 (Premiums)
1327 $this->click('link=Premiums');
1328 $this->waitForElementPresent('_qf_Premium_next-bottom');
1329 $this->click('premiums_active');
1330 $this->type('premiums_intro_title', "Prem Title $hash");
1331 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1332 $this->type('premiums_contact_email', "$hash@example.info");
1333 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1334 $this->click('premiums_display_min_contribution');
1335 $this->type('premiums_nothankyou_label', 'No thank-you');
1336 $this->click('_qf_Premium_next');
1337 $this->waitForElementPresent('_qf_Premium_next-bottom');
1339 $this->waitForPageToLoad($this->getTimeoutMsec());
1340 $text = "'Premium' information has been saved.";
1341 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1345 // fill in step 8 (Widget Settings)
1346 $this->click('link=Widgets');
1347 $this->waitForElementPresent('_qf_Widget_next-bottom');
1349 $this->click('is_active');
1350 $this->type('url_logo', "URL to Logo Image $hash");
1351 $this->type('button_title', "Button Title $hash");
1352 // Type About text in ckEditor (fieldname, text to type, editor)
1353 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1355 $this->click('_qf_Widget_next');
1356 $this->waitForElementPresent('_qf_Widget_next-bottom');
1358 $this->waitForPageToLoad($this->getTimeoutMsec());
1359 $text = "'Widget' information has been saved.";
1360 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1364 // fill in step 9 (Enable Personal Campaign Pages)
1365 $this->click('link=Personal Campaigns');
1366 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1367 $this->click('pcp_active');
1368 if (!$isPcpApprovalNeeded) {
1369 $this->click('is_approval_needed');
1371 $this->type('notify_email', "$hash@example.name");
1372 $this->select('supporter_profile_id', 'value=2');
1373 $this->type('tellfriend_limit', 7);
1374 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1376 $this->click('_qf_Contribute_next-bottom');
1377 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1378 $this->waitForPageToLoad($this->getTimeoutMsec());
1379 $text = "'Pcp' information has been saved.";
1380 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1387 * Update default strict rule.
1389 * @param string $contactType
1390 * @param array $fields
1391 * Fields to be set for strict rule.
1392 * @param int $threshold
1393 * Rule's threshold value.
1395 public function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1396 // set default strict rule.
1398 if ($contactType == 'Organization') {
1401 elseif ($contactType == 'Household') {
1405 // Default dedupe fields for each Contact type.
1406 if (empty($fields)) {
1407 $fields = array('civicrm_email.email' => 10);
1408 if ($contactType == 'Organization') {
1410 'civicrm_contact.organization_name' => 10,
1411 'civicrm_email.email' => 10,
1414 elseif ($contactType == 'Household') {
1416 'civicrm_contact.household_name' => 10,
1417 'civicrm_email.email' => 10,
1422 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1425 foreach ($fields as $field => $weight) {
1426 $this->select("where_{$count}", "value={$field}");
1427 $this->type("length_{$count}", '');
1428 $this->type("weight_{$count}", $weight);
1433 $this->type('threshold', $threshold);
1435 $this->click('_qf_DedupeRules_next-bottom');
1436 $this->waitForPageToLoad($this->getTimeoutMsec());
1440 for ($i = $count; $i <= 4; $i++
) {
1441 $this->select("where_{$i}", 'label=- none -');
1442 $this->type("length_{$i}", '');
1443 $this->type("weight_{$i}", '');
1446 $this->type('threshold', $threshold);
1449 $this->click('_qf_DedupeRules_next-bottom');
1450 $this->waitForPageToLoad($this->getTimeoutMsec());
1454 * @param string $period_type
1455 * @param int $duration_interval
1456 * @param string $duration_unit
1457 * @param string $auto_renew
1461 public function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1462 $membershipTitle = substr(sha1(rand()), 0, 7);
1463 $membershipOrg = $membershipTitle . ' memorg';
1464 $this->webtestAddOrganization($membershipOrg, TRUE);
1466 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1467 $memTypeParams = array(
1468 'membership_type' => $title,
1469 'member_of_contact' => $membershipOrg,
1470 'financial_type' => 2,
1471 'period_type' => $period_type,
1474 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1476 $this->type('name', $memTypeParams['membership_type']);
1478 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1479 // select the radio first since the element id changes after membership org search results are loaded
1480 switch ($auto_renew) {
1482 $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')]");
1486 $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')]");
1490 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1491 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')]")) {
1492 $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')]");
1497 $this->select2('member_of_contact_id', $membershipTitle);
1499 $this->type('minimum_fee', '100');
1500 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1502 $this->type('duration_interval', $duration_interval);
1503 $this->select('duration_unit', "label={$duration_unit}");
1505 $this->select('period_type', "value={$period_type}");
1507 $this->click('_qf_MembershipType_upload-bottom');
1508 $this->waitForElementPresent('link=Add Membership Type');
1509 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1511 return $memTypeParams;
1515 * @param null $groupName
1516 * @param null $parentGroupName
1518 * @return null|string
1520 public function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1521 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1525 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1527 $this->type('title', $groupName);
1530 $this->type('description', 'Adding new group.');
1532 // check Access Control
1533 $this->click('group_type[1]');
1535 // check Mailing List
1536 $this->click('group_type[2]');
1538 // select Visibility as Public Pages
1539 $this->select('visibility', 'value=Public Pages');
1541 // select parent group
1542 if ($parentGroupName) {
1543 $this->select('parents', "*$parentGroupName");
1547 $this->clickLink('_qf_Edit_upload-bottom');
1549 // Is status message correct?
1550 $this->waitForText('crm-notification-container', "$groupName");
1555 * @param string $activityType
1559 public function WebtestAddActivity($activityType = "Meeting") {
1560 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1561 // We're using Quick Add block on the main page for this.
1562 $firstName1 = substr(sha1(rand()), 0, 7);
1563 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1564 $firstName2 = substr(sha1(rand()), 0, 7);
1565 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1567 $this->click("css=li#tab_activity a");
1569 // waiting for the activity dropdown to show up
1570 $this->waitForElementPresent("other_activity");
1572 // Select the activity type from the activity dropdown
1573 $this->select("other_activity", "label=Meeting");
1575 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1576 $this->waitForElementPresent("s2id_target_contact_id");
1578 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__
);
1580 // Typing contact's name into the field (using typeKeys(), not type()!)...
1581 $this->select2("assignee_contact_id", $firstName1, TRUE);
1583 // ...and verifying if the page contains properly formatted display name for chosen contact.
1584 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__
);
1586 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1587 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1588 // For simple input fields we can use field id as selector
1589 $this->type("subject", $subject);
1590 $this->type("location", "Some location needs to be put in this field.");
1592 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1594 // Setting duration.
1595 $this->type("duration", "30");
1597 // Putting in details.
1598 $this->type("details", "Really brief details information.");
1600 // Making sure that status is set to Scheduled (using value, not label).
1601 $this->select("status_id", "value=1");
1603 // Setting priority.
1604 $this->select("priority_id", "value=1");
1606 // Scheduling follow-up.
1607 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1608 $this->select("followup_activity_type_id", "value=1");
1609 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1610 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1613 $this->click("_qf_Activity_upload-bottom");
1614 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1616 // Is status message correct?
1617 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1619 $this->waitForElementPresent("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1621 // click through to the Activity view screen
1622 $this->clickLinkSuppressPopup("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']", '_qf_Activity_cancel-bottom');
1624 // parse URL to grab the activity id
1625 // pass id back to any other tests that call this class
1626 return $this->urlArg('id');
1632 public static function checkDoLocalDBTest() {
1633 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1634 CIVICRM_WEBTEST_LOCAL_DB
1636 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1643 * Generic function to compare expected values after an api call to retrieved.
1646 * @param string $daoName
1647 * DAO Name of object we're evaluating.
1650 * @param array $match
1651 * Associative array of field name => expected value. Empty if asserting
1652 * that a DELETE occurred
1653 * @param bool $delete
1654 * are we checking that a DELETE action occurred?
1656 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
1657 if (self
::checkDoLocalDBTest()) {
1658 CiviDBAssert
::assertDBState($this, $daoName, $id, $match, $delete);
1663 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1664 * @param string $daoName
1665 * @param string $searchValue
1666 * @param string $returnColumn
1667 * @param string $searchColumn
1668 * @param string $message
1670 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1671 if (self
::checkDoLocalDBTest()) {
1672 CiviDBAssert
::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1677 * Request a record from the DB by searchColumn+searchValue. Success if returnColumn value is NULL.
1678 * @param string $daoName
1679 * @param string $searchValue
1680 * @param string $returnColumn
1681 * @param string $searchColumn
1682 * @param string $message
1684 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1685 if (self
::checkDoLocalDBTest()) {
1686 CiviDBAssert
::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1691 * Request a record from the DB by id. Success if row not found.
1692 * @param string $daoName
1694 * @param string $message
1696 public function assertDBRowNotExist($daoName, $id, $message) {
1697 if (self
::checkDoLocalDBTest()) {
1698 CiviDBAssert
::assertDBRowNotExist($this, $daoName, $id, $message);
1703 * Compare all values in a single retrieved DB record to an array of expected values.
1704 * @param string $daoName
1705 * @param array $searchParams
1706 * @param $expectedValues
1708 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1709 if (self
::checkDoLocalDBTest()) {
1710 CiviDBAssert
::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1717 * @param string $message
1719 public function assertType($expected, $actual, $message = '') {
1720 $this->assertInternalType($expected, $actual, $message);
1724 * Add new Financial Account.
1725 * @param $financialAccountTitle
1726 * @param bool $financialAccountDescription
1727 * @param bool $accountingCode
1728 * @param bool $firstName
1729 * @param bool $financialAccountType
1730 * @param bool $taxDeductible
1731 * @param bool $isActive
1732 * @param bool $isTax
1733 * @param bool $taxRate
1734 * @param bool $isDefault
1736 public function _testAddFinancialAccount(
1737 $financialAccountTitle,
1738 $financialAccountDescription = FALSE,
1739 $accountingCode = FALSE,
1741 $financialAccountType = FALSE,
1742 $taxDeductible = FALSE,
1749 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1751 $this->click("link=Add Financial Account");
1752 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1754 // Financial Account Name
1755 $this->type('name', $financialAccountTitle);
1757 // Financial Description
1758 if ($financialAccountDescription) {
1759 $this->type('description', $financialAccountDescription);
1763 if ($accountingCode) {
1764 $this->type('accounting_code', $accountingCode);
1767 // Autofill Organization
1769 $this->webtestOrganisationAutocomplete($firstName);
1772 // Financial Account Type
1773 if ($financialAccountType) {
1774 $this->select('financial_account_type_id', "label={$financialAccountType}");
1777 // Is Tax Deductible
1778 if ($taxDeductible) {
1779 $this->check('is_deductible');
1782 $this->uncheck('is_deductible');
1786 $this->check('is_active');
1789 $this->uncheck('is_active');
1793 $this->check('is_tax');
1796 $this->uncheck('is_tax');
1800 $this->type('tax_rate', $taxRate);
1805 $this->check('is_default');
1808 $this->uncheck('is_default');
1810 $this->click('_qf_FinancialAccount_next-botttom');
1814 * Edit Financial Account.
1815 * @param $editfinancialAccount
1816 * @param bool $financialAccountTitle
1817 * @param bool $financialAccountDescription
1818 * @param bool $accountingCode
1819 * @param bool $firstName
1820 * @param bool $financialAccountType
1821 * @param bool $taxDeductible
1822 * @param bool $isActive
1823 * @param bool $isTax
1824 * @param bool $taxRate
1825 * @param bool $isDefault
1827 public function _testEditFinancialAccount(
1828 $editfinancialAccount,
1829 $financialAccountTitle = FALSE,
1830 $financialAccountDescription = FALSE,
1831 $accountingCode = FALSE,
1833 $financialAccountType = FALSE,
1834 $taxDeductible = FALSE,
1841 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1844 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']");
1845 $this->clickLink("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1847 // Change Financial Account Name
1848 if ($financialAccountTitle) {
1849 $this->type('name', $financialAccountTitle);
1852 // Financial Description
1853 if ($financialAccountDescription) {
1854 $this->type('description', $financialAccountDescription);
1858 if ($accountingCode) {
1859 $this->type('accounting_code', $accountingCode);
1862 // Autofill Edit Organization
1864 $this->webtestOrganisationAutocomplete($firstName);
1867 // Financial Account Type
1868 if ($financialAccountType) {
1869 $this->select('financial_account_type_id', "label={$financialAccountType}");
1872 // Is Tax Deductible
1873 if ($taxDeductible) {
1874 $this->check('is_deductible');
1877 $this->uncheck('is_deductible');
1882 $this->check('is_tax');
1885 $this->uncheck('is_tax');
1890 $this->type('tax_rate', $taxRate);
1895 $this->check('is_default');
1898 $this->uncheck('is_default');
1903 $this->check('is_active');
1906 $this->uncheck('is_active');
1908 $this->click('_qf_FinancialAccount_next-botttom');
1909 $this->waitForElementPresent('link=Add Financial Account');
1913 * Delete Financial Account.
1914 * @param $financialAccountTitle
1916 public function _testDeleteFinancialAccount($financialAccountTitle) {
1917 $this->click("xpath=//table/tbody//tr/td[1]/div[text()='{$financialAccountTitle}']/../../td[9]/span/a[text()='Delete']");
1918 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1919 $this->click('_qf_FinancialAccount_next-botttom');
1920 $this->waitForElementPresent('link=Add Financial Account');
1921 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1925 * Verify data after ADD and EDIT.
1926 * @param $verifyData
1928 public function _assertFinancialAccount($verifyData) {
1929 foreach ($verifyData as $key => $expectedValue) {
1930 $actualValue = $this->getValue($key);
1931 if ($key == 'parent_financial_account') {
1932 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1935 $this->assertEquals($expectedValue, $actualValue);
1941 * @param $verifySelectFieldData
1943 public function _assertSelectVerify($verifySelectFieldData) {
1944 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1945 $actualvalue = $this->getSelectedLabel($key);
1946 $this->assertEquals($expectedvalue, $actualvalue);
1951 * @param $financialType
1952 * @param string $option
1954 public function addeditFinancialType($financialType, $option = 'new') {
1955 $this->openCiviPage("admin/financial/financialType", "reset=1");
1957 if ($option == 'Delete') {
1958 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]");
1959 $this->waitForElementPresent("css=span.btn-slide-active");
1960 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]/ul/li[2]/a");
1961 $this->waitForElementPresent("_qf_FinancialType_next");
1962 $this->click("_qf_FinancialType_next");
1963 $this->waitForElementPresent("newFinancialType");
1964 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1967 if ($option == 'new') {
1968 $this->click("link=Add Financial Type");
1971 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[oldname]']/../../td[7]/span/a[text()='Edit']");
1973 $this->waitForElementPresent("name");
1974 $this->type('name', $financialType['name']);
1975 if ($option == 'new') {
1976 $this->type('description', $financialType['name'] . ' description');
1979 if ($financialType['is_reserved']) {
1980 $this->check('is_reserved');
1983 $this->uncheck('is_reserved');
1986 if ($financialType['is_deductible']) {
1987 $this->check('is_deductible');
1990 $this->uncheck('is_deductible');
1993 $this->click('_qf_FinancialType_next');
1994 if ($option == 'new') {
1995 $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.";
1998 $text = "The financial type \"{$financialType['name']}\" has been updated.";
2000 $this->checkCRMAlert($text);
2004 * Give the specified permissions.
2005 * Note: this function logs in as 'admin' (logging out if necessary)
2006 * @param $permission
2008 public function changePermissions($permission) {
2009 $this->webtestLogin('admin');
2010 $this->open("{$this->sboxPath}admin/people/permissions");
2011 $this->waitForElementPresent('edit-submit');
2012 foreach ((array) $permission as $perm) {
2013 $this->check($perm);
2015 $this->click('edit-submit');
2016 $this->waitForPageToLoad($this->getTimeoutMsec());
2017 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
2021 * @param $profileTitle
2022 * @param $profileFields
2024 public function addProfile($profileTitle, $profileFields) {
2025 $this->openCiviPage('admin/uf/group', "reset=1");
2027 $this->clickLink('link=Add Profile', '_qf_Group_cancel-bottom');
2028 $this->type('title', $profileTitle);
2029 $this->clickLink('_qf_Group_next-bottom');
2031 $this->waitForText('crm-notification-container', "Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now.");
2033 foreach ($profileFields as $field) {
2034 $this->waitForElementPresent('field_name_0');
2035 $this->click("id=field_name_0");
2036 $this->select("id=field_name_0", "label=" . $field['type']);
2037 $this->waitForElementPresent('field_name_1');
2038 $this->click("id=field_name_1");
2039 $this->select("id=field_name_1", "label=" . $field['name']);
2040 $this->waitForElementPresent('label');
2041 $this->type("id=label", $field['label']);
2042 $this->click("id=_qf_Field_next_new-top");
2043 $this->waitForElementPresent("xpath=//select[@id='field_name_1'][@style='display: none;']");
2044 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
2049 * @param string $name
2054 * @param $financialType
2056 public function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
2057 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
2058 $this->type("name", $name);
2059 $this->type("sku", $sku);
2060 $this->click("CIVICRM_QFID_noImage_16");
2061 $this->type("min_contribution", $amount);
2062 $this->type("price", $price);
2063 $this->type("cost", $cost);
2064 if ($financialType) {
2065 $this->select("financial_type_id", "label={$financialType}");
2067 $this->click("_qf_ManagePremiums_upload-bottom");
2068 $this->waitForPageToLoad($this->getTimeoutMsec());
2073 * @param $financialAccount
2075 public function addPaymentInstrument($label, $financialAccount) {
2076 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
2077 $this->type("label", $label);
2078 $this->select("financial_account_id", "value=$financialAccount");
2079 $this->click("_qf_Options_next-bottom");
2080 $this->waitForPageToLoad($this->getTimeoutMsec());
2084 * Ensure we have a default mailbox set up for CiviMail.
2086 public function setupDefaultMailbox() {
2087 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
2088 // Check if it hasn't already been set up
2089 if (!$this->getSelectedValue('protocol')) {
2090 $this->type('name', 'Test Domain');
2091 $this->select('protocol', "IMAP");
2092 $this->type('server', 'localhost');
2093 $this->type('domain', 'example.com');
2094 $this->clickLink('_qf_MailSettings_next-top');
2099 * Determine the default time-out in milliseconds.
2101 * @return string, timeout expressed in milliseconds
2103 public function getTimeoutMsec() {
2104 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
2105 $timeout = ($this->settings
&& @$this->settings
->timeout
) ?
($this->settings
->timeout
* 1000) : 30000;
2106 return (string) $timeout; // don't know why, but all our old code used a string
2111 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
2114 * @param array $customSets
2115 * Custom sets i.e entity wise sets want to be created and checked.
2116 * e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
2117 * 'triggerElement' => $triggerElement))
2118 * array $triggerElement: the element which is responsible for custom group to load
2120 * which uses the entity info as its selection value
2121 * @param array $pageUrl
2122 * The url which on which the ajax custom group load takes place.
2123 * @param string $beforeTriggering
2126 public function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
2127 // FIXME: Testing a theory that these failures have something to do with permissions
2128 $this->webtestLogin('admin');
2130 //add the custom set
2131 $return = $this->addCustomGroupField($customSets);
2133 // FIXME: Hack to ensure caches are properly cleared
2135 $userName = $this->loggedInAs
;
2136 $this->webtestLogout();
2137 $this->webtestLogin($userName);
2140 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
2142 // FIXME: Try to find out what the heck is going on with these tests
2143 $this->waitForAjaxContent();
2144 $this->checkForErrorsOnPage();
2146 foreach ($return as $values) {
2147 foreach ($values as $entityType => $customData) {
2148 //initiate necessary variables
2149 list($entity, $entityData) = explode('_', $entityType);
2150 $elementType = CRM_Utils_Array
::value('type', $customData['triggerElement'], 'select');
2151 $elementName = CRM_Utils_Array
::value('name', $customData['triggerElement']);
2152 if (is_callable($beforeTriggering)) {
2153 call_user_func($beforeTriggering);
2155 if ($elementType == 'select') {
2156 //reset the select box, so triggering of ajax only happens
2157 //WRT input of value in this function
2158 $this->select($elementName, "index=0");
2160 if (!empty($entityData)) {
2161 if ($elementType == 'select') {
2162 $this->select($elementName, "label=regexp:{$entityData}");
2164 elseif ($elementType == 'checkbox') {
2165 $val = explode(',', $entityData);
2166 foreach ($val as $v) {
2167 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2168 $this->check($checkId);
2171 elseif ($elementType == 'select2') {
2172 $this->select2($elementName, $entityData);
2175 // FIXME: Try to find out what the heck is going on with these tests
2176 $this->waitForAjaxContent();
2177 $this->checkForErrorsOnPage();
2179 //checking for proper custom data which is loading through ajax
2180 $this->waitForElementPresent("css=.custom-group-{$customData['cgtitle']}");
2181 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2182 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2188 * @param $customSets
2192 public function addCustomGroupField($customSets) {
2194 foreach ($customSets as $customSet) {
2195 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2197 //fill custom group title
2198 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2199 $this->click("title");
2200 $this->type("title", $customGroupTitle);
2202 //custom group extends
2203 $this->click("extends_0");
2204 $this->select("extends_0", "value={$customSet['entity']}");
2205 if (!empty($customSet['subEntity'])) {
2206 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2210 $this->uncheck('collapse_display');
2213 $this->click('_qf_Group_next-bottom');
2215 //Is custom group created?
2216 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2218 $gid = $this->urlArg('gid');
2219 $this->waitForTextPresent("{$customGroupTitle} - New Field");
2221 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2222 $this->waitForElementPresent('label');
2223 $this->type('label', $fieldLabel);
2224 $this->click('_qf_Field_done-bottom');
2226 $this->waitForText('crm-notification-container', $fieldLabel);
2227 $this->waitForAjaxContent();
2229 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2231 "{$customSet['entity']}_{$customSet['subEntity']}" => array(
2232 'cgtitle' => $customGroupTitle,
2234 'triggerElement' => $customSet['triggerElement'],
2238 // Go home for a sec to give time for caches to clear
2239 $this->openCiviPage('');
2245 * Type and select first occurance of autocomplete.
2248 * @param bool $multiple
2249 * @param bool $xpath
2251 public function select2($fieldName, $label, $multiple = FALSE, $xpath = FALSE) {
2252 // In the case of chainSelect, wait for options to load
2253 $this->waitForElementNotPresent('css=select.loading');
2255 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2256 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2257 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2258 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2259 $this->waitForElementPresent("//*[@class='select2-result-label']");
2260 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2264 $this->clickAt($fieldName);
2267 $this->clickAt("//*[@id='$fieldName']/../div/a");
2269 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2270 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2271 $this->type("//*[@id='select2-drop']/div/input", $label);
2272 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
2273 $this->waitForElementPresent("//*[@class='select2-result-label']");
2274 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2276 // Wait a sec for select2 to update the original element
2281 * Select multiple options.
2285 public function multiselect2($fieldid, $params) {
2286 // In the case of chainSelect, wait for options to load
2287 $this->waitForElementNotPresent('css=select.loading');
2288 foreach ($params as $value) {
2289 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2290 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2291 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2292 $this->assertElementContainsText("xpath=//*[@id='$fieldid']/preceding-sibling::div[1]/", $value);
2294 // Wait a sec for select2 to update the original element
2299 * Check for unobtrusive status message as set by CRM.status
2302 public function checkCRMStatus($text = NULL) {
2303 $this->waitForElementPresent("css=.crm-status-box-outer.status-success");
2305 $this->assertElementContainsText("css=.crm-status-box-outer.status-success", $text);
2310 * Check for obtrusive status message as set by CRM.alert
2312 * @param string $type
2314 public function checkCRMAlert($text, $type = 'success') {
2315 $this->waitForElementPresent("css=div.ui-notify-message.$type");
2316 $this->waitForText("css=div.ui-notify-message.$type", $text);
2317 // We got the message, now let's close it so the webtest doesn't get confused by lots of open alerts
2318 $this->click('css=.ui-notify-cross');
2322 * Enable or disable Pop-ups via Display Preferences
2323 * @param bool $enabled
2325 public function enableDisablePopups($enabled = TRUE) {
2326 $this->openCiviPage('admin/setting/preferences/display', 'reset=1');
2327 $isChecked = $this->isChecked('ajaxPopupsEnabled');
2328 if (($isChecked && !$enabled) ||
(!$isChecked && $enabled)) {
2329 $this->click('ajaxPopupsEnabled');
2332 $this->assertChecked('ajaxPopupsEnabled');
2335 $this->assertNotChecked('ajaxPopupsEnabled');
2337 $this->clickLink("_qf_Display_next-bottom");
2341 * Attempt to get information about what went wrong if we encounter an error when loading a page.
2343 public function checkForErrorsOnPage() {
2344 foreach (array('Access denied', 'Page not found') as $err) {
2345 if ($this->isElementPresent("xpath=//h1[contains(., '$err')]")) {
2346 $this->fail("'$err' encountered at " . $this->getLocation() . "\nwhile logged in as '{$this->loggedInAs}'");
2349 if ($this->isElementPresent("xpath=//span[text()='Sorry but we are not able to provide this at the moment.']")) {
2350 $msg = '"Fatal Error" encountered at ' . $this->getLocation();
2351 if ($this->isElementPresent('css=div.crm-section.crm-error-message')) {
2352 $msg .= "\nError Message: " . $this->getText('css=div.crm-section.crm-error-message');