3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
67 parent
::__construct($name, $data, $dataName, $browser);
68 $this->loggedInAs
= NULL;
70 require_once 'CiviSeleniumSettings.php';
71 $this->settings
= new CiviSeleniumSettings();
72 if (property_exists($this->settings
, 'serverStartupTimeOut') && $this->settings
->serverStartupTimeOut
) {
73 global $CiviSeleniumTestCase_polled;
74 if (!$CiviSeleniumTestCase_polled) {
75 $CiviSeleniumTestCase_polled = TRUE;
76 CRM_Utils_Network
::waitForServiceStartup(
77 $this->drivers
[0]->getHost(),
78 $this->drivers
[0]->getPort(),
79 $this->settings
->serverStartupTimeOut
85 require_once 'CRM/Core/ClassLoader.php';
86 CRM_Core_ClassLoader
::singleton()->register();
88 // also initialize a connection to the db
89 // FIXME: not necessary for most tests, consider moving into functions that need this
90 $config = CRM_Core_Config
::singleton();
93 protected function setUp() {
94 $this->setBrowser($this->settings
->browser
);
95 // Make sure that below strings have path separator at the end
96 $this->setBrowserUrl($this->settings
->sandboxURL
);
97 $this->sboxPath
= $this->settings
->sandboxPATH
;
98 if (property_exists($this->settings
, 'rcHost') && $this->settings
->rcHost
) {
99 $this->setHost($this->settings
->rcHost
);
101 if (property_exists($this->settings
, 'rcPort') && $this->settings
->rcPort
) {
102 $this->setPort($this->settings
->rcPort
);
106 protected function prepareTestSession() {
107 $result = parent
::prepareTestSession();
109 // Set any cookies required by local installation
110 // Note: considered doing this in setUp(), but the Selenium session wasn't yet initialized.
111 if (property_exists($this->settings
, 'cookies')) {
112 // We don't really care about this page, but it seems we need
113 // to open a page before setting a cookie.
114 $this->open($this->sboxPath
);
115 $this->waitForPageToLoad($this->getTimeoutMsec());
116 $this->setCookies($this->settings
->cookies
);
122 * @param array $cookies each item is an array with keys:
124 * - value: string; note that RFC's don't define particular encoding scheme, so
125 * you must pick one yourself and pre-encode; does not allow values with
126 * commas, semicolons, or whitespace
127 * - path: string; default: '/'
128 * - max_age: int; default: 1 week (7*24*60*60)
130 protected function setCookies($cookies) {
131 foreach ($cookies as $cookie) {
132 if (!isset($cookie['path'])) {
133 $cookie['path'] = '/';
135 if (!isset($cookie['max_age'])) {
136 $cookie['max_age'] = 7*24*60*60;
138 $this->deleteCookie($cookie['name'], $cookie['path']);
139 $optionExprs = array();
140 foreach ($cookie as $key => $value) {
141 if ($key != 'name' && $key != 'value') {
142 $optionExprs[] = "$key=$value";
145 $this->createCookie("{$cookie['name']}={$cookie['value']}", implode(', ', $optionExprs));
149 protected function tearDown() {
153 * Authenticate as drupal user
154 * @param $user: (str) the key 'user' or 'admin', or a literal username
155 * @param $pass: (str) if $user is a literal username and not 'user' or 'admin', supply the password
157 function webtestLogin($user = 'user', $pass = NULL) {
158 // If already logged in as correct user, do nothing
159 if ($this->loggedInAs
=== $user) {
162 // If we are logged in as a different user, log out first
163 if ($this->loggedInAs
) {
164 $this->webtestLogout();
166 $this->open("{$this->sboxPath}user");
167 // Lookup username & password if not supplied
169 if ($pass === NULL) {
170 $pass = $user == 'admin' ?
$this->settings
->adminPassword
: $this->settings
->password
;
171 $username = $user == 'admin' ?
$this->settings
->adminUsername
: $this->settings
->username
;
173 // Make sure login form is available
174 $this->waitForElementPresent('edit-submit');
175 $this->type('edit-name', $username);
176 $this->type('edit-pass', $pass);
177 $this->click('edit-submit');
178 $this->waitForPageToLoad($this->getTimeoutMsec());
179 $this->loggedInAs
= $user;
182 function webtestLogout() {
183 if ($this->loggedInAs
) {
184 $this->open($this->sboxPath
. "user/logout");
185 $this->waitForPageToLoad($this->getTimeoutMsec());
187 $this->loggedInAs
= NULL;
191 * Open an internal path beginning with 'civicrm/'
193 * @param $url (str) omit the 'civicrm/' it will be added for you
194 * @param $args (str|array) optional url arguments
195 * @param $waitFor - page element to wait for - using this is recommended to ensure the document is fully loaded
197 * Although it doesn't seem to do much now, using this function is recommended for
198 * opening all civi pages, and using the $args param is also strongly encouraged
199 * This will make it much easier to run webtests in other CMSs in the future
201 function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
202 // Construct full url with args
203 // This could be extended in future to work with other CMS style urls
205 if (is_array($args)) {
207 foreach ($args as $key => $val) {
208 $url .= $sep . $key . '=' . $val;
216 $this->open("{$this->sboxPath}civicrm/$url");
217 $this->waitForPageToLoad($this->getTimeoutMsec());
219 $this->waitForElementPresent($waitFor);
224 * Click on a link or button
225 * Wait for the page to load
226 * Wait for an element to be present
228 function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
229 $this->click($element);
230 // conditional wait for page load e.g for ajax form save
231 if ($waitForPageLoad) {
232 $this->waitForPageToLoad($this->getTimeoutMsec());
235 $this->waitForElementPresent($waitFor);
240 * Call the API on the local server
241 * (kind of defeats the point of a webtest - see CRM-11889)
243 function webtest_civicrm_api($entity, $action, $params) {
244 if (!isset($params['version'])) {
245 $params['version'] = 3;
248 $result = civicrm_api($entity, $action, $params);
249 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
254 * Call the API on the remote server
255 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
258 function rest_civicrm_api($entity, $action, $params = array()) {
262 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
266 // Naughty sidestep of civi's security checks
267 'header' => "X-Requested-With: XMLHttpRequest",
270 $ctx = stream_context_create($request);
271 $result = file_get_contents($url, FALSE, $ctx);
272 return json_decode($result, TRUE);
276 * @param $option_group_name
280 function webtestGetFirstValueForOptionGroup($option_group_name) {
281 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
282 'option_group_name' => $option_group_name,
292 function webtestGetValidCountryID() {
294 if (is_null($_country_id)) {
295 $config_backend = $this->webtestGetConfig('countryLimit');
296 $_country_id = current($config_backend);
306 function webtestGetValidEntityID($entity) {
307 // michaelmcandrew: would like to use getvalue but there is a bug
308 // for e.g. group where option.limit not working at the moment CRM-9110
309 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
310 if (!empty($result['values'])) {
311 return current(array_keys($result['values']));
321 function webtestGetConfig($field) {
322 static $_config_backend;
323 if (is_null($_config_backend)) {
324 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
325 'current_domain' => 1,
327 'return' => 'config_backend'
329 $_config_backend = unserialize($result);
331 return $_config_backend[$field];
335 * Ensures the required CiviCRM components are enabled
337 function enableComponents($components) {
338 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
339 $enabledComponents = $this->getSelectOptions("enableComponents-t");
341 foreach ((array) $components as $comp) {
342 if (!in_array($comp, $enabledComponents)) {
343 $this->addSelection("enableComponents-f", "label=$comp");
344 $this->click("//option[@value='$comp']");
350 $this->click("_qf_Component_next-bottom");
351 $this->waitForPageToLoad($this->getTimeoutMsec());
352 $this->waitForText('crm-notification-container', "Saved");
357 * Add a contact with the given first and last names and either a given email
358 * (when specified), a random email (when true) or no email (when unspecified or null).
360 * @param string $fname contact’s first name
361 * @param string $lname contact’s last name
362 * @param mixed $email contact’s email (when string) or random email (when true) or no email (when null)
364 * @param null $contactSubtype
366 * @return mixed either a string with the (either generated or provided) email or null (if no email)
368 function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
369 $url = $this->sboxPath
. 'civicrm/contact/add?reset=1&ct=Individual';
370 if ($contactSubtype) {
371 $url = $url . "&cst={$contactSubtype}";
374 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
375 $this->type('first_name', $fname);
376 $this->type('last_name', $lname);
377 if ($email === TRUE) {
378 $email = substr(sha1(rand()), 0, 7) . '@example.org';
381 $this->type('email_1_email', $email);
383 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
384 $this->click('_qf_Contact_upload_view-bottom');
385 $this->waitForPageToLoad($this->getTimeoutMsec());
390 * @param string $householdName
393 * @return null|string
395 function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
397 $this->openCiviPage("contact/add", "reset=1&ct=Household");
398 $this->click('household_name');
399 $this->type('household_name', $householdName);
401 if ($email === TRUE) {
402 $email = substr(sha1(rand()), 0, 7) . '@example.org';
405 $this->type('email_1_email', $email);
408 $this->click('_qf_Contact_upload_view');
409 $this->waitForPageToLoad($this->getTimeoutMsec());
414 * @param string $organizationName
416 * @param null $contactSubtype
418 * @return null|string
420 function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
422 $url = $this->sboxPath
. 'civicrm/contact/add?reset=1&ct=Organization';
423 if ($contactSubtype) {
424 $url = $url . "&cst={$contactSubtype}";
427 $this->click('organization_name');
428 $this->type('organization_name', $organizationName);
430 if ($email === TRUE) {
431 $email = substr(sha1(rand()), 0, 7) . '@example.org';
434 $this->type('email_1_email', $email);
436 $this->click('_qf_Contact_upload_view');
437 $this->waitForPageToLoad($this->getTimeoutMsec());
443 function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
444 $this->select2($fieldName,$sortName);
445 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
450 function webtestOrganisationAutocomplete($sortName) {
451 $this->clickAt("//*[@id='contact_id']/../div/a");
452 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
453 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
454 $this->type("//*[@id='select2-drop']/div/input", $sortName);
455 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
456 $this->waitForElementPresent("//*[@class='select2-result-label']");
457 $this->clickAt("//*[@class='select2-results']/li[1]");
458 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
462 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
463 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
464 * 3. Examples of $strToTime arguments -
465 * webtestFillDate('start_date',"now")
466 * webtestFillDate('start_date',"10 September 2000")
467 * webtestFillDate('start_date',"+1 day")
468 * webtestFillDate('start_date',"+1 week")
469 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
470 * webtestFillDate('start_date',"next Thursday")
471 * webtestFillDate('start_date',"last Monday")
474 * @param $dateElement
475 * @param null $strToTimeArgs
477 function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
478 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
480 $year = date('Y', $timeStamp);
481 // -1 ensures month number is inline with calender widget's month
482 $mon = date('n', $timeStamp) - 1;
483 $day = date('j', $timeStamp);
485 $this->click("{$dateElement}_display");
486 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
487 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
488 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
489 $this->click("link=$day");
492 // 1. set both date and time.
494 * @param $dateElement
495 * @param null $strToTimeArgs
497 function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
498 $this->webtestFillDate($dateElement, $strToTimeArgs);
500 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
501 $hour = date('h', $timeStamp);
502 $min = date('i', $timeStamp);
503 $meri = date('A', $timeStamp);
505 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
509 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
511 * @param array $expected Array of key/value pairs (like Status/Registered) to be checked
512 * @param string $xpathPrefix Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath
513 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
514 * @param string $tableId Pass in the id attribute of a table to be verified if you want to only check a specific table
517 function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
520 $tableLocator = "[@id='$tableId']";
522 foreach ($expected as $label => $value) {
524 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
525 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
528 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
529 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
535 * Types text into a ckEditor rich text field in a form
537 * @param string $fieldName form field name (as assigned by PHP buildForm class)
538 * @param string $text text to type into the field
539 * @param string $editor which text editor (valid values are 'CKEditor', 'TinyMCE')
543 function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor', $compressed = FALSE) {
544 // make sure cursor focuses on the field
545 $this->fireEvent($fieldName, 'focus');
546 if ($editor == 'CKEditor') {
548 $this->click("{$fieldName}-plain");
550 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
551 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
553 elseif ($editor == 'TinyMCE') {
554 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
555 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
558 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
560 $this->selectFrame('relative=top');
564 * Types option label and name into a table of multiple choice options
565 * (for price set fields of type select, radio, or checkbox)
566 * TODO: extend for custom field multiple choice table input
568 * @param array $options form field name (as assigned by PHP buildForm class)
569 * @param array $validateStrings appends label and name strings to this array so they can be validated later
573 function addMultipleChoiceOptions($options, &$validateStrings) {
574 foreach ($options as $oIndex => $oValue) {
575 $validateStrings[] = $oValue['label'];
576 $validateStrings[] = $oValue['amount'];
577 if (!empty($oValue['membership_type_id'])) {
578 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
580 if (!empty($oValue['financial_type_id'])) {
581 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
583 $this->type("option_label_{$oIndex}", $oValue['label']);
584 $this->type("option_amount_{$oIndex}", $oValue['amount']);
585 $this->click('link=another choice');
591 function webtestNewDialogContact($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
592 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
593 // 4 - Individual profile
594 // 5 - Organization profile
595 // 6 - Household profile
596 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
597 $this->clickAt("xpath=//div[@id='$selectId']/a");
598 $this->click("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]");
600 $this->waitForElementPresent('_qf_Edit_next');
604 $this->type('first_name', $fname);
605 $this->type('last_name', $lname);
609 $this->type('organization_name', $fname);
613 $this->type('household_name', $fname);
617 $this->type('email-Primary', $email);
618 $this->click('_qf_Edit_next');
620 // Is new contact created?
622 $this->waitForText("xpath=//div[@id='$selectId']","$lname, $fname");
625 $this->waitForText("xpath=//div[@id='$selectId']","$fname");
630 * Generic function to check that strings are present in the page
632 * @strings array array of strings or a single string
637 function assertStringsPresent($strings) {
638 foreach ((array) $strings as $string) {
639 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
644 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
646 * @url string url to parse or retrieve current url if null
649 * @return array returns an associative array containing any of the various components
650 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
651 * http://php.net/manual/en/function.parse-url.php
653 function parseURL($url = NULL) {
655 $url = $this->getLocation();
658 $elements = parse_url($url);
659 if (!empty($elements['query'])) {
660 $elements['queryString'] = array();
661 parse_str($elements['query'], $elements['queryString']);
667 * Returns a single argument from the url query
669 function urlArg($arg, $url = NULL) {
670 $elements = $this->parseURL($url);
671 return isset($elements['queryString'][$arg]) ?
$elements['queryString'][$arg] : NULL;
675 * Define a payment processor for use by a webtest. Default is to create Dummy processor
676 * which is useful for testing online public forms (online contribution pages and event registration)
678 * @param string $processorName Name assigned to new processor
679 * @param string $processorType Name for processor type (e.g. PayPal, Dummy, etc.)
680 * @param array $processorSettings Array of fieldname => value for required settings for the processor
682 * @param string $financialAccount
683 * @throws PHPUnit_Framework_AssertionFailedError
687 function webtestAddPaymentProcessor($processorName, $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
688 if (!$processorName) {
689 $this->fail("webTestAddPaymentProcessor requires $processorName.");
691 if ($processorType == 'Dummy') {
692 $processorSettings = array(
693 'user_name' => 'dummy',
694 'url_site' => 'http://dummy.com',
695 'test_user_name' => 'dummytest',
696 'test_url_site' => 'http://dummytest.com',
699 elseif ($processorType == 'AuthNet') {
700 // FIXME: we 'll need to make a new separate account for testing
701 $processorSettings = array(
702 'test_user_name' => '5ULu56ex',
703 'test_password' => '7ARxW575w736eF5p',
706 elseif ($processorType == 'Google_Checkout') {
707 // FIXME: we 'll need to make a new separate account for testing
708 $processorSettings = array(
709 'test_user_name' => '559999327053114',
710 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
713 elseif ($processorType == 'PayPal') {
714 $processorSettings = array(
715 'test_user_name' => '559999327053114',
716 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
717 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
720 elseif ($processorType == 'PayPal_Standard') {
721 $processorSettings = array(
722 'test_user_name' => 'V18ki@9r5Bf.org',
725 elseif (empty($processorSettings)) {
726 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
728 $pid = CRM_Core_DAO
::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
730 $this->fail("$processorType processortype not found.");
732 $this->open($this->sboxPath
. 'civicrm/admin/paymentProcessor?action=add&reset=1&pp=' . $pid);
733 $this->waitForPageToLoad($this->getTimeoutMsec());
734 $this->type('name', $processorName);
735 $this->select('financial_account_id', "label={$financialAccount}");
737 foreach ($processorSettings AS $f => $v) {
740 $this->click('_qf_PaymentProcessor_next-bottom');
741 $this->waitForPageToLoad($this->getTimeoutMsec());
742 // Is new processor created?
743 $this->assertTrue($this->isTextPresent($processorName), 'Processor name not found in selector after adding payment processor (webTestAddPaymentProcessor).');
745 $paymentProcessorId = explode('&id=', $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href"));
746 $paymentProcessorId = explode('&', $paymentProcessorId[1]);
747 return $paymentProcessorId[0];
750 function webtestAddCreditCardDetails() {
751 $this->waitForElementPresent('credit_card_type');
752 $this->select('credit_card_type', 'label=Visa');
753 $this->type('credit_card_number', '4807731747657838');
754 $this->type('cvv2', '123');
755 $this->select('credit_card_exp_date[M]', 'label=Feb');
756 $this->select('credit_card_exp_date[Y]', 'label=2019');
760 * @param null $firstName
761 * @param null $middleName
762 * @param null $lastName
766 function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
772 $middleName = 'Apple';
776 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
779 $this->type('billing_first_name', $firstName);
780 $this->type('billing_middle_name', $middleName);
781 $this->type('billing_last_name', $lastName);
783 $this->type('billing_street_address-5', '234 Lincoln Ave');
784 $this->type('billing_city-5', 'San Bernadino');
785 $this->select('billing_country_id-5', 'value=1228');
786 $this->click('billing_state_province_id-5');
787 $this->select('billing_state_province_id-5', 'label=California');
788 $this->type('billing_postal_code-5', '93245');
790 return array($firstName, $middleName, $lastName);
794 * @param $fieldLocator
795 * @param null $filePath
797 * @return null|string
799 function webtestAttachFile($fieldLocator, $filePath = NULL) {
801 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
802 $fp = @fopen
($filePath, 'w');
803 fputs($fp, 'Test file created by selenium test.');
807 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
809 $this->attachFile($fieldLocator, "file://{$filePath}");
817 * @param null $filePath
819 * @return null|string
821 function webtestCreateCSV($headers, $rows, $filePath = NULL) {
823 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
826 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
828 foreach ($rows as $row) {
830 foreach ($headers as $field => $header) {
831 $temp[$field] = isset($row[$field]) ?
'"' . $row[$field] . '"' : '""';
833 $data .= implode(', ', $temp) . "\r\n";
836 $fp = @fopen
($filePath, 'w');
840 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
846 * Create new relationship type w/ user specified params or default.
848 * @param $params array of required params.
850 * @return an array of saved params values.
852 function webtestAddRelationshipType($params = array()) {
853 $this->openCiviPage("admin/reltype", "reset=1&action=add");
855 //build the params if not passed.
856 if (!is_array($params) ||
empty($params)) {
858 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
859 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
860 'contact_types_a' => 'Individual',
861 'contact_types_b' => 'Individual',
862 'description' => 'Test Relationship Type Description',
865 //make sure we have minimum required params.
866 if (!isset($params['label_a_b']) ||
empty($params['label_a_b'])) {
867 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
870 //start the form fill.
871 $this->type('label_a_b', $params['label_a_b']);
872 $this->type('label_b_a', $params['label_b_a']);
873 $this->select('contact_types_a', "value={$params['contact_type_a']}");
874 $this->select('contact_types_b', "value={$params['contact_type_b']}");
875 $this->type('description', $params['description']);
878 $this->click('_qf_RelationshipType_next-bottom');
879 $this->waitForPageToLoad($this->getTimeoutMsec());
882 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
883 "Status message didn't show up after saving!"
886 $this->openCiviPage("admin/reltype", "reset=1");
888 //validate data on selector.
890 if (isset($data['description'])) {
891 unset($data['description']);
893 $this->assertStringsPresent($data);
899 * Create new online contribution page w/ user specified params or defaults.
900 * FIXME: this function take an absurd number of params - very unwieldy :(
904 * @param null $pageTitle
905 * @param array $processor
906 * @param bool $amountSection
907 * @param bool $payLater
908 * @param bool $onBehalf
909 * @param bool $pledges
910 * @param bool $recurring
911 * @param bool $membershipTypes
912 * @param null $memPriceSetId
913 * @param bool $friend
914 * @param int $profilePreId
915 * @param int $profilePostId
916 * @param bool $premiums
917 * @param bool $widget
919 * @param bool $isAddPaymentProcessor
920 * @param bool $isPcpApprovalNeeded
921 * @param bool $isSeparatePayment
922 * @param bool $honoreeSection
923 * @param bool $allowOtherAmount
924 * @param bool $isConfirmEnabled
925 * @param string $financialType
926 * @param bool $fixedAmount
927 * @param bool $membershipsRequired
928 * @internal param \can $User define pageTitle, hash and rand values for later data verification
930 * @return null $pageId of newly created online contribution page.
932 function webtestAddContributionPage($hash = NULL,
935 $processor = array('Dummy Processor' => 'Dummy'),
936 $amountSection = TRUE,
941 $membershipTypes = TRUE,
942 $memPriceSetId = NULL,
949 $isAddPaymentProcessor = TRUE,
950 $isPcpApprovalNeeded = FALSE,
951 $isSeparatePayment = FALSE,
952 $honoreeSection = TRUE,
953 $allowOtherAmount = TRUE,
954 $isConfirmEnabled = TRUE,
955 $financialType = 'Donation',
957 $membershipsRequired = TRUE
960 $hash = substr(sha1(rand()), 0, 7);
963 $pageTitle = 'Donate Online ' . $hash;
967 $rand = 2 * rand(2, 50);
970 // Create a new payment processor if requested
971 if ($isAddPaymentProcessor) {
972 while (list($processorName, $processorType) = each($processor)) {
973 $this->webtestAddPaymentProcessor($processorName, $processorType);
977 // go to the New Contribution Page page
978 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
980 // fill in step 1 (Title and Settings)
981 $this->type('title', $pageTitle);
983 //to select financial type
984 $this->select('financial_type_id', "label={$financialType}");
987 $this->click('is_organization');
988 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
989 $this->type('for_organization', "On behalf $hash");
991 if ($onBehalf == 'required') {
992 $this->click('CIVICRM_QFID_2_4');
994 elseif ($onBehalf == 'optional') {
995 $this->click('CIVICRM_QFID_1_2');
999 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1000 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1002 $this->type('goal_amount', 10 * $rand);
1004 // FIXME: handle Start/End Date/Time
1005 if ($honoreeSection) {
1006 $this->click('honor_block_is_active');
1007 $this->type('honor_block_title', "Honoree Section Title $hash");
1008 $this->type('honor_block_text', "Honoree Introductory Message $hash");
1009 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1010 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1011 $this->waitForElementPresent("//*[@class='select2-result-label']");
1012 $this->clickAt("//*[@class='select2-results']/li[1]");
1015 // is confirm enabled? it starts out enabled, so uncheck it if false
1016 if (!$isConfirmEnabled) {
1017 $this->click("id=is_confirm_enabled");
1021 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1023 // Get contribution page id
1024 $pageId = $this->urlArg('id');
1026 // fill in step 2 (Processor, Pay Later, Amounts)
1027 if (!empty($processor)) {
1029 while (list($processorName) = each($processor)) {
1030 // select newly created processor
1031 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1032 $this->assertTrue($this->isTextPresent($processorName));
1033 $this->check($xpath);
1037 if ($amountSection && !$memPriceSetId) {
1039 $this->click('is_pay_later');
1040 $this->type('pay_later_text', "Pay later label $hash");
1041 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1045 $this->click('is_pledge_active');
1046 $this->click('pledge_frequency_unit[week]');
1047 $this->click('is_pledge_interval');
1048 $this->type('initial_reminder_day', 3);
1049 $this->type('max_reminders', 2);
1050 $this->type('additional_reminder_day', 1);
1052 elseif ($recurring) {
1053 $this->click('is_recur');
1054 $this->click("is_recur_interval");
1055 $this->click("is_recur_installments");
1057 if ($allowOtherAmount) {
1059 $this->click('is_allow_other_amount');
1061 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1062 //$this->type('min_amount', $rand / 2);
1063 //$this->type('max_amount', $rand * 10);
1065 if ($fixedAmount ||
!$allowOtherAmount) {
1066 $this->type('label_1', "Label $hash");
1067 $this->type('value_1', "$rand");
1069 $this->click('CIVICRM_QFID_1_4');
1072 $this->click('amount_block_is_active');
1075 $this->click('_qf_Amount_next');
1076 $this->waitForElementPresent('_qf_Amount_next-bottom');
1077 $this->waitForPageToLoad($this->getTimeoutMsec());
1078 $text = "'Amount' information has been saved.";
1079 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1081 if ($memPriceSetId ||
(($membershipTypes === TRUE) ||
(is_array($membershipTypes) && !empty($membershipTypes)))) {
1082 // go to step 3 (memberships)
1083 $this->click('link=Memberships');
1084 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1086 // fill in step 3 (Memberships)
1087 $this->click('member_is_active');
1088 $this->waitForElementPresent('displayFee');
1089 $this->type('new_title', "Title - New Membership $hash");
1090 $this->type('renewal_title', "Title - Renewals $hash");
1092 if ($memPriceSetId) {
1093 $this->click('member_price_set_id');
1094 $this->select('member_price_set_id', "value={$memPriceSetId}");
1097 if ($membershipTypes === TRUE) {
1098 $membershipTypes = array(array('id' => 2));
1101 // FIXME: handle Introductory Message - New Memberships/Renewals
1102 foreach ($membershipTypes as $mType) {
1103 $this->click("membership_type_{$mType['id']}");
1104 if (array_key_exists('default', $mType)) {
1107 if (array_key_exists('auto_renew', $mType)) {
1108 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1111 if ($membershipsRequired) {
1112 $this->click('is_required');
1114 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1115 $this->click('CIVICRM_QFID_2_4');
1116 if ($isSeparatePayment) {
1117 $this->click('is_separate_payment');
1120 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1121 $text = "'MembershipBlock' information has been saved.";
1122 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1125 // go to step 4 (thank-you and receipting)
1126 $this->click('link=Receipt');
1127 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1130 $this->type('thankyou_title', "Thank-you Page Title $hash");
1131 // FIXME: handle Thank-you Message/Page Footer
1132 $this->type('receipt_from_name', "Receipt From Name $hash");
1133 $this->type('receipt_from_email', "$hash@example.org");
1134 $this->type('receipt_text', "Receipt Message $hash");
1135 $this->type('cc_receipt', "$hash@example.net");
1136 $this->type('bcc_receipt', "$hash@example.com");
1138 $this->click('_qf_ThankYou_next');
1139 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1140 $this->waitForPageToLoad($this->getTimeoutMsec());
1141 $text = "'ThankYou' information has been saved.";
1142 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1145 // fill in step 5 (Tell a Friend)
1146 $this->click('link=Tell a Friend');
1147 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1148 $this->click('tf_is_active');
1149 $this->type('tf_title', "TaF Title $hash");
1150 $this->type('intro', "TaF Introduction $hash");
1151 $this->type('suggested_message', "TaF Suggested Message $hash");
1152 $this->type('general_link', "TaF Info Page Link $hash");
1153 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1154 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1156 //$this->click('_qf_Contribute_next');
1157 $this->click('_qf_Contribute_next-bottom');
1158 $this->waitForPageToLoad($this->getTimeoutMsec());
1159 $text = "'Friend' information has been saved.";
1160 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1163 if ($profilePreId ||
$profilePostId) {
1164 // fill in step 6 (Include Profiles)
1165 $this->click('css=li#tab_custom a');
1166 $this->waitForElementPresent('_qf_Custom_next-bottom');
1168 if ($profilePreId) {
1169 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1172 if ($profilePostId) {
1173 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1176 $this->click('_qf_Custom_next-bottom');
1177 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1179 $this->waitForPageToLoad($this->getTimeoutMsec());
1180 $text = "'Custom' information has been saved.";
1181 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1185 // fill in step 7 (Premiums)
1186 $this->click('link=Premiums');
1187 $this->waitForElementPresent('_qf_Premium_next-bottom');
1188 $this->click('premiums_active');
1189 $this->type('premiums_intro_title', "Prem Title $hash");
1190 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1191 $this->type('premiums_contact_email', "$hash@example.info");
1192 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1193 $this->click('premiums_display_min_contribution');
1194 $this->type('premiums_nothankyou_label', 'No thank-you');
1195 $this->click('_qf_Premium_next');
1196 $this->waitForElementPresent('_qf_Premium_next-bottom');
1198 $this->waitForPageToLoad($this->getTimeoutMsec());
1199 $text = "'Premium' information has been saved.";
1200 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1204 // fill in step 8 (Widget Settings)
1205 $this->click('link=Widgets');
1206 $this->waitForElementPresent('_qf_Widget_next-bottom');
1208 $this->click('is_active');
1209 $this->type('url_logo', "URL to Logo Image $hash");
1210 $this->type('button_title', "Button Title $hash");
1211 // Type About text in ckEditor (fieldname, text to type, editor)
1212 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1214 $this->click('_qf_Widget_next');
1215 $this->waitForElementPresent('_qf_Widget_next-bottom');
1217 $this->waitForPageToLoad($this->getTimeoutMsec());
1218 $text = "'Widget' information has been saved.";
1219 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1223 // fill in step 9 (Enable Personal Campaign Pages)
1224 $this->click('link=Personal Campaigns');
1225 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1226 $this->click('pcp_active');
1227 if (!$isPcpApprovalNeeded) {
1228 $this->click('is_approval_needed');
1230 $this->type('notify_email', "$hash@example.name");
1231 $this->select('supporter_profile_id', 'value=2');
1232 $this->type('tellfriend_limit', 7);
1233 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1235 $this->click('_qf_Contribute_next-bottom');
1236 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1237 $this->waitForPageToLoad($this->getTimeoutMsec());
1238 $text = "'Pcp' information has been saved.";
1239 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1246 * Function to update default strict rule.
1248 * @params string $contactType Contact type
1249 * @param string $contactType
1250 * @param array $fields Fields to be set for strict rule
1251 * @param Integer $threshold Rule's threshold value
1253 function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1254 // set default strict rule.
1256 if ($contactType == 'Organization') {
1259 elseif ($contactType == 'Household') {
1263 // Default dedupe fields for each Contact type.
1264 if (empty($fields)) {
1265 $fields = array('civicrm_email.email' => 10);
1266 if ($contactType == 'Organization') {
1268 'civicrm_contact.organization_name' => 10,
1269 'civicrm_email.email' => 10,
1272 elseif ($contactType == 'Household') {
1274 'civicrm_contact.household_name' => 10,
1275 'civicrm_email.email' => 10,
1280 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1283 foreach ($fields as $field => $weight) {
1284 $this->select("where_{$count}", "value={$field}");
1285 $this->type("length_{$count}", '');
1286 $this->type("weight_{$count}", $weight);
1291 $this->type('threshold', $threshold);
1293 $this->click('_qf_DedupeRules_next-bottom');
1294 $this->waitForPageToLoad($this->getTimeoutMsec());
1298 for ($i = $count; $i <= 4; $i++
) {
1299 $this->select("where_{$i}", 'label=- none -');
1300 $this->type("length_{$i}", '');
1301 $this->type("weight_{$i}", '');
1304 $this->type('threshold', $threshold);
1307 $this->click('_qf_DedupeRules_next-bottom');
1308 $this->waitForPageToLoad($this->getTimeoutMsec());
1312 * @param string $period_type
1313 * @param int $duration_interval
1314 * @param string $duration_unit
1315 * @param string $auto_renew
1319 function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1320 $membershipTitle = substr(sha1(rand()), 0, 7);
1321 $membershipOrg = $membershipTitle . ' memorg';
1322 $this->webtestAddOrganization($membershipOrg, TRUE);
1324 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1325 $memTypeParams = array(
1326 'membership_type' => $title,
1327 'member_of_contact' => $membershipOrg,
1328 'financial_type' => 2,
1329 'period_type' => $period_type,
1332 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1334 $this->type('name', $memTypeParams['membership_type']);
1336 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1337 // select the radio first since the element id changes after membership org search results are loaded
1338 switch ($auto_renew) {
1340 $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')]");
1344 $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')]");
1348 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1349 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')]")) {
1350 $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')]");
1355 $this->select2('member_of_contact_id',$membershipTitle);
1357 $this->type('minimum_fee', '100');
1358 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1360 $this->type('duration_interval', $duration_interval);
1361 $this->select('duration_unit', "label={$duration_unit}");
1363 $this->select('period_type', "value={$period_type}");
1365 $this->click('_qf_MembershipType_upload-bottom');
1366 $this->waitForElementPresent('link=Add Membership Type');
1367 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1369 return $memTypeParams;
1373 * @param null $groupName
1374 * @param null $parentGroupName
1376 * @return null|string
1378 function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1379 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1383 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1385 $this->type('title', $groupName);
1388 $this->type('description', 'Adding new group.');
1390 // check Access Control
1391 $this->click('group_type[1]');
1393 // check Mailing List
1394 $this->click('group_type[2]');
1396 // select Visibility as Public Pages
1397 $this->select('visibility', 'value=Public Pages');
1399 // select parent group
1400 if ($parentGroupName) {
1401 $this->select('parents', "*$parentGroupName");
1405 $this->clickLink('_qf_Edit_upload-bottom');
1407 // Is status message correct?
1408 $this->waitForText('crm-notification-container', "$groupName");
1413 * @param string $activityType
1417 function WebtestAddActivity($activityType = "Meeting") {
1418 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1419 // We're using Quick Add block on the main page for this.
1420 $firstName1 = substr(sha1(rand()), 0, 7);
1421 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1422 $firstName2 = substr(sha1(rand()), 0, 7);
1423 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1425 $this->click("css=li#tab_activity a");
1427 // waiting for the activity dropdown to show up
1428 $this->waitForElementPresent("other_activity");
1430 // Select the activity type from the activity dropdown
1431 $this->select("other_activity", "label=Meeting");
1433 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1434 $this->waitForElementPresent("s2id_target_contact_id");
1436 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__
);
1438 // Typing contact's name into the field (using typeKeys(), not type()!)...
1439 $this->select2("assignee_contact_id", $firstName1, TRUE);
1441 // ...and verifying if the page contains properly formatted display name for chosen contact.
1442 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__
);
1444 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1445 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1446 // For simple input fields we can use field id as selector
1447 $this->type("subject", $subject);
1448 $this->type("location", "Some location needs to be put in this field.");
1450 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1452 // Setting duration.
1453 $this->type("duration", "30");
1455 // Putting in details.
1456 $this->type("details", "Really brief details information.");
1458 // Making sure that status is set to Scheduled (using value, not label).
1459 $this->select("status_id", "value=1");
1461 // Setting priority.
1462 $this->select("priority_id", "value=1");
1464 // Scheduling follow-up.
1465 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1466 $this->select("followup_activity_type_id", "value=1");
1467 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1468 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1471 $this->click("_qf_Activity_upload-bottom");
1472 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1474 // Is status message correct?
1475 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1477 $this->waitForElementPresent("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1479 // click through to the Activity view screen
1480 $this->click("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1481 $this->waitForElementPresent('_qf_Activity_cancel-bottom');
1483 // parse URL to grab the activity id
1484 // pass id back to any other tests that call this class
1485 return $this->urlArg('id');
1492 function checkDoLocalDBTest() {
1493 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1494 CIVICRM_WEBTEST_LOCAL_DB
1496 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1503 * Generic function to compare expected values after an api call to retrieved
1506 * @daoName string DAO Name of object we're evaluating.
1507 * @id int Id of object
1508 * @match array Associative array of field name => expected value. Empty if asserting
1509 * that a DELETE occurred
1510 * @delete boolean True if we're checking that a DELETE action occurred.
1512 function assertDBState($daoName, $id, $match, $delete = FALSE) {
1513 if (!self
::checkDoLocalDBTest()) {
1517 return CiviDBAssert
::assertDBState($this, $daoName, $id, $match, $delete);
1520 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1523 * @param $searchValue
1524 * @param $returnColumn
1525 * @param $searchColumn
1528 * @return null|string
1530 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1531 if (!self
::checkDoLocalDBTest()) {
1535 return CiviDBAssert
::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1538 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1541 * @param $searchValue
1542 * @param $returnColumn
1543 * @param $searchColumn
1546 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1547 if (!self
::checkDoLocalDBTest()) {
1551 return CiviDBAssert
::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1554 // Request a record from the DB by id. Success if row not found.
1560 function assertDBRowNotExist($daoName, $id, $message) {
1561 if (!self
::checkDoLocalDBTest()) {
1565 return CiviDBAssert
::assertDBRowNotExist($this, $daoName, $id, $message);
1568 // Compare a single column value in a retrieved DB record to an expected value
1571 * @param $searchValue
1572 * @param $returnColumn
1573 * @param $searchColumn
1574 * @param $expectedValue
1575 * @param string $message
1577 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1578 $expectedValue, $message
1580 if (!self
::checkDoLocalDBTest()) {
1584 return CiviDBAssert
::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1585 $expectedValue, $message
1589 // Compare all values in a single retrieved DB record to an array of expected values
1592 * @param $searchParams
1593 * @param $expectedValues
1595 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1596 if (!self
::checkDoLocalDBTest()) {
1600 return CiviDBAssert
::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1604 * @param $expectedValues
1605 * @param $actualValues
1607 function assertAttributesEquals(&$expectedValues, &$actualValues) {
1608 if (!self
::checkDoLocalDBTest()) {
1612 return CiviDBAssert
::assertAttributesEquals($expectedValues, $actualValues);
1618 * @param string $message
1620 function assertType($expected, $actual, $message = '') {
1621 return $this->assertInternalType($expected, $actual, $message);
1625 * Add new Financial Account
1627 function _testAddFinancialAccount($financialAccountTitle,
1628 $financialAccountDescription = FALSE,
1629 $accountingCode = FALSE,
1631 $financialAccountType = FALSE,
1632 $taxDeductible = FALSE,
1639 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1641 $this->click("link=Add Financial Account");
1642 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1644 // Financial Account Name
1645 $this->type('name', $financialAccountTitle);
1647 // Financial Description
1648 if ($financialAccountDescription) {
1649 $this->type('description', $financialAccountDescription);
1653 if ($accountingCode) {
1654 $this->type('accounting_code', $accountingCode);
1657 // Autofill Organization
1659 $this->webtestOrganisationAutocomplete($firstName);
1662 // Financial Account Type
1663 if ($financialAccountType) {
1664 $this->select('financial_account_type_id', "label={$financialAccountType}");
1667 // Is Tax Deductible
1668 if ($taxDeductible) {
1669 $this->check('is_deductible');
1672 $this->uncheck('is_deductible');
1676 $this->check('is_active');
1679 $this->uncheck('is_active');
1683 $this->check('is_tax');
1686 $this->uncheck('is_tax');
1690 $this->type('tax_rate', $taxRate);
1695 $this->check('is_default');
1698 $this->uncheck('is_default');
1700 $this->click('_qf_FinancialAccount_next-botttom');
1704 * Edit Financial Account
1706 function _testEditFinancialAccount($editfinancialAccount,
1707 $financialAccountTitle = FALSE,
1708 $financialAccountDescription = FALSE,
1709 $accountingCode = FALSE,
1711 $financialAccountType = FALSE,
1712 $taxDeductible = FALSE,
1719 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1722 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
1723 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1725 // Change Financial Account Name
1726 if ($financialAccountTitle) {
1727 $this->type('name', $financialAccountTitle);
1730 // Financial Description
1731 if ($financialAccountDescription) {
1732 $this->type('description', $financialAccountDescription);
1736 if ($accountingCode) {
1737 $this->type('accounting_code', $accountingCode);
1740 // Autofill Edit Organization
1742 $this->webtestOrganisationAutocomplete($firstName);
1745 // Financial Account Type
1746 if ($financialAccountType) {
1747 $this->select('financial_account_type_id', "label={$financialAccountType}");
1750 // Is Tax Deductible
1751 if ($taxDeductible) {
1752 $this->check('is_deductible');
1755 $this->uncheck('is_deductible');
1760 $this->check('is_tax');
1763 $this->uncheck('is_tax');
1768 $this->type('tax_rate', $taxRate);
1773 $this->check('is_default');
1776 $this->uncheck('is_default');
1781 $this->check('is_active');
1784 $this->uncheck('is_active');
1786 $this->click('_qf_FinancialAccount_next-botttom');
1787 $this->waitForElementPresent('link=Add Financial Account');
1791 * Delete Financial Account
1793 function _testDeleteFinancialAccount($financialAccountTitle) {
1794 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1795 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1796 $this->click('_qf_FinancialAccount_next-botttom');
1797 $this->waitForElementPresent('link=Add Financial Account');
1798 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1802 * Verify data after ADD and EDIT
1804 function _assertFinancialAccount($verifyData) {
1805 foreach ($verifyData as $key => $expectedValue) {
1806 $actualValue = $this->getValue($key);
1807 if ($key == 'parent_financial_account') {
1808 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1811 $this->assertEquals($expectedValue, $actualValue);
1817 * @param $verifySelectFieldData
1819 function _assertSelectVerify($verifySelectFieldData) {
1820 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1821 $actualvalue = $this->getSelectedLabel($key);
1822 $this->assertEquals($expectedvalue, $actualvalue);
1827 * @param $financialType
1828 * @param string $option
1830 function addeditFinancialType($financialType, $option = 'new') {
1831 $this->openCiviPage("admin/financial/financialType", "reset=1");
1833 if ($option == 'Delete') {
1834 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1835 $this->waitForElementPresent("css=span.btn-slide-active");
1836 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1837 $this->waitForElementPresent("_qf_FinancialType_next");
1838 $this->click("_qf_FinancialType_next");
1839 $this->waitForElementPresent("newFinancialType");
1840 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1843 if ($option == 'new') {
1844 $this->click("link=Add Financial Type");
1847 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1849 $this->waitForElementPresent("name");
1850 $this->type('name', $financialType['name']);
1851 if ($option == 'new') {
1852 $this->type('description', $financialType['name'] . ' description');
1855 if ($financialType['is_reserved']) {
1856 $this->check('is_reserved');
1859 $this->uncheck('is_reserved');
1862 if ($financialType['is_deductible']) {
1863 $this->check('is_deductible');
1866 $this->uncheck('is_deductible');
1869 $this->click('_qf_FinancialType_next');
1870 if ($option == 'new') {
1871 $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.";
1874 $text = "The financial type '{$financialType['name']}' has been saved.";
1876 $this->waitForText('crm-notification-container', $text);
1880 * Give the specified permissions
1881 * Note: this function logs in as 'admin' (logging out if necessary)
1883 function changePermissions($permission) {
1884 $this->webtestLogin('admin');
1885 $this->open("{$this->sboxPath}admin/people/permissions");
1886 $this->waitForElementPresent('edit-submit');
1887 foreach ((array) $permission as $perm) {
1888 $this->check($perm);
1890 $this->click('edit-submit');
1891 $this->waitForPageToLoad($this->getTimeoutMsec());
1892 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
1896 * @param $profileTitle
1897 * @param $profileFields
1899 function addProfile($profileTitle, $profileFields) {
1900 $this->openCiviPage('admin/uf/group', "reset=1");
1902 $this->click('link=Add Profile');
1904 // Add membership custom data field to profile
1905 $this->waitForElementPresent('_qf_Group_cancel-bottom');
1906 $this->type('title', $profileTitle);
1907 $this->click('_qf_Group_next-bottom');
1909 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1910 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now."));
1912 foreach ($profileFields as $field) {
1913 $this->waitForElementPresent('field_name_0');
1914 // $this->waitForPageToLoad($this->getTimeoutMsec());
1915 $this->click("id=field_name_0");
1916 $this->select("id=field_name_0", "label=" . $field['type']);
1917 $this->waitForElementPresent('field_name_1');
1918 $this->click("id=field_name_1");
1919 $this->select("id=field_name_1", "label=" . $field['name']);
1920 $this->waitForElementPresent('label');
1921 $this->type("id=label", $field['label']);
1922 $this->click("id=_qf_Field_next_new-top");
1923 $this->waitForPageToLoad($this->getTimeoutMsec());
1924 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
1934 * @param $financialType
1936 function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
1937 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
1938 $this->type("name", $name);
1939 $this->type("sku", $sku);
1940 $this->click("CIVICRM_QFID_noImage_16");
1941 $this->type("min_contribution", $amount);
1942 $this->type("price", $price);
1943 $this->type("cost", $cost);
1944 if ($financialType) {
1945 $this->select("financial_type_id", "label={$financialType}");
1947 $this->click("_qf_ManagePremiums_upload-bottom");
1948 $this->waitForPageToLoad($this->getTimeoutMsec());
1953 * @param $financialAccount
1955 function addPaymentInstrument($label, $financialAccount) {
1956 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
1957 $this->type("label", $label);
1958 $this->select("financial_account_id", "value=$financialAccount");
1959 $this->click("_qf_Options_next-bottom");
1960 $this->waitForPageToLoad($this->getTimeoutMsec());
1964 * Ensure we have a default mailbox set up for CiviMail
1966 function setupDefaultMailbox() {
1967 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
1968 // Check if it hasn't already been set up
1969 if (!$this->getSelectedValue('protocol')) {
1970 $this->type('name', 'Test Domain');
1971 $this->select('protocol', "IMAP");
1972 $this->type('server', 'localhost');
1973 $this->type('domain', 'example.com');
1974 $this->click('_qf_MailSettings_next-top');
1975 $this->waitForPageToLoad($this->getTimeoutMsec());
1980 * Determine the default time-out in milliseconds.
1982 * @return string, timeout expressed in milliseconds
1984 function getTimeoutMsec() {
1985 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
1986 $timeout = ($this->settings
&& @$this->settings
->timeout
) ?
($this->settings
->timeout
* 1000) : 30000;
1987 return (string) $timeout; // don't know why, but all our old code used a string
1992 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
1995 * @param array $customSets custom sets i.e entity wise sets want to be created and checked
1996 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
1997 'triggerElement' => $triggerElement))
1998 array $triggerElement: the element which is responsible for custom group to load
2000 which uses the entity info as its selection value
2001 * @param array $pageUrl the url which on which the ajax custom group load takes place
2002 * @param $beforeTriggering code to execute before actual element triggering
2005 function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
2006 //add the custom set
2007 $return = $this->addCustomGroupField($customSets);
2009 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
2010 foreach($return as $values) {
2011 foreach ($values as $entityType => $customData) {
2012 //initiate necessary variables
2013 list($entity, $entityData) = explode('_', $entityType);
2014 $elementType = CRM_Utils_Array
::value('type', $customData['triggerElement'], 'select');
2015 $elementName = CRM_Utils_Array
::value('name', $customData['triggerElement']);
2016 if ($beforeTriggering) {
2017 call_user_func($beforeTriggering);
2019 if ($elementType == 'select') {
2020 //reset the select box, so triggering of ajax only happens
2021 //WRT input of value in this function
2022 $this->select($elementName, "index=0");
2024 if (!empty($entityData)) {
2025 if ($elementType == 'select') {
2026 $this->select($elementName, "label=regexp:{$entityData}");
2028 elseif ($elementType == 'checkbox') {
2029 $val = explode(',', $entityData);
2030 foreach($val as $v) {
2031 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2032 $this->check($checkId);
2035 elseif ($elementType == 'select2') {
2036 $this->select2($elementName, $entityData);
2039 //checking for proper custom data which is loading through ajax
2040 $this->waitForElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]",
2041 "The on the fly custom group has not been rendered for entity : {$entity} => {$entityData}");
2042 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2043 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2049 * @param $customSets
2053 function addCustomGroupField($customSets) {
2054 foreach ($customSets as $customSet) {
2055 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2057 //fill custom group title
2058 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2059 $this->click("title");
2060 $this->type("title", $customGroupTitle);
2062 //custom group extends
2063 $this->click("extends_0");
2064 $this->select("extends_0", "value={$customSet['entity']}");
2065 if (!empty($customSet['subEntity'])) {
2066 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2070 $this->uncheck('collapse_display');
2073 $this->click('_qf_Group_next-bottom');
2075 //Is custom group created?
2076 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2077 $this->click('css=a#newCustomField');
2079 $gid = $this->urlArg('gid');
2080 $this->waitForTextPresent("{$customGroupTitle} - New Field");
2082 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2083 $this->type('label', $fieldLabel);
2084 $this->click('_qf_Field_next_new-bottom');
2085 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2088 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
2094 * function to type and select first occurance of autocomplete
2096 function select2($fieldName,$label, $multiple = FALSE, $xpath=FALSE) {
2098 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2099 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2100 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2101 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2102 $this->waitForElementPresent("//*[@class='select2-result-label']");
2103 $this->clickAt("//*[@class='select2-results']/li[1]/div");
2107 $this->clickAt($fieldName);
2110 $this->clickAt("//*[@id='$fieldName']/../div/a");
2112 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2113 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2114 $this->type("//*[@id='select2-drop']/div/input", $label);
2115 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
2116 $this->waitForElementPresent("//*[@class='select2-result-label']");
2117 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2122 * function to select multiple options
2124 function multiselect2($fieldid, $params) {
2125 foreach($params as $value) {
2126 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2127 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2128 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2129 $this->assertElementContainsText("xpath=//*[@id='$fieldid']/preceding-sibling::div[1]/", $value);
2134 * function to enable or disable Pop-ups via Display Preferences
2136 function enableDisablePopups($enabled = TRUE) {
2137 $this->openCiviPage('admin/setting/preferences/display', 'reset=1');
2138 $isChecked = $this->isChecked('ajaxPopupsEnabled');
2139 if (($isChecked && !$enabled) ||
(!$isChecked && $enabled)) {
2140 $this->click('ajaxPopupsEnabled');
2143 $this->assertChecked('ajaxPopupsEnabled');
2146 $this->assertNotChecked('ajaxPopupsEnabled');
2148 $this->click("_qf_Display_next-bottom");
2149 $this->waitForPageToLoad($this->getTimeoutMsec());