3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 define('CIVICRM_WEBTEST', 1);
31 * Base class for CiviCRM Selenium tests
33 * Common functions for unit tests
36 class CiviSeleniumTestCase
extends PHPUnit_Extensions_SeleniumTestCase
{
38 // Current logged-in user
39 protected $loggedInAs = NULL;
41 private $settingCache;
46 * Because we are overriding the parent class constructor, we
47 * need to show the same arguments as exist in the constructor of
48 * PHPUnit_Framework_TestCase, since
49 * PHPUnit_Framework_TestSuite::createTest() creates a
50 * ReflectionClass of the Test class and checks the constructor
51 * of that class to decide how to set up the test.
55 * @param string $dataName
56 * @param array $browser
58 public function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
59 parent
::__construct($name, $data, $dataName, $browser);
60 $this->loggedInAs
= NULL;
62 if (!empty($GLOBALS['_CV'])) {
63 require_once 'CiviSeleniumSettings.auto.php';
65 elseif (CRM_Utils_File
::isIncludable('CiviSeleniumSettings.php')) {
66 require_once 'CiviSeleniumSettings.php';
69 throw new RuntimeException("Cannot initialize Selenium test. Please setup CiviSeleniumSettings.php or configure \"cv\".");
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
);
104 $this->settingCache
= array();
110 protected function prepareTestSession() {
111 $result = parent
::prepareTestSession();
113 // Set any cookies required by local installation
114 // Note: considered doing this in setUp(), but the Selenium session wasn't yet initialized.
115 if (property_exists($this->settings
, 'cookies')) {
116 // We don't really care about this page, but it seems we need
117 // to open a page before setting a cookie.
118 $this->open($this->sboxPath
);
119 $this->waitForPageToLoad($this->getTimeoutMsec());
120 $this->setCookies($this->settings
->cookies
);
126 * @param array $cookies
127 * Each item is an Array with keys:
129 * - value: string; note that RFC's don't define particular encoding scheme, so
130 * you must pick one yourself and pre-encode; does not allow values with
131 * commas, semicolons, or whitespace
132 * - path: string; default: '/'
133 * - max_age: int; default: 1 week (7*24*60*60)
135 protected function setCookies($cookies) {
136 foreach ($cookies as $cookie) {
137 if (!isset($cookie['path'])) {
138 $cookie['path'] = '/';
140 if (!isset($cookie['max_age'])) {
141 $cookie['max_age'] = 7 * 24 * 60 * 60;
143 $this->deleteCookie($cookie['name'], $cookie['path']);
144 $optionExprs = array();
145 foreach ($cookie as $key => $value) {
146 if ($key != 'name' && $key != 'value') {
147 $optionExprs[] = "$key=$value";
150 $this->createCookie("{$cookie['name']}={$cookie['value']}", implode(', ', $optionExprs));
154 protected function tearDown() {
158 * Authenticate as drupal user.
159 * @param $user : (str) the key 'user' or 'admin', or a literal username
160 * @param $pass : (str) if $user is a literal username and not 'user' or 'admin', supply the password
162 public function webtestLogin($user = 'user', $pass = NULL) {
163 // If already logged in as correct user, do nothing
164 if ($this->loggedInAs
=== $user) {
167 // If we are logged in as a different user, log out first
168 if ($this->loggedInAs
) {
169 $this->webtestLogout();
171 $this->open("{$this->sboxPath}user");
172 // Lookup username & password if not supplied
174 if ($pass === NULL) {
175 $pass = $user == 'admin' ?
$this->settings
->adminPassword
: $this->settings
->password
;
176 $username = $user == 'admin' ?
$this->settings
->adminUsername
: $this->settings
->username
;
178 // Make sure login form is available
179 $this->waitForElementPresent('edit-submit');
180 $this->type('edit-name', $username);
181 $this->type('edit-pass', $pass);
182 $this->click('edit-submit');
183 $this->waitForPageToLoad($this->getTimeoutMsec());
184 $this->loggedInAs
= $user;
187 public function webtestLogout() {
188 if ($this->loggedInAs
) {
189 $this->open($this->sboxPath
. "user/logout");
190 $this->waitForPageToLoad($this->getTimeoutMsec());
192 $this->loggedInAs
= NULL;
196 * Open an internal path beginning with 'civicrm/'
199 * omit the 'civicrm/' it will be added for you.
200 * @param string|array $args
201 * optional url arguments.
203 * Page element to wait for - using this is recommended to ensure the document is fully loaded.
205 * Although it doesn't seem to do much now, using this function is recommended for
206 * opening all civi pages, and using the $args param is also strongly encouraged
207 * This will make it much easier to run webtests in other CMSs in the future
209 public function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
210 // Construct full url with args
211 // This could be extended in future to work with other CMS style urls
213 if (is_array($args)) {
215 foreach ($args as $key => $val) {
216 $url .= $sep . $key . '=' . $val;
224 $this->open("{$this->sboxPath}civicrm/$url");
225 $this->waitForPageToLoad($this->getTimeoutMsec());
226 $this->checkForErrorsOnPage();
228 $this->waitForElementPresent($waitFor);
233 * Click on a link or button.
234 * Wait for the page to load
235 * Wait for an element to be present
237 * @param string $waitFor
238 * @param bool $waitForPageLoad
240 public function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
241 $this->click($element);
242 // conditional wait for page load e.g for ajax form save
243 if ($waitForPageLoad) {
244 $this->waitForPageToLoad($this->getTimeoutMsec());
245 $this->checkForErrorsOnPage();
248 $this->waitForElementPresent($waitFor);
253 * Click a link or button and wait for an ajax dialog to load.
254 * @param string $element
255 * @param string $waitFor
257 public function clickPopupLink($element, $waitFor = NULL) {
258 $this->clickAjaxLink($element, 'css=.ui-dialog');
260 $this->waitForElementPresent($waitFor);
265 * Click a link or button and wait for ajax content to load or refresh.
266 * @param string $element
267 * @param string $waitFor
269 public function clickAjaxLink($element, $waitFor = NULL) {
270 $this->click($element);
272 $this->waitForElementPresent($waitFor);
274 $this->waitForAjaxContent();
278 * Force a link to open full-page, even if it would normally open in a popup
279 * @note: works with links only, not buttons
280 * @param string $element
281 * @param string $waitFor
283 public function clickLinkSuppressPopup($element, $waitFor = 'civicrm-footer') {
284 $link = $this->getAttribute($element . '@href');
286 $this->waitForPageToLoad($this->getTimeoutMsec());
288 $this->waitForElementPresent($waitFor);
293 * Wait for all ajax snippets to finish loading.
295 public function waitForAjaxContent() {
296 $this->waitForElementNotPresent('css=.blockOverlay');
297 // Some ajax calls happen in pairs (e.g. submit a popup form then refresh the underlying content)
298 // So we'll wait a sec and recheck to see if any more stuff is loading
300 if ($this->isElementPresent('css=.blockOverlay')) {
301 $this->waitForAjaxContent();
306 * Call the API on the local server.
307 * (kind of defeats the point of a webtest - see CRM-11889)
313 public function webtest_civicrm_api($entity, $action, $params) {
314 if (!isset($params['version'])) {
315 $params['version'] = 3;
318 $result = civicrm_api($entity, $action, $params);
319 $this->assertAPISuccess($result);
324 * Call the API on the remote server using the AJAX endpoint.
329 * @param array $params
332 public function rest_civicrm_api($entity, $action, $params = array()) {
340 setTimeout(function(){
341 CRM.api3("@entity", "@action", @params).then(function(a){
342 cj("<textarea>").css("display", "none").prop("id","crmajax@reqId").val(JSON.stringify(a)).appendTo("body");
347 '@entity' => $entity,
348 '@action' => $action,
349 '@params' => json_encode($params),
352 $js = strtr($jsCmd, $jsArgs);
353 $this->runScript($js);
354 $this->waitForElementPresent("crmajax{$reqId}");
355 $result = json_decode($this->getValue("crmajax{$reqId}"), TRUE);
356 $this->runScript("cj('#crmajax{$reqId}').remove();");
361 * @param string $option_group_name
365 public function webtestGetFirstValueForOptionGroup($option_group_name) {
366 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
367 'option_group_name' => $option_group_name,
377 public function webtestGetValidCountryID() {
379 if (is_null($_country_id)) {
380 $_country_id = $this->webtestGetSetting('defaultContactCountry');
390 public function webtestGetValidEntityID($entity) {
391 // michaelmcandrew: would like to use getvalue but there is a bug
392 // for e.g. group where option.limit not working at the moment CRM-9110
393 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
394 if (!empty($result['values'])) {
395 return current(array_keys($result['values']));
401 * @param string $field
404 public function webtestGetSetting($field) {
405 if (!isset($this->settingCache
[$field])) {
406 $result = $this->webtest_civicrm_api("Setting", "getsingle", array(
409 $this->settingCache
[$field] = $result[$field];
411 return $this->settingCache
[$field];
415 * Ensures the required CiviCRM components are enabled.
418 public function enableComponents($components) {
419 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
420 $enabledComponents = $this->getSelectOptions("enableComponents-t");
422 foreach ((array) $components as $comp) {
423 if (!in_array($comp, $enabledComponents)) {
424 $this->addSelection("enableComponents-f", "label=$comp");
425 $this->click("//option[@value='$comp']");
431 $this->clickLink("_qf_Component_next-bottom");
432 $this->checkCRMAlert("Saved");
437 * Add a contact with the given first and last names and either a given email.
438 * (when specified), a random email (when true) or no email (when unspecified or null).
440 * @param string $fname
441 * Contact’s first name.
442 * @param string $lname
443 * Contact’s last name.
444 * @param mixed $email
445 * Contact’s email (when string) or random email (when true) or no email (when null).
446 * @param string $contactSubtype
448 * @return string|null
449 * either a string with the (either generated or provided) email or null (if no email)
451 public function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
452 $args = 'reset=1&ct=Individual';
453 if ($contactSubtype) {
454 $args .= "&cst={$contactSubtype}";
456 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
457 $this->type('first_name', $fname);
458 $this->type('last_name', $lname);
459 if ($email === TRUE) {
460 $email = substr(sha1(rand()), 0, 7) . '@example.org';
463 $this->type('email_1_email', $email);
465 $this->clickLink('_qf_Contact_upload_view-bottom');
470 * @param string $householdName
473 * @return null|string
475 public function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
476 $this->openCiviPage("contact/add", "reset=1&ct=Household");
477 $this->click('household_name');
478 $this->type('household_name', $householdName);
480 if ($email === TRUE) {
481 $email = substr(sha1(rand()), 0, 7) . '@example.org';
484 $this->type('email_1_email', $email);
487 $this->clickLink('_qf_Contact_upload_view');
492 * @param string $organizationName
494 * @param null $contactSubtype
496 * @return null|string
498 public function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
499 $args = 'reset=1&ct=Organization';
500 if ($contactSubtype) {
501 $args .= "&cst={$contactSubtype}";
503 $this->openCiviPage('contact/add', $args, '_qf_Contact_upload_view-bottom');
504 $this->click('organization_name');
505 $this->type('organization_name', $organizationName);
507 if ($email === TRUE) {
508 $email = substr(sha1(rand()), 0, 7) . '@example.org';
511 $this->type('email_1_email', $email);
513 $this->clickLink('_qf_Contact_upload_view');
519 * @param string $fieldName
521 public function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
522 $this->select2($fieldName, $sortName);
523 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
529 public function webtestOrganisationAutocomplete($sortName) {
530 $this->clickAt("//*[@id='contact_id']/../div/a");
531 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
532 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
533 $this->type("//*[@id='select2-drop']/div/input", $sortName);
534 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
535 $this->waitForElementPresent("//*[@class='select2-result-label']");
536 $this->clickAt("//*[@class='select2-results']/li[1]");
537 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
541 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
542 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
543 * 3. Examples of $strToTime arguments -
544 * webtestFillDate('start_date',"now")
545 * webtestFillDate('start_date',"10 September 2000")
546 * webtestFillDate('start_date',"+1 day")
547 * webtestFillDate('start_date',"+1 week")
548 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
549 * webtestFillDate('start_date',"next Thursday")
550 * webtestFillDate('start_date',"last Monday")
551 * @param $dateElement
552 * @param null $strToTimeArgs
554 public function webtestFillDate($dateElement, $strToTimeArgs = NULL, $multiselect = FALSE) {
555 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
557 $year = date('Y', $timeStamp);
558 // -1 ensures month number is inline with calender widget's month
559 $mon = date('n', $timeStamp) - 1;
560 $day = date('j', $timeStamp);
563 $this->click("xpath=//input[starts-with(@id, '{$dateElement}_display_')]");
565 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
566 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
567 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
568 $this->click("link=$day");
572 * 1. set both date and time.
573 * @param $dateElement
574 * @param null $strToTimeArgs
576 public function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
577 $this->webtestFillDate($dateElement, $strToTimeArgs);
579 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
580 $hour = date('h', $timeStamp);
581 $min = date('i', $timeStamp);
582 $meri = date('A', $timeStamp);
584 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
588 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
590 * @param array $expected
591 * Array of key/value pairs (like Status/Registered) to be checked.
592 * @param string $xpathPrefix
593 * Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath.
594 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
595 * @param string $tableId
596 * Pass in the id attribute of a table to be verified if you want to only check a specific table.
599 public function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
602 $tableLocator = "[@id='$tableId']";
604 foreach ($expected as $label => $value) {
606 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
607 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value));
610 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
611 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value));
617 * Types text into a ckEditor rich text field in a form.
619 * @param string $fieldName
620 * Form field name (as assigned by PHP buildForm class).
621 * @param string $text
622 * Text to type into the field.
623 * @param string $editor
624 * Which text editor (valid values are 'CKEditor', 'TinyMCE').
626 * @param bool $compressed
627 * @throws \PHPUnit_Framework_AssertionFailedError
629 public function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor', $compressed = FALSE) {
630 // make sure cursor focuses on the field
631 $this->fireEvent($fieldName, 'focus');
632 if ($editor == 'CKEditor') {
634 $this->click("xpath=//textarea[@id='{$fieldName}']/../div[1]");
636 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
637 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
639 elseif ($editor == 'TinyMCE') {
640 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
641 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
644 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
646 $this->selectFrame('relative=top');
650 * Types option label and name into a table of multiple choice options.
651 * (for price set fields of type select, radio, or checkbox)
652 * TODO: extend for custom field multiple choice table input
654 * @param array $options
655 * Form field name (as assigned by PHP buildForm class).
656 * @param array $validateStrings
657 * Appends label and name strings to this array so they can be validated later.
661 public function addMultipleChoiceOptions($options, &$validateStrings) {
662 foreach ($options as $oIndex => $oValue) {
663 $validateStrings[] = $oValue['label'];
664 $validateStrings[] = $oValue['amount'];
665 if (!empty($oValue['membership_type_id'])) {
666 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
668 if (!empty($oValue['financial_type_id'])) {
669 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
671 $this->type("option_label_{$oIndex}", $oValue['label']);
672 $this->type("option_amount_{$oIndex}", $oValue['amount']);
673 $this->click('link=another choice');
678 * Use a contact EntityRef field to add a new contact.
679 * @param string $field
681 * @param string $contactType
683 * Array of contact attributes (id, names, email)
685 public function createDialogContact($field = 'contact_id', $contactType = 'Individual') {
686 $selectId = 's2id_' . $this->getAttribute($field . '@id');
687 $this->clickAt("xpath=//div[@id='$selectId']/a");
688 $this->clickAjaxLink("xpath=//li[@class='select2-no-results']//a[contains(text(), 'New $contactType')]", '_qf_Edit_next');
690 $name = substr(sha1(rand()), 0, rand(6, 8));
692 if ($contactType == 'Individual') {
693 $params['first_name'] = "$name $contactType";
694 $params['last_name'] = substr(sha1(rand()), 0, rand(5, 9));
697 $params[strtolower($contactType) . '_name'] = "$name $contactType";
699 foreach ($params as $param => $val) {
700 $this->type($param, $val);
702 $this->type('email-Primary', $params['email'] = "{$name}@example.com");
703 $this->clickAjaxLink('_qf_Edit_next');
705 $this->waitForText("xpath=//div[@id='$selectId']", "$name");
707 $params['sort_name'] = $contactType == 'Individual' ?
$params['last_name'] . ', ' . $params['first_name'] : "$name $contactType";
708 $params['display_name'] = $contactType == 'Individual' ?
$params['first_name'] . ' ' . $params['last_name'] : $params['sort_name'];
709 $params['id'] = $this->getValue($field);
714 * @deprecated in favor of createDialogContact
715 * @param string $fname
716 * @param string $lname
717 * @param string $email
719 * @param string $selectId
721 * @param string $prefix
723 public function webtestNewDialogContact(
724 $fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
725 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
726 // 4 - Individual profile
727 // 5 - Organization profile
728 // 6 - Household profile
729 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
730 $this->clickAt("xpath=//div[@id='$selectId']/a");
731 $this->clickPopupLink("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]", '_qf_Edit_next');
735 $this->type('first_name', $fname);
736 $this->type('last_name', $lname);
740 $this->type('organization_name', $fname);
744 $this->type('household_name', $fname);
748 $this->type('email-Primary', $email);
749 $this->clickAjaxLink('_qf_Edit_next');
751 // Is new contact created?
753 $this->waitForText("xpath=//div[@id='$selectId']", "$lname, $fname");
756 $this->waitForText("xpath=//div[@id='$selectId']", "$fname");
761 * Generic function to check that strings are present in the page.
763 * @strings array array of strings or a single string
768 public function assertStringsPresent($strings) {
769 foreach ((array) $strings as $string) {
770 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
775 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
777 * @url string url to parse or retrieve current url if null
781 * returns an associative array containing any of the various components
782 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
783 * http://php.net/manual/en/function.parse-url.php
785 public function parseURL($url = NULL) {
787 $url = $this->getLocation();
790 $elements = parse_url($url);
791 if (!empty($elements['query'])) {
792 $elements['queryString'] = array();
793 parse_str($elements['query'], $elements['queryString']);
799 * Returns a single argument from the url query.
804 public function urlArg($arg, $url = NULL) {
805 $elements = $this->parseURL($url);
806 return isset($elements['queryString'][$arg]) ?
$elements['queryString'][$arg] : NULL;
810 * Define a payment processor for use by a webtest. Default is to create Dummy processor
811 * which is useful for testing online public forms (online contribution pages and event registration)
813 * @param string $processorName
814 * Name assigned to new processor.
815 * @param string $processorType
816 * Name for processor type (e.g. PayPal, Dummy, etc.).
817 * @param array $processorSettings
818 * Array of fieldname => value for required settings for the processor.
820 * @param string $financialAccount
821 * @throws PHPUnit_Framework_AssertionFailedError
824 public function webtestAddPaymentProcessor($processorName = 'Test Processor', $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
825 if (!$processorName) {
826 $this->fail("webTestAddPaymentProcessor requires $processorName.");
828 // Ensure we are logged in as admin before we proceed
829 $this->webtestLogin('admin');
831 if ($processorName === 'Test Processor') {
832 // Use the default test processor, no need to create a new one
833 $this->openCiviPage('admin/paymentProcessor', 'action=update&id=1&reset=1', '_qf_PaymentProcessor_cancel-bottom');
834 $this->check('is_default');
835 $this->select('financial_account_id', "label={$financialAccount}");
836 $this->clickLink('_qf_PaymentProcessor_next-bottom');
840 if ($processorType == 'Dummy') {
841 $processorSettings = array(
842 'user_name' => 'dummy',
843 'url_site' => 'http://dummy.com',
844 'test_user_name' => 'dummytest',
845 'test_url_site' => 'http://dummytest.com',
848 elseif ($processorType == 'AuthNet') {
849 // FIXME: we 'll need to make a new separate account for testing
850 $processorSettings = array(
851 //dummy live username/password are passed to bypass processor validation on live credential
852 'user_name' => '3HcY62mY',
853 'password' => '69943NrwaQA92b8J',
854 'test_user_name' => '5ULu56ex',
855 'password' => '7ARxW575w736eF5p',
856 'test_password' => '7ARxW575w736eF5p',
859 elseif ($processorType == 'PayPal') {
860 $processorSettings = array(
861 'test_user_name' => '559999327053114',
862 'user_name' => '559999327053114',
863 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
864 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
865 'password' => 'R2zv2g60-A7GXKJYl0nR0g',
866 'signature' => 'R2zv2g60-A7GXKJYl0nR0g',
869 elseif ($processorType == 'PayPal_Standard') {
870 $processorSettings = array(
871 'user_name' => 'V18ki@9r5Bf.org',
872 'test_user_name' => 'V18ki@9r5Bf.org',
875 elseif (empty($processorSettings)) {
876 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
878 $pid = CRM_Core_DAO
::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
880 $this->fail("$processorType processortype not found.");
882 $this->openCiviPage('admin/paymentProcessor', 'action=add&reset=1&pp=' . $pid, 'name');
883 $this->type('name', $processorName);
884 $this->select('financial_account_id', "label={$financialAccount}");
885 foreach ($processorSettings as $f => $v) {
890 $this->clickLink('_qf_PaymentProcessor_next-bottom');
892 $this->waitForTextPresent($processorName);
894 // Get payment processor id
895 $paymentProcessorLink = $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href");
896 return $this->urlArg('id', $paymentProcessorLink);
899 public function webtestAddCreditCardDetails() {
900 $this->waitForElementPresent('credit_card_type');
901 $this->select('credit_card_type', 'label=Visa');
902 $this->type('credit_card_number', '4807731747657838');
903 $this->type('cvv2', '123');
904 $this->select('credit_card_exp_date[M]', 'label=Feb');
905 $this->select('credit_card_exp_date[Y]', 'label=2019');
909 * @param null $firstName
910 * @param null $middleName
911 * @param null $lastName
915 public function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
921 $middleName = 'Apple';
925 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
928 $this->type('billing_first_name', $firstName);
929 $this->type('billing_middle_name', $middleName);
930 $this->type('billing_last_name', $lastName);
932 $this->type('billing_street_address-5', '234 Lincoln Ave');
933 $this->type('billing_city-5', 'San Bernadino');
934 $this->select2('billing_country_id-5', 'UNITED STATES');
935 $this->select2('billing_state_province_id-5', 'California');
936 $this->type('billing_postal_code-5', '93245');
938 return array($firstName, $middleName, $lastName);
942 * @param $fieldLocator
943 * @param null $filePath
945 * @return null|string
947 public function webtestAttachFile($fieldLocator, $filePath = NULL) {
949 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
950 $fp = @fopen
($filePath, 'w');
951 fwrite($fp, 'Test file created by selenium test.');
955 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
957 $this->attachFile($fieldLocator, "file://{$filePath}");
965 * @param null $filePath
967 * @return null|string
969 public function webtestCreateCSV($headers, $rows, $filePath = NULL) {
971 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
974 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
976 foreach ($rows as $row) {
978 foreach ($headers as $field => $header) {
979 $temp[$field] = isset($row[$field]) ?
'"' . $row[$field] . '"' : '""';
981 $data .= implode(', ', $temp) . "\r\n";
984 $fp = @fopen
($filePath, 'w');
988 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
994 * Create new relationship type w/ user specified params or default.
996 * @param array $params
997 * array of required params.
1000 * array of saved params values.
1002 public function webtestAddRelationshipType($params = array()) {
1003 $this->openCiviPage("admin/reltype", "reset=1&action=add");
1005 //build the params if not passed.
1006 if (!is_array($params) ||
empty($params)) {
1008 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
1009 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
1010 'contact_types_a' => 'Individual',
1011 'contact_types_b' => 'Individual',
1012 'description' => 'Test Relationship Type Description',
1015 //make sure we have minimum required params.
1016 if (!isset($params['label_a_b']) ||
empty($params['label_a_b'])) {
1017 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
1020 //start the form fill.
1021 $this->type('label_a_b', $params['label_a_b']);
1022 $this->type('label_b_a', $params['label_b_a']);
1023 $this->select('contact_types_a', "value={$params['contact_type_a']}");
1024 $this->select('contact_types_b', "value={$params['contact_type_b']}");
1025 $this->type('description', $params['description']);
1028 $this->click('_qf_RelationshipType_next-bottom');
1029 $this->waitForPageToLoad($this->getTimeoutMsec());
1032 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
1033 "Status message didn't show up after saving!"
1036 $this->openCiviPage("admin/reltype", "reset=1");
1038 //validate data on selector.
1040 if (isset($data['description'])) {
1041 unset($data['description']);
1043 $this->assertStringsPresent($data);
1049 * Create new online contribution page w/ user specified params or defaults.
1050 * FIXME: this function take an absurd number of params - very unwieldy :(
1054 * @param null $pageTitle
1055 * @param array $processor
1056 * @param bool $amountSection
1057 * @param bool $payLater
1058 * @param bool $onBehalf
1059 * @param bool $pledges
1060 * @param bool $recurring
1061 * @param bool $membershipTypes
1062 * @param int $memPriceSetId
1063 * @param bool $friend
1064 * @param int $profilePreId
1065 * @param int $profilePostId
1066 * @param bool $premiums
1067 * @param bool $widget
1069 * @param bool $isAddPaymentProcessor
1070 * @param bool $isPcpApprovalNeeded
1071 * @param bool $isSeparatePayment
1072 * @param bool $honoreeSection
1073 * @param bool $allowOtherAmount
1074 * @param bool $isConfirmEnabled
1075 * @param string $financialType
1076 * @param bool $fixedAmount
1077 * @param bool $membershipsRequired
1080 * of newly created online contribution page.
1082 public function webtestAddContributionPage(
1086 $processor = array('Test Processor' => 'Dummy'),
1087 $amountSection = TRUE,
1092 $membershipTypes = TRUE,
1093 $memPriceSetId = NULL,
1100 $isAddPaymentProcessor = TRUE,
1101 $isPcpApprovalNeeded = FALSE,
1102 $isSeparatePayment = FALSE,
1103 $honoreeSection = TRUE,
1104 $allowOtherAmount = TRUE,
1105 $isConfirmEnabled = TRUE,
1106 $financialType = 'Donation',
1107 $fixedAmount = TRUE,
1108 $membershipsRequired = TRUE
1111 $hash = substr(sha1(rand()), 0, 7);
1114 $pageTitle = 'Donate Online ' . $hash;
1118 $rand = 2 * rand(2, 50);
1121 // Create a new payment processor if requested
1122 if ($isAddPaymentProcessor) {
1123 while (list($processorName, $processorType) = each($processor)) {
1124 $this->webtestAddPaymentProcessor($processorName, $processorType);
1128 // go to the New Contribution Page page
1129 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
1131 // fill in step 1 (Title and Settings)
1132 $this->type('title', $pageTitle);
1134 //to select financial type
1135 $this->select('financial_type_id', "label={$financialType}");
1138 $this->click('is_organization');
1139 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
1140 $this->type('for_organization', "On behalf $hash");
1142 if ($onBehalf == 'required') {
1143 $this->click('CIVICRM_QFID_2_4');
1145 elseif ($onBehalf == 'optional') {
1146 $this->click('CIVICRM_QFID_1_2');
1150 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1151 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1153 $this->type('goal_amount', 10 * $rand);
1155 // FIXME: handle Start/End Date/Time
1156 if ($honoreeSection) {
1157 $this->click('honor_block_is_active');
1158 $this->type('honor_block_title', "Honoree Section Title $hash");
1159 $this->type('honor_block_text', "Honoree Introductory Message $hash");
1160 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1161 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1162 $this->waitForElementPresent("//*[@class='select2-result-label']");
1163 $this->clickAt("//*[@class='select2-results']/li[1]");
1166 // is confirm enabled? it starts out enabled, so uncheck it if false
1167 if (!$isConfirmEnabled) {
1168 $this->click("id=is_confirm_enabled");
1172 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1174 // Get contribution page id
1175 $pageId = $this->urlArg('id');
1177 // fill in step 2 (Processor, Pay Later, Amounts)
1178 if (!empty($processor)) {
1180 while (list($processorName) = each($processor)) {
1181 // select newly created processor
1182 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1183 $this->assertTrue($this->isTextPresent($processorName));
1184 $this->check($xpath);
1188 if ($amountSection && !$memPriceSetId) {
1190 $this->click('is_pay_later');
1191 $this->type('pay_later_text', "Pay later label $hash");
1192 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1196 $this->click('is_pledge_active');
1197 $this->click('pledge_frequency_unit[week]');
1198 $this->click('is_pledge_interval');
1199 $this->type('initial_reminder_day', 3);
1200 $this->type('max_reminders', 2);
1201 $this->type('additional_reminder_day', 1);
1203 elseif ($recurring) {
1204 $this->click('is_recur');
1205 $this->click("is_recur_interval");
1206 $this->click("is_recur_installments");
1208 if ($allowOtherAmount) {
1210 $this->click('is_allow_other_amount');
1212 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1213 //$this->type('min_amount', $rand / 2);
1214 //$this->type('max_amount', $rand * 10);
1216 if ($fixedAmount ||
!$allowOtherAmount) {
1217 $this->type('label_1', "Label $hash");
1218 $this->type('value_1', "$rand");
1220 $this->click('CIVICRM_QFID_1_4');
1223 $this->click('amount_block_is_active');
1226 $this->click('_qf_Amount_next');
1227 $this->waitForElementPresent('_qf_Amount_next-bottom');
1228 $this->waitForPageToLoad($this->getTimeoutMsec());
1229 $text = "'Amount' information has been saved.";
1230 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1232 if ($memPriceSetId ||
(($membershipTypes === TRUE) ||
(is_array($membershipTypes) && !empty($membershipTypes)))) {
1233 // go to step 3 (memberships)
1234 $this->click('link=Memberships');
1235 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1237 // fill in step 3 (Memberships)
1238 $this->click('member_is_active');
1239 $this->waitForElementPresent('displayFee');
1240 $this->type('new_title', "Title - New Membership $hash");
1241 $this->type('renewal_title', "Title - Renewals $hash");
1243 if ($memPriceSetId) {
1244 $this->click('member_price_set_id');
1245 $this->select('member_price_set_id', "value={$memPriceSetId}");
1248 if ($membershipTypes === TRUE) {
1249 $membershipTypes = array(array('id' => 2, 'name' => 'Student', 'default' => 1));
1252 // FIXME: handle Introductory Message - New Memberships/Renewals
1253 foreach ($membershipTypes as $mType) {
1254 $this->click("membership_type_{$mType['id']}");
1255 if (array_key_exists('default', $mType)) {
1256 $this->click("xpath=//label[text() = '$mType[name]']/parent::td/parent::tr/td[2]/input");
1258 if (array_key_exists('auto_renew', $mType)) {
1259 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1262 if ($membershipsRequired) {
1263 $this->click('is_required');
1265 if ($isSeparatePayment) {
1266 $this->click('is_separate_payment');
1269 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1270 $text = "'MembershipBlock' information has been saved.";
1271 $this->isTextPresent($text);
1274 // go to step 4 (thank-you and receipting)
1275 $this->click('link=Receipt');
1276 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1279 $this->type('thankyou_title', "Thank-you Page Title $hash");
1280 // FIXME: handle Thank-you Message/Page Footer
1281 $this->type('receipt_from_name', "Receipt From Name $hash");
1282 $this->type('receipt_from_email', "$hash@example.org");
1283 $this->type('receipt_text', "Receipt Message $hash");
1284 $this->type('cc_receipt', "$hash@example.net");
1285 $this->type('bcc_receipt', "$hash@example.com");
1287 $this->click('_qf_ThankYou_next');
1288 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1289 $this->waitForPageToLoad($this->getTimeoutMsec());
1290 $text = "'ThankYou' information has been saved.";
1291 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1294 // fill in step 5 (Tell a Friend)
1295 $this->click('link=Tell a Friend');
1296 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1297 $this->click('tf_is_active');
1298 $this->type('tf_title', "TaF Title $hash");
1299 $this->type('intro', "TaF Introduction $hash");
1300 $this->type('suggested_message', "TaF Suggested Message $hash");
1301 $this->type('general_link', "TaF Info Page Link $hash");
1302 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1303 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1305 //$this->click('_qf_Contribute_next');
1306 $this->click('_qf_Contribute_next-bottom');
1307 $this->waitForPageToLoad($this->getTimeoutMsec());
1308 $text = "'Friend' information has been saved.";
1309 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1312 if ($profilePreId ||
$profilePostId) {
1313 // fill in step 6 (Include Profiles)
1314 $this->click('css=li#tab_custom a');
1315 $this->waitForElementPresent('_qf_Custom_next-bottom');
1317 if ($profilePreId) {
1318 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1321 if ($profilePostId) {
1322 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1325 $this->click('_qf_Custom_next-bottom');
1326 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1328 $this->waitForPageToLoad($this->getTimeoutMsec());
1329 $text = "'Custom' information has been saved.";
1330 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1334 // fill in step 7 (Premiums)
1335 $this->click('link=Premiums');
1336 $this->waitForElementPresent('_qf_Premium_next-bottom');
1337 $this->click('premiums_active');
1338 $this->type('premiums_intro_title', "Prem Title $hash");
1339 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1340 $this->type('premiums_contact_email', "$hash@example.info");
1341 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1342 $this->click('premiums_display_min_contribution');
1343 $this->type('premiums_nothankyou_label', 'No thank-you');
1344 $this->click('_qf_Premium_next');
1345 $this->waitForElementPresent('_qf_Premium_next-bottom');
1347 $this->waitForPageToLoad($this->getTimeoutMsec());
1348 $text = "'Premium' information has been saved.";
1349 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1350 $this->openCiviPage("admin/contribute/premium", "reset=1&action=update&id={$pageId}");
1351 $this->waitForAjaxContent();
1352 $this->waitForElementPresent('_qf_Premium_cancel-bottom');
1353 $this->click("xpath=//div[@class='messages status no-popup']/a[text()='add one']");
1354 $this->waitForElementPresent('_qf_AddProduct_cancel-bottom');
1355 $this->select('product_id', "value=1");
1356 $this->select('financial_type_id', "value=1");
1357 $this->click('_qf_AddProduct_next-bottom');
1358 $this->waitForElementPresent('_qf_Premium_cancel-bottom');
1359 $this->click('_qf_Premium_next-bottom');
1360 $this->waitForPageToLoad($this->getTimeoutMsec());
1364 // fill in step 8 (Widget Settings)
1365 $this->click('link=Widgets');
1366 $this->waitForElementPresent('_qf_Widget_next-bottom');
1367 $this->click('is_active');
1368 $this->type('url_logo', "URL to Logo Image $hash");
1369 $this->type('button_title', "Button Title $hash");
1370 // Type About text in ckEditor (fieldname, text to type, editor)
1371 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1373 $this->click('_qf_Widget_next');
1374 $this->waitForElementPresent('_qf_Widget_next-bottom');
1376 $this->waitForPageToLoad($this->getTimeoutMsec());
1377 $text = "'Widget' information has been saved.";
1378 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1382 // fill in step 9 (Enable Personal Campaign Pages)
1383 $this->click('link=Personal Campaigns');
1384 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1385 $this->click('pcp_active');
1386 if (!$isPcpApprovalNeeded) {
1387 $this->click('is_approval_needed');
1389 $this->type('notify_email', "$hash@example.name");
1390 $this->select('supporter_profile_id', 'value=2');
1391 $this->type('tellfriend_limit', 7);
1392 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1394 $this->click('_qf_Contribute_next-bottom');
1395 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1396 $this->waitForPageToLoad($this->getTimeoutMsec());
1397 $text = "'Pcp' information has been saved.";
1398 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1405 * Update default strict rule.
1407 * @param string $contactType
1408 * @param array $fields
1409 * Fields to be set for strict rule.
1410 * @param int $threshold
1411 * Rule's threshold value.
1413 public function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1414 // set default strict rule.
1416 if ($contactType == 'Organization') {
1419 elseif ($contactType == 'Household') {
1423 // Default dedupe fields for each Contact type.
1424 if (empty($fields)) {
1425 $fields = array('civicrm_email.email' => 10);
1426 if ($contactType == 'Organization') {
1428 'civicrm_contact.organization_name' => 10,
1429 'civicrm_email.email' => 10,
1432 elseif ($contactType == 'Household') {
1434 'civicrm_contact.household_name' => 10,
1435 'civicrm_email.email' => 10,
1440 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1443 foreach ($fields as $field => $weight) {
1444 $this->select("where_{$count}", "value={$field}");
1445 $this->type("length_{$count}", '');
1446 $this->type("weight_{$count}", $weight);
1451 $this->type('threshold', $threshold);
1453 $this->click('_qf_DedupeRules_next-bottom');
1454 $this->waitForPageToLoad($this->getTimeoutMsec());
1458 for ($i = $count; $i <= 4; $i++
) {
1459 $this->select("where_{$i}", 'label=- none -');
1460 $this->type("length_{$i}", '');
1461 $this->type("weight_{$i}", '');
1464 $this->type('threshold', $threshold);
1467 $this->click('_qf_DedupeRules_next-bottom');
1468 $this->waitForPageToLoad($this->getTimeoutMsec());
1472 * @param string $period_type
1473 * @param int $duration_interval
1474 * @param string $duration_unit
1475 * @param string $auto_renew
1476 * @param int $minimumFee
1477 * @param string $financialType
1481 public function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no', $minimumFee = 100, $financialType = 'Member Dues') {
1482 $membershipTitle = substr(sha1(rand()), 0, 7);
1483 $membershipOrg = $membershipTitle . ' memorg';
1484 $this->webtestAddOrganization($membershipOrg, TRUE);
1486 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1487 $memTypeParams = array(
1488 'membership_type' => $title,
1489 'member_of_contact' => $membershipOrg,
1490 'financial_type' => $financialType,
1491 'period_type' => $period_type,
1494 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1496 $this->type('name', $memTypeParams['membership_type']);
1498 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1499 // select the radio first since the element id changes after membership org search results are loaded
1500 switch ($auto_renew) {
1502 $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')]");
1506 $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')]");
1510 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1511 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')]")) {
1512 $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')]");
1517 $this->select2('member_of_contact_id', $membershipTitle);
1519 $this->type('minimum_fee', $minimumFee);
1520 $this->select('financial_type_id', "label={$memTypeParams['financial_type']}");
1522 $this->type('duration_interval', $duration_interval);
1523 $this->select('duration_unit', "label={$duration_unit}");
1525 $this->select('period_type', "value={$period_type}");
1527 $this->click('_qf_MembershipType_upload-bottom');
1528 $this->waitForElementPresent('link=Add Membership Type');
1529 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1531 return $memTypeParams;
1535 * @param null $groupName
1536 * @param null $parentGroupName
1538 * @return null|string
1540 public function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1541 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1545 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1547 $this->type('title', $groupName);
1550 $this->type('description', 'Adding new group.');
1552 // check Access Control
1553 $this->click('group_type[1]');
1555 // check Mailing List
1556 $this->click('group_type[2]');
1558 // select Visibility as Public Pages
1559 $this->select('visibility', 'value=Public Pages');
1561 // select parent group
1562 if ($parentGroupName) {
1563 $this->select('parents', "*$parentGroupName");
1567 $this->clickLink('_qf_Edit_upload-bottom');
1569 // Is status message correct?
1570 $this->waitForText('crm-notification-container', "$groupName");
1575 * @param string $activityType
1579 public function WebtestAddActivity($activityType = "Meeting") {
1580 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1581 // We're using Quick Add block on the main page for this.
1582 $firstName1 = substr(sha1(rand()), 0, 7);
1583 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1584 $firstName2 = substr(sha1(rand()), 0, 7);
1585 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1587 $this->click("css=li#tab_activity a");
1589 // waiting for the activity dropdown to show up
1590 $this->waitForElementPresent("other_activity");
1592 // Select the activity type from the activity dropdown
1593 $this->select("other_activity", "label=Meeting");
1595 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1596 $this->waitForElementPresent("s2id_target_contact_id");
1598 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__
);
1600 // Typing contact's name into the field (using typeKeys(), not type()!)...
1601 $this->select2("assignee_contact_id", $firstName1, TRUE);
1603 // ...and verifying if the page contains properly formatted display name for chosen contact.
1604 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__
);
1606 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1607 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1608 // For simple input fields we can use field id as selector
1609 $this->type("subject", $subject);
1610 $this->type("location", "Some location needs to be put in this field.");
1612 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1614 // Setting duration.
1615 $this->type("duration", "30");
1617 // Putting in details.
1618 $this->type("details", "Really brief details information.");
1620 // Making sure that status is set to Scheduled (using value, not label).
1621 $this->select("status_id", "value=1");
1623 // Setting priority.
1624 $this->select("priority_id", "value=1");
1626 // Scheduling follow-up.
1627 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1628 $this->select("followup_activity_type_id", "value=1");
1629 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1630 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1633 $this->click("_qf_Activity_upload-bottom");
1634 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1636 // Is status message correct?
1637 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1639 $this->waitForElementPresent("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1641 // click through to the Activity view screen
1642 $this->clickLinkSuppressPopup("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']", '_qf_Activity_cancel-bottom');
1644 // parse URL to grab the activity id
1645 // pass id back to any other tests that call this class
1646 return $this->urlArg('id');
1652 public static function checkDoLocalDBTest() {
1653 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1654 CIVICRM_WEBTEST_LOCAL_DB
1656 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1663 * Generic function to compare expected values after an api call to retrieved.
1666 * @param string $daoName
1667 * DAO Name of object we're evaluating.
1670 * @param array $match
1671 * Associative array of field name => expected value. Empty if asserting
1672 * that a DELETE occurred
1673 * @param bool $delete
1674 * are we checking that a DELETE action occurred?
1676 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
1677 if (self
::checkDoLocalDBTest()) {
1678 CiviDBAssert
::assertDBState($this, $daoName, $id, $match, $delete);
1683 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1684 * @param string $daoName
1685 * @param string $searchValue
1686 * @param string $returnColumn
1687 * @param string $searchColumn
1688 * @param string $message
1690 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1691 if (self
::checkDoLocalDBTest()) {
1692 CiviDBAssert
::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1697 * Request a record from the DB by searchColumn+searchValue. Success if returnColumn value is NULL.
1698 * @param string $daoName
1699 * @param string $searchValue
1700 * @param string $returnColumn
1701 * @param string $searchColumn
1702 * @param string $message
1704 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1705 if (self
::checkDoLocalDBTest()) {
1706 CiviDBAssert
::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1711 * Request a record from the DB by id. Success if row not found.
1712 * @param string $daoName
1714 * @param string $message
1716 public function assertDBRowNotExist($daoName, $id, $message) {
1717 if (self
::checkDoLocalDBTest()) {
1718 CiviDBAssert
::assertDBRowNotExist($this, $daoName, $id, $message);
1723 * Compare all values in a single retrieved DB record to an array of expected values.
1724 * @param string $daoName
1725 * @param array $searchParams
1726 * @param $expectedValues
1728 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1729 if (self
::checkDoLocalDBTest()) {
1730 CiviDBAssert
::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1737 * @param string $message
1739 public function assertType($expected, $actual, $message = '') {
1740 $this->assertInternalType($expected, $actual, $message);
1744 * Add new Financial Account.
1745 * @param $financialAccountTitle
1746 * @param bool $financialAccountDescription
1747 * @param bool $accountingCode
1748 * @param bool $firstName
1749 * @param bool $financialAccountType
1750 * @param bool $taxDeductible
1751 * @param bool $isActive
1752 * @param bool $isTax
1753 * @param bool $taxRate
1754 * @param bool $isDefault
1756 public function _testAddFinancialAccount(
1757 $financialAccountTitle,
1758 $financialAccountDescription = FALSE,
1759 $accountingCode = FALSE,
1761 $financialAccountType = FALSE,
1762 $taxDeductible = FALSE,
1769 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1771 $this->click("link=Add Financial Account");
1772 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1774 // Financial Account Name
1775 $this->type('name', $financialAccountTitle);
1777 // Financial Description
1778 if ($financialAccountDescription) {
1779 $this->type('description', $financialAccountDescription);
1783 if ($accountingCode) {
1784 $this->type('accounting_code', $accountingCode);
1787 // Autofill Organization
1789 $this->webtestOrganisationAutocomplete($firstName);
1792 // Financial Account Type
1793 if ($financialAccountType) {
1794 $this->select('financial_account_type_id', "label={$financialAccountType}");
1797 // Is Tax Deductible
1798 if ($taxDeductible) {
1799 $this->check('is_deductible');
1802 $this->uncheck('is_deductible');
1806 $this->check('is_active');
1809 $this->uncheck('is_active');
1813 $this->check('is_tax');
1816 $this->uncheck('is_tax');
1820 $this->type('tax_rate', $taxRate);
1825 $this->check('is_default');
1828 $this->uncheck('is_default');
1830 $this->click('_qf_FinancialAccount_next-botttom');
1834 * Edit Financial Account.
1835 * @param $editfinancialAccount
1836 * @param bool $financialAccountTitle
1837 * @param bool $financialAccountDescription
1838 * @param bool $accountingCode
1839 * @param bool $firstName
1840 * @param bool $financialAccountType
1841 * @param bool $taxDeductible
1842 * @param bool $isActive
1843 * @param bool $isTax
1844 * @param bool $taxRate
1845 * @param bool $isDefault
1847 public function _testEditFinancialAccount(
1848 $editfinancialAccount,
1849 $financialAccountTitle = FALSE,
1850 $financialAccountDescription = FALSE,
1851 $accountingCode = FALSE,
1853 $financialAccountType = FALSE,
1854 $taxDeductible = FALSE,
1861 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1864 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']");
1865 $this->clickLink("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1867 // Change Financial Account Name
1868 if ($financialAccountTitle) {
1869 $this->type('name', $financialAccountTitle);
1872 // Financial Description
1873 if ($financialAccountDescription) {
1874 $this->type('description', $financialAccountDescription);
1878 if ($accountingCode) {
1879 $this->type('accounting_code', $accountingCode);
1882 // Autofill Edit Organization
1884 $this->webtestOrganisationAutocomplete($firstName);
1887 // Financial Account Type
1888 if ($financialAccountType) {
1889 $this->select('financial_account_type_id', "label={$financialAccountType}");
1892 // Is Tax Deductible
1893 if ($taxDeductible) {
1894 $this->check('is_deductible');
1897 $this->uncheck('is_deductible');
1902 $this->check('is_tax');
1905 $this->uncheck('is_tax');
1910 $this->type('tax_rate', $taxRate);
1915 $this->check('is_default');
1918 $this->uncheck('is_default');
1923 $this->check('is_active');
1926 $this->uncheck('is_active');
1928 $this->click('_qf_FinancialAccount_next-botttom');
1929 $this->waitForElementPresent('link=Add Financial Account');
1933 * Delete Financial Account.
1934 * @param $financialAccountTitle
1936 public function _testDeleteFinancialAccount($financialAccountTitle) {
1937 $this->click("xpath=//table/tbody//tr/td[1]/div[text()='{$financialAccountTitle}']/../../td[9]/span/a[text()='Delete']");
1938 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1939 $this->click('_qf_FinancialAccount_next-botttom');
1940 $this->waitForElementPresent('link=Add Financial Account');
1941 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1945 * Verify data after ADD and EDIT.
1946 * @param $verifyData
1948 public function _assertFinancialAccount($verifyData) {
1949 foreach ($verifyData as $key => $expectedValue) {
1950 $actualValue = $this->getValue($key);
1951 if ($key == 'parent_financial_account') {
1952 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1955 $this->assertEquals($expectedValue, $actualValue);
1961 * @param $verifySelectFieldData
1963 public function _assertSelectVerify($verifySelectFieldData) {
1964 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1965 $actualvalue = $this->getSelectedLabel($key);
1966 $this->assertEquals($expectedvalue, $actualvalue);
1971 * @param $financialType
1972 * @param string $option
1974 public function addeditFinancialType($financialType, $option = 'new') {
1975 $this->openCiviPage("admin/financial/financialType", "reset=1");
1977 if ($option == 'Delete') {
1978 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]");
1979 $this->waitForElementPresent("css=span.btn-slide-active");
1980 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]/ul/li[2]/a");
1981 $this->waitForElementPresent("_qf_FinancialType_next");
1982 $this->click("_qf_FinancialType_next");
1983 $this->waitForElementPresent("newFinancialType");
1984 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1987 if ($option == 'new') {
1988 $this->click("link=Add Financial Type");
1991 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[oldname]']/../../td[7]/span/a[text()='Edit']");
1993 $this->waitForElementPresent("name");
1994 $this->type('name', $financialType['name']);
1995 if ($option == 'new') {
1996 $this->type('description', $financialType['name'] . ' description');
1999 if ($financialType['is_reserved']) {
2000 $this->check('is_reserved');
2003 $this->uncheck('is_reserved');
2006 if ($financialType['is_deductible']) {
2007 $this->check('is_deductible');
2010 $this->uncheck('is_deductible');
2013 $this->click('_qf_FinancialType_next');
2014 if ($option == 'new') {
2015 $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.";
2018 $text = "The financial type \"{$financialType['name']}\" has been updated.";
2020 $this->checkCRMAlert($text);
2024 * Give the specified permissions.
2025 * Note: this function logs in as 'admin' (logging out if necessary)
2026 * @param $permission
2028 public function changePermissions($permission) {
2029 $this->webtestLogin('admin');
2030 $this->open("{$this->sboxPath}admin/people/permissions");
2031 $this->waitForElementPresent('edit-submit');
2032 foreach ((array) $permission as $perm) {
2033 $this->check($perm);
2035 $this->click('edit-submit');
2036 $this->waitForPageToLoad($this->getTimeoutMsec());
2037 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
2041 * @param $profileTitle
2042 * @param $profileFields
2044 public function addProfile($profileTitle, $profileFields) {
2045 $this->openCiviPage('admin/uf/group', "reset=1");
2047 $this->clickLink('link=Add Profile', '_qf_Group_cancel-bottom');
2048 $this->type('title', $profileTitle);
2049 $this->clickLink('_qf_Group_next-bottom');
2051 $this->waitForText('crm-notification-container', "Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now.");
2053 foreach ($profileFields as $field) {
2054 $this->waitForElementPresent('field_name_0');
2055 $this->click("id=field_name_0");
2056 $this->select("id=field_name_0", "label=" . $field['type']);
2057 $this->waitForElementPresent('field_name_1');
2058 $this->click("id=field_name_1");
2059 $this->select("id=field_name_1", "label=" . $field['name']);
2060 $this->waitForElementPresent('label');
2061 $this->type("id=label", $field['label']);
2062 $this->click("id=_qf_Field_next_new-top");
2063 $this->waitForElementPresent("xpath=//select[@id='field_name_1'][@style='display: none;']");
2064 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
2069 * @param string $name
2074 * @param $financialType
2076 public function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
2077 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
2078 $this->type("name", $name);
2079 $this->type("sku", $sku);
2080 $this->click("CIVICRM_QFID_noImage_16");
2081 $this->type("min_contribution", $amount);
2082 $this->type("price", $price);
2083 $this->type("cost", $cost);
2084 if ($financialType) {
2085 $this->select("financial_type_id", "label={$financialType}");
2087 $this->click("_qf_ManagePremiums_upload-bottom");
2088 $this->waitForPageToLoad($this->getTimeoutMsec());
2093 * @param $financialAccount
2095 public function addPaymentInstrument($label, $financialAccount) {
2096 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
2097 $this->type("label", $label);
2098 $this->type("value", "value" . $label);
2099 $this->select("financial_account_id", "value=$financialAccount");
2100 $this->click("_qf_Options_next-bottom");
2101 $this->waitForPageToLoad($this->getTimeoutMsec());
2105 * Ensure we have a default mailbox set up for CiviMail.
2107 public function setupDefaultMailbox() {
2108 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
2109 // Check if it hasn't already been set up
2110 if (!$this->getSelectedValue('protocol')) {
2111 $this->type('name', 'Test Domain');
2112 $this->select('protocol', "IMAP");
2113 $this->type('server', 'localhost');
2114 $this->type('domain', 'example.com');
2115 $this->clickLink('_qf_MailSettings_next-top');
2120 * Determine the default time-out in milliseconds.
2122 * @return string, timeout expressed in milliseconds
2124 public function getTimeoutMsec() {
2125 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
2126 $timeout = ($this->settings
&& @$this->settings
->timeout
) ?
($this->settings
->timeout
* 1000) : 30000;
2127 return (string) $timeout; // don't know why, but all our old code used a string
2132 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
2135 * @param array $customSets
2136 * Custom sets i.e entity wise sets want to be created and checked.
2137 * e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
2138 * 'triggerElement' => $triggerElement))
2139 * array $triggerElement: the element which is responsible for custom group to load
2141 * which uses the entity info as its selection value
2142 * @param array $pageUrl
2143 * The url which on which the ajax custom group load takes place.
2144 * @param string $beforeTriggering
2147 public function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
2148 // FIXME: Testing a theory that these failures have something to do with permissions
2149 $this->webtestLogin('admin');
2151 //add the custom set
2152 $return = $this->addCustomGroupField($customSets);
2154 // FIXME: Hack to ensure caches are properly cleared
2156 $userName = $this->loggedInAs
;
2157 $this->webtestLogout();
2158 $this->webtestLogin($userName);
2161 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
2163 // FIXME: Try to find out what the heck is going on with these tests
2164 $this->waitForAjaxContent();
2165 $this->checkForErrorsOnPage();
2167 foreach ($return as $values) {
2168 foreach ($values as $entityType => $customData) {
2169 //initiate necessary variables
2170 list($entity, $entityData) = explode('_', $entityType);
2171 $elementType = CRM_Utils_Array
::value('type', $customData['triggerElement'], 'select');
2172 $elementName = CRM_Utils_Array
::value('name', $customData['triggerElement']);
2173 if (is_callable($beforeTriggering)) {
2174 call_user_func($beforeTriggering);
2176 if ($elementType == 'select') {
2177 //reset the select box, so triggering of ajax only happens
2178 //WRT input of value in this function
2179 $this->select($elementName, "index=0");
2181 if (!empty($entityData)) {
2182 if ($elementType == 'select') {
2183 $this->select($elementName, "label=regexp:{$entityData}");
2185 elseif ($elementType == 'checkbox') {
2186 $val = explode(',', $entityData);
2187 foreach ($val as $v) {
2188 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2189 $this->check($checkId);
2192 elseif ($elementType == 'select2') {
2193 $this->select2($elementName, $entityData);
2196 // FIXME: Try to find out what the heck is going on with these tests
2197 $this->waitForAjaxContent();
2198 $this->checkForErrorsOnPage();
2200 //checking for proper custom data which is loading through ajax
2201 $this->waitForElementPresent("css=.custom-group-{$customData['cgtitle']}");
2202 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2203 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2209 * @param $customSets
2213 public function addCustomGroupField($customSets) {
2215 foreach ($customSets as $customSet) {
2216 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2218 //fill custom group title
2219 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2220 $this->click("title");
2221 $this->type("title", $customGroupTitle);
2223 //custom group extends
2224 $this->click("extends_0");
2225 $this->select("extends_0", "value={$customSet['entity']}");
2226 if (!empty($customSet['subEntity'])) {
2227 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2231 $this->uncheck('collapse_display');
2234 $this->click('_qf_Group_next-bottom');
2236 //Is custom group created?
2237 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2239 $gid = $this->urlArg('gid');
2240 $this->waitForTextPresent("{$customGroupTitle} - New Field");
2242 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2243 $this->waitForElementPresent('label');
2244 $this->type('label', $fieldLabel);
2245 $this->click('_qf_Field_done-bottom');
2247 $this->waitForText('crm-notification-container', $fieldLabel);
2248 $this->waitForAjaxContent();
2250 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2252 "{$customSet['entity']}_{$customSet['subEntity']}" => array(
2253 'cgtitle' => $customGroupTitle,
2255 'triggerElement' => $customSet['triggerElement'],
2259 // Go home for a sec to give time for caches to clear
2260 $this->openCiviPage('');
2266 * Type and select first occurrence of autocomplete.
2269 * @param string $labels
2270 * @param bool $multiple
2271 * @param bool $xpath
2273 public function select2($fieldName, $labels, $multiple = FALSE, $xpath = FALSE) {
2274 // In the case of chainSelect, wait for options to load
2275 $this->waitForElementNotPresent('css=select.loading');
2277 foreach ((array) $labels as $label) {
2278 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2279 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2280 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2281 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2282 $this->waitForElementPresent("//*[@class='select2-result-label']");
2283 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2288 $this->clickAt($fieldName);
2291 $this->clickAt("//*[@id='$fieldName']/../div/a");
2293 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2294 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2295 $this->type("//*[@id='select2-drop']/div/input", $labels);
2296 $this->typeKeys("//*[@id='select2-drop']/div/input", $labels);
2297 $this->waitForElementPresent("//*[@class='select2-result-label']");
2298 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2300 // Wait a sec for select2 to update the original element
2305 * Select multiple options.
2308 * @param $isDate if multiple date is to be selected from datepicker
2310 public function multiselect2($fieldid, $params, $isDate = FALSE) {
2311 // In the case of chainSelect, wait for options to load
2312 $this->waitForElementNotPresent('css=select.loading');
2313 foreach ($params as $value) {
2315 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2316 $this->webtestFillDate($fieldid, $value, TRUE);
2319 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2320 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2321 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2322 $this->assertElementContainsText("xpath=//*[@id='$fieldid']/preceding-sibling::div[1]/", $value);
2325 // Wait a sec for select2 to update the original element
2330 * Check for unobtrusive status message as set by CRM.status
2333 public function checkCRMStatus($text = NULL) {
2334 $this->waitForElementPresent("css=.crm-status-box-outer.status-success");
2336 $this->assertElementContainsText("css=.crm-status-box-outer.status-success", $text);
2341 * Check for obtrusive status message as set by CRM.alert
2343 * @param string $type
2345 public function checkCRMAlert($text, $type = 'success') {
2346 $this->waitForElementPresent("css=div.ui-notify-message.$type");
2347 $this->waitForText("css=div.ui-notify-message.$type", $text);
2348 // We got the message, now let's close it so the webtest doesn't get confused by lots of open alerts
2349 $this->click('css=.ui-notify-cross');
2353 * Enable or disable Pop-ups via Display Preferences
2354 * @param bool $enabled
2356 public function enableDisablePopups($enabled = TRUE) {
2357 $this->openCiviPage('admin/setting/preferences/display', 'reset=1');
2358 $isChecked = $this->isChecked('ajaxPopupsEnabled');
2359 if (($isChecked && !$enabled) ||
(!$isChecked && $enabled)) {
2360 $this->click('ajaxPopupsEnabled');
2363 $this->assertChecked('ajaxPopupsEnabled');
2366 $this->assertNotChecked('ajaxPopupsEnabled');
2368 $this->clickLink("_qf_Display_next-bottom");
2372 * Attempt to get information about what went wrong if we encounter an error when loading a page.
2374 public function checkForErrorsOnPage() {
2375 foreach (array('Access denied', 'Page not found') as $err) {
2376 if ($this->isElementPresent("xpath=//h1[contains(., '$err')]")) {
2377 $this->fail("'$err' encountered at " . $this->getLocation() . "\nwhile logged in as '{$this->loggedInAs}'");
2380 if ($this->isElementPresent("xpath=//span[text()='Sorry but we are not able to provide this at the moment.']")) {
2381 $msg = '"Fatal Error" encountered at ' . $this->getLocation();
2382 if ($this->isElementPresent('css=div.crm-section.crm-error-message')) {
2383 $msg .= "\nError Message: " . $this->getText('css=div.crm-section.crm-error-message');
2391 * Contact record (per APIv3).
2393 public function webtestGetLoggedInContact() {
2394 $result = $this->rest_civicrm_api('Contact', 'get', array(
2395 'id' => 'user_contact_id',
2397 $this->assertAPISuccess($result, 'Load logged-in contact');
2398 return CRM_Utils_Array
::first($result['values']);
2401 public function assertAPISuccess($apiResult, $prefix = '') {
2402 if (!empty($prefix)) {
2405 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
2407 if (!empty($apiResult['debug_information'])) {
2408 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
2410 if (!empty($apiResult['trace'])) {
2411 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
2413 $this->assertFalse(civicrm_error($apiResult), $prefix . $errorMessage);
2414 //$this->assertEquals(0, $apiResult['is_error']);
2422 public function webtestStandalonePledgeAdd() {
2423 $this->webtestLogin();
2425 $this->openCiviPage('pledge/add', 'reset=1&context=standalone', '_qf_Pledge_upload');
2427 // create new contact using dialog
2428 $contact = $this->createDialogContact();
2430 $this->type('amount', '100');
2431 $this->type('installments', '10');
2432 $this->select('frequency_unit', 'value=week');
2433 $this->type('frequency_day', '2');
2435 $this->webtestFillDate('acknowledge_date', 'now');
2437 $this->select('contribution_page_id', 'value=3');
2440 $this->click('PaymentReminders');
2441 $this->waitForElementPresent('additional_reminder_day');
2442 $this->type('initial_reminder_day', '4');
2443 $this->type('max_reminders', '2');
2444 $this->type('additional_reminder_day', '4');
2446 $this->click('_qf_Pledge_upload-bottom');
2448 $this->waitForText('crm-notification-container', "Pledge has been recorded and the payment schedule has been created.");
2450 // verify if Pledge is created
2451 $this->waitForElementPresent("xpath=//div[@class='view-content']//table//tbody/tr[1]/td[10]/span/a[text()='View']");
2453 //click through to the Pledge view screen
2454 $this->click("xpath=//div[@class='view-content']//table//tbody/tr[1]/td[10]/span/a[text()='View']");
2455 $this->waitForElementPresent('_qf_PledgeView_next-bottom');
2456 $pledgeDate = date('F jS, Y', strtotime('now'));
2458 $this->webtestVerifyTabularData(array(
2459 'Pledge By' => $contact['display_name'],
2460 'Total Pledge Amount' => '$ 100.00',
2461 'To be paid in' => '10 installments of $ 10.00 every 1 week(s)',
2462 'Payments are due on the' => '2 day of the period',
2463 'Pledge Made' => $pledgeDate,
2464 'Financial Type' => 'Donation',
2465 'Pledge Status' => 'Pending',
2466 'Initial Reminder Day' => '4 days prior to schedule date',
2467 'Maximum Reminders Send' => 2,
2468 'Send additional reminders' => '4 days after the last one sent',
2471 $this->clickLink('_qf_PledgeView_next-bottom', "xpath=//div[@class='view-content']//table[@class='selector row-highlight']//tbody/tr[1]/td[1]/a", FALSE);
2472 $this->waitForAjaxContent();
2473 $this->click("xpath=//div[@class='view-content']//table[@class='selector row-highlight']//tbody/tr[1]/td[1]/a");
2474 $this->waitForElementPresent("xpath=//div[@class='view-content']//table//tbody/tr[2]/td/div/table/tbody/tr[2]/td[8]/a[text()='Record Payment']");
2479 * Add a contact via profile
2481 public function webtestAddViaCreateProfile() {
2482 $this->webtestLogin();
2484 $this->openCiviPage('profile/create', 'reset=1&gid=1', '_qf_Edit_next');
2486 $firstName = 'Jo' . substr(sha1(rand()), 0, 4);
2487 $lastName = 'Ad' . substr(sha1(rand()), 0, 7);
2489 //contact details section
2490 //fill in first name
2491 $this->type("first_name", $firstName);
2494 $this->type("last_name", $lastName);
2497 $this->waitForElementPresent('street_address-1');
2498 $this->type("street_address-1", "902C El Camino Way SW");
2499 $this->waitForElementPresent('city-1');
2500 $this->type("city-1", "Dumfries");
2501 $this->type("postal_code-1", "1234");
2502 $this->assertSelected('country-1', "UNITED STATES");
2503 $this->select("state_province-1", "value=1019");
2506 $this->click("_qf_Edit_next");
2507 $this->waitForPageToLoad($this->getTimeoutMsec());
2509 $this->assertElementContainsText('css=.msg-text', "Your information has been saved.");