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 +--------------------------------------------------------------------+
28 require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
31 * Include configuration
33 define('CIVICRM_SETTINGS_PATH', __DIR__
. '/civicrm.settings.dist.php');
34 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__
. '/civicrm.settings.local.php');
35 define('CIVICRM_WEBTEST', 1);
37 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH
)) {
38 require_once CIVICRM_SETTINGS_LOCAL_PATH
;
40 require_once CIVICRM_SETTINGS_PATH
;
43 * Base class for CiviCRM Selenium tests
45 * Common functions for unit tests
48 class CiviSeleniumTestCase
extends PHPUnit_Extensions_SeleniumTestCase
{
50 // Current logged-in user
51 protected $loggedInAs = NULL;
56 * Because we are overriding the parent class constructor, we
57 * need to show the same arguments as exist in the constructor of
58 * PHPUnit_Framework_TestCase, since
59 * PHPUnit_Framework_TestSuite::createTest() creates a
60 * ReflectionClass of the Test class and checks the constructor
61 * of that class to decide how to set up the test.
65 * @param string $dataName
66 * @param array $browser
68 function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
69 parent
::__construct($name, $data, $dataName, $browser);
70 $this->loggedInAs
= NULL;
72 require_once 'CiviSeleniumSettings.php';
73 $this->settings
= new CiviSeleniumSettings();
74 if (property_exists($this->settings
, 'serverStartupTimeOut') && $this->settings
->serverStartupTimeOut
) {
75 global $CiviSeleniumTestCase_polled;
76 if (!$CiviSeleniumTestCase_polled) {
77 $CiviSeleniumTestCase_polled = TRUE;
78 CRM_Utils_Network
::waitForServiceStartup(
79 $this->drivers
[0]->getHost(),
80 $this->drivers
[0]->getPort(),
81 $this->settings
->serverStartupTimeOut
87 require_once 'CRM/Core/ClassLoader.php';
88 CRM_Core_ClassLoader
::singleton()->register();
90 // also initialize a connection to the db
91 // FIXME: not necessary for most tests, consider moving into functions that need this
92 $config = CRM_Core_Config
::singleton();
95 protected function setUp() {
96 $this->setBrowser($this->settings
->browser
);
97 // Make sure that below strings have path separator at the end
98 $this->setBrowserUrl($this->settings
->sandboxURL
);
99 $this->sboxPath
= $this->settings
->sandboxPATH
;
100 if (property_exists($this->settings
, 'rcHost') && $this->settings
->rcHost
) {
101 $this->setHost($this->settings
->rcHost
);
103 if (property_exists($this->settings
, 'rcPort') && $this->settings
->rcPort
) {
104 $this->setPort($this->settings
->rcPort
);
108 protected function tearDown() {
112 * Authenticate as drupal user
113 * @param $user: (str) the key 'user' or 'admin', or a literal username
114 * @param $pass: (str) if $user is a literal username and not 'user' or 'admin', supply the password
116 function webtestLogin($user = 'user', $pass = NULL) {
117 // If already logged in as correct user, do nothing
118 if ($this->loggedInAs
=== $user) {
121 // If we are logged in as a different user, log out first
122 if ($this->loggedInAs
) {
123 $this->webtestLogout();
125 $this->open("{$this->sboxPath}user");
126 // Lookup username & password if not supplied
128 if ($pass === NULL) {
129 $pass = $user == 'admin' ?
$this->settings
->adminPassword
: $this->settings
->password
;
130 $username = $user == 'admin' ?
$this->settings
->adminUsername
: $this->settings
->username
;
132 // Make sure login form is available
133 $this->waitForElementPresent('edit-submit');
134 $this->type('edit-name', $username);
135 $this->type('edit-pass', $pass);
136 $this->click('edit-submit');
137 $this->waitForPageToLoad($this->getTimeoutMsec());
138 $this->loggedInAs
= $user;
141 function webtestLogout() {
142 if ($this->loggedInAs
) {
143 $this->open($this->sboxPath
. "user/logout");
144 $this->waitForPageToLoad($this->getTimeoutMsec());
146 $this->loggedInAs
= NULL;
150 * Open an internal path beginning with 'civicrm/'
152 * @param $url (str) omit the 'civicrm/' it will be added for you
153 * @param $args (str|array) optional url arguments
154 * @param $waitFor - page element to wait for - using this is recommended to ensure the document is fully loaded
156 * Although it doesn't seem to do much now, using this function is recommended for
157 * opening all civi pages, and using the $args param is also strongly encouraged
158 * This will make it much easier to run webtests in other CMSs in the future
160 function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
161 // Construct full url with args
162 // This could be extended in future to work with other CMS style urls
164 if (is_array($args)) {
166 foreach ($args as $key => $val) {
167 $url .= $sep . $key . '=' . $val;
175 $this->open("{$this->sboxPath}civicrm/$url");
176 $this->waitForPageToLoad($this->getTimeoutMsec());
178 $this->waitForElementPresent($waitFor);
183 * Click on a link or button
184 * Wait for the page to load
185 * Wait for an element to be present
187 function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
188 $this->click($element);
189 // conditional wait for page load e.g for ajax form save
190 if ($waitForPageLoad) {
191 $this->waitForPageToLoad($this->getTimeoutMsec());
194 $this->waitForElementPresent($waitFor);
199 * Call the API on the local server
200 * (kind of defeats the point of a webtest - see CRM-11889)
202 function webtest_civicrm_api($entity, $action, $params) {
203 if (!isset($params['version'])) {
204 $params['version'] = 3;
207 $result = civicrm_api($entity, $action, $params);
208 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
213 * Call the API on the remote server
214 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
217 function rest_civicrm_api($entity, $action, $params = array()) {
221 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
225 // Naughty sidestep of civi's security checks
226 'header' => "X-Requested-With: XMLHttpRequest",
229 $ctx = stream_context_create($request);
230 $result = file_get_contents($url, FALSE, $ctx);
231 return json_decode($result, TRUE);
235 * @param $option_group_name
239 function webtestGetFirstValueForOptionGroup($option_group_name) {
240 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
241 'option_group_name' => $option_group_name,
251 function webtestGetValidCountryID() {
253 if (is_null($_country_id)) {
254 $config_backend = $this->webtestGetConfig('countryLimit');
255 $_country_id = current($config_backend);
265 function webtestGetValidEntityID($entity) {
266 // michaelmcandrew: would like to use getvalue but there is a bug
267 // for e.g. group where option.limit not working at the moment CRM-9110
268 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
269 if (!empty($result['values'])) {
270 return current(array_keys($result['values']));
280 function webtestGetConfig($field) {
281 static $_config_backend;
282 if (is_null($_config_backend)) {
283 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
284 'current_domain' => 1,
286 'return' => 'config_backend'
288 $_config_backend = unserialize($result);
290 return $_config_backend[$field];
294 * Ensures the required CiviCRM components are enabled
296 function enableComponents($components) {
297 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
298 $enabledComponents = $this->getSelectOptions("enableComponents-t");
300 foreach ((array) $components as $comp) {
301 if (!in_array($comp, $enabledComponents)) {
302 $this->addSelection("enableComponents-f", "label=$comp");
303 $this->click("//option[@value='$comp']");
309 $this->click("_qf_Component_next-bottom");
310 $this->waitForPageToLoad($this->getTimeoutMsec());
311 $this->waitForText('crm-notification-container', "Saved");
316 * Add a contact with the given first and last names and either a given email
317 * (when specified), a random email (when true) or no email (when unspecified or null).
319 * @param string $fname contact’s first name
320 * @param string $lname contact’s last name
321 * @param mixed $email contact’s email (when string) or random email (when true) or no email (when null)
323 * @param null $contactSubtype
325 * @return mixed either a string with the (either generated or provided) email or null (if no email)
327 function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
328 $url = $this->sboxPath
. 'civicrm/contact/add?reset=1&ct=Individual';
329 if ($contactSubtype) {
330 $url = $url . "&cst={$contactSubtype}";
333 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
334 $this->type('first_name', $fname);
335 $this->type('last_name', $lname);
336 if ($email === TRUE) {
337 $email = substr(sha1(rand()), 0, 7) . '@example.org';
340 $this->type('email_1_email', $email);
342 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
343 $this->click('_qf_Contact_upload_view-bottom');
344 $this->waitForPageToLoad($this->getTimeoutMsec());
349 * @param string $householdName
352 * @return null|string
354 function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
356 $this->openCiviPage("contact/add", "reset=1&ct=Household");
357 $this->click('household_name');
358 $this->type('household_name', $householdName);
360 if ($email === TRUE) {
361 $email = substr(sha1(rand()), 0, 7) . '@example.org';
364 $this->type('email_1_email', $email);
367 $this->click('_qf_Contact_upload_view');
368 $this->waitForPageToLoad($this->getTimeoutMsec());
373 * @param string $organizationName
375 * @param null $contactSubtype
377 * @return null|string
379 function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
381 $url = $this->sboxPath
. 'civicrm/contact/add?reset=1&ct=Organization';
382 if ($contactSubtype) {
383 $url = $url . "&cst={$contactSubtype}";
386 $this->click('organization_name');
387 $this->type('organization_name', $organizationName);
389 if ($email === TRUE) {
390 $email = substr(sha1(rand()), 0, 7) . '@example.org';
393 $this->type('email_1_email', $email);
395 $this->click('_qf_Contact_upload_view');
396 $this->waitForPageToLoad($this->getTimeoutMsec());
402 function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
403 $this->select2($fieldName,$sortName);
404 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
409 function webtestOrganisationAutocomplete($sortName) {
410 $this->clickAt("//*[@id='contact_id']/../div/a");
411 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
412 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
413 $this->type("//*[@id='select2-drop']/div/input", $sortName);
414 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
415 $this->waitForElementPresent("//*[@class='select2-result-label']");
416 $this->clickAt("//*[@class='select2-results']/li[1]");
417 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
421 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
422 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
423 * 3. Examples of $strToTime arguments -
424 * webtestFillDate('start_date',"now")
425 * webtestFillDate('start_date',"10 September 2000")
426 * webtestFillDate('start_date',"+1 day")
427 * webtestFillDate('start_date',"+1 week")
428 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
429 * webtestFillDate('start_date',"next Thursday")
430 * webtestFillDate('start_date',"last Monday")
433 * @param $dateElement
434 * @param null $strToTimeArgs
436 function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
437 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
439 $year = date('Y', $timeStamp);
440 // -1 ensures month number is inline with calender widget's month
441 $mon = date('n', $timeStamp) - 1;
442 $day = date('j', $timeStamp);
444 $this->click("{$dateElement}_display");
445 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
446 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
447 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
448 $this->click("link=$day");
451 // 1. set both date and time.
453 * @param $dateElement
454 * @param null $strToTimeArgs
456 function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
457 $this->webtestFillDate($dateElement, $strToTimeArgs);
459 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
460 $hour = date('h', $timeStamp);
461 $min = date('i', $timeStamp);
462 $meri = date('A', $timeStamp);
464 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
468 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
470 * @param array $expected Array of key/value pairs (like Status/Registered) to be checked
471 * @param string $xpathPrefix Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath
472 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
473 * @param string $tableId Pass in the id attribute of a table to be verified if you want to only check a specific table
476 function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
479 $tableLocator = "[@id='$tableId']";
481 foreach ($expected as $label => $value) {
483 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
484 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
487 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
488 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
494 * Types text into a ckEditor rich text field in a form
496 * @param string $fieldName form field name (as assigned by PHP buildForm class)
497 * @param string $text text to type into the field
498 * @param string $editor which text editor (valid values are 'CKEditor', 'TinyMCE')
502 function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor') {
503 // make sure cursor focuses on the field
504 $this->fireEvent($fieldName, 'focus');
505 if ($editor == 'CKEditor') {
506 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
507 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
509 elseif ($editor == 'TinyMCE') {
510 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
511 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
514 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
516 $this->selectFrame('relative=top');
520 * Types option label and name into a table of multiple choice options
521 * (for price set fields of type select, radio, or checkbox)
522 * TODO: extend for custom field multiple choice table input
524 * @param array $options form field name (as assigned by PHP buildForm class)
525 * @param array $validateStrings appends label and name strings to this array so they can be validated later
529 function addMultipleChoiceOptions($options, &$validateStrings) {
530 foreach ($options as $oIndex => $oValue) {
531 $validateStrings[] = $oValue['label'];
532 $validateStrings[] = $oValue['amount'];
533 if (!empty($oValue['membership_type_id'])) {
534 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
536 if (!empty($oValue['financial_type_id'])) {
537 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
539 $this->type("option_label_{$oIndex}", $oValue['label']);
540 $this->type("option_amount_{$oIndex}", $oValue['amount']);
541 $this->click('link=another choice');
547 function webtestNewDialogContact($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
548 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
549 // 4 - Individual profile
550 // 5 - Organization profile
551 // 6 - Household profile
552 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
553 $this->clickAt("xpath=//div[@id='$selectId']/a");
554 $this->click("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]");
556 $this->waitForElementPresent('_qf_Edit_next');
560 $this->type('first_name', $fname);
561 $this->type('last_name', $lname);
565 $this->type('organization_name', $fname);
569 $this->type('household_name', $fname);
573 $this->type('email-Primary', $email);
574 $this->click('_qf_Edit_next');
576 // Is new contact created?
578 $this->waitForText("xpath=//div[@id='$selectId']","$lname, $fname");
581 $this->waitForText("xpath=//div[@id='$selectId']","$fname");
586 * Generic function to check that strings are present in the page
588 * @strings array array of strings or a single string
593 function assertStringsPresent($strings) {
594 foreach ((array) $strings as $string) {
595 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
600 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
602 * @url string url to parse or retrieve current url if null
605 * @return array returns an associative array containing any of the various components
606 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
607 * http://php.net/manual/en/function.parse-url.php
609 function parseURL($url = NULL) {
611 $url = $this->getLocation();
614 $elements = parse_url($url);
615 if (!empty($elements['query'])) {
616 $elements['queryString'] = array();
617 parse_str($elements['query'], $elements['queryString']);
623 * Returns a single argument from the url query
625 function urlArg($arg, $url = NULL) {
626 $elements = $this->parseURL($url);
627 return isset($elements['queryString'][$arg]) ?
$elements['queryString'][$arg] : NULL;
631 * Define a payment processor for use by a webtest. Default is to create Dummy processor
632 * which is useful for testing online public forms (online contribution pages and event registration)
634 * @param string $processorName Name assigned to new processor
635 * @param string $processorType Name for processor type (e.g. PayPal, Dummy, etc.)
636 * @param array $processorSettings Array of fieldname => value for required settings for the processor
638 * @param string $financialAccount
639 * @throws PHPUnit_Framework_AssertionFailedError
643 function webtestAddPaymentProcessor($processorName, $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
644 if (!$processorName) {
645 $this->fail("webTestAddPaymentProcessor requires $processorName.");
647 if ($processorType == 'Dummy') {
648 $processorSettings = array(
649 'user_name' => 'dummy',
650 'url_site' => 'http://dummy.com',
651 'test_user_name' => 'dummytest',
652 'test_url_site' => 'http://dummytest.com',
655 elseif ($processorType == 'AuthNet') {
656 // FIXME: we 'll need to make a new separate account for testing
657 $processorSettings = array(
658 'test_user_name' => '5ULu56ex',
659 'test_password' => '7ARxW575w736eF5p',
662 elseif ($processorType == 'Google_Checkout') {
663 // FIXME: we 'll need to make a new separate account for testing
664 $processorSettings = array(
665 'test_user_name' => '559999327053114',
666 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
669 elseif ($processorType == 'PayPal') {
670 $processorSettings = array(
671 'test_user_name' => '559999327053114',
672 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
673 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
676 elseif ($processorType == 'PayPal_Standard') {
677 $processorSettings = array(
678 'test_user_name' => 'V18ki@9r5Bf.org',
681 elseif (empty($processorSettings)) {
682 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
684 $pid = CRM_Core_DAO
::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
686 $this->fail("$processorType processortype not found.");
688 $this->open($this->sboxPath
. 'civicrm/admin/paymentProcessor?action=add&reset=1&pp=' . $pid);
689 $this->waitForPageToLoad($this->getTimeoutMsec());
690 $this->type('name', $processorName);
691 $this->select('financial_account_id', "label={$financialAccount}");
693 foreach ($processorSettings AS $f => $v) {
696 $this->click('_qf_PaymentProcessor_next-bottom');
697 $this->waitForPageToLoad($this->getTimeoutMsec());
698 // Is new processor created?
699 $this->assertTrue($this->isTextPresent($processorName), 'Processor name not found in selector after adding payment processor (webTestAddPaymentProcessor).');
701 $paymentProcessorId = explode('&id=', $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href"));
702 $paymentProcessorId = explode('&', $paymentProcessorId[1]);
703 return $paymentProcessorId[0];
706 function webtestAddCreditCardDetails() {
707 $this->waitForElementPresent('credit_card_type');
708 $this->select('credit_card_type', 'label=Visa');
709 $this->type('credit_card_number', '4807731747657838');
710 $this->type('cvv2', '123');
711 $this->select('credit_card_exp_date[M]', 'label=Feb');
712 $this->select('credit_card_exp_date[Y]', 'label=2019');
716 * @param null $firstName
717 * @param null $middleName
718 * @param null $lastName
722 function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
728 $middleName = 'Apple';
732 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
735 $this->type('billing_first_name', $firstName);
736 $this->type('billing_middle_name', $middleName);
737 $this->type('billing_last_name', $lastName);
739 $this->type('billing_street_address-5', '234 Lincoln Ave');
740 $this->type('billing_city-5', 'San Bernadino');
741 $this->select('billing_country_id-5', 'value=1228');
742 $this->click('billing_state_province_id-5');
743 $this->select('billing_state_province_id-5', 'label=California');
744 $this->type('billing_postal_code-5', '93245');
746 return array($firstName, $middleName, $lastName);
750 * @param $fieldLocator
751 * @param null $filePath
753 * @return null|string
755 function webtestAttachFile($fieldLocator, $filePath = NULL) {
757 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
758 $fp = @fopen
($filePath, 'w');
759 fputs($fp, 'Test file created by selenium test.');
763 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
765 $this->attachFile($fieldLocator, "file://{$filePath}");
773 * @param null $filePath
775 * @return null|string
777 function webtestCreateCSV($headers, $rows, $filePath = NULL) {
779 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
782 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
784 foreach ($rows as $row) {
786 foreach ($headers as $field => $header) {
787 $temp[$field] = isset($row[$field]) ?
'"' . $row[$field] . '"' : '""';
789 $data .= implode(', ', $temp) . "\r\n";
792 $fp = @fopen
($filePath, 'w');
796 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
802 * Create new relationship type w/ user specified params or default.
804 * @param $params array of required params.
806 * @return an array of saved params values.
808 function webtestAddRelationshipType($params = array()) {
809 $this->openCiviPage("admin/reltype", "reset=1&action=add");
811 //build the params if not passed.
812 if (!is_array($params) ||
empty($params)) {
814 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
815 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
816 'contact_types_a' => 'Individual',
817 'contact_types_b' => 'Individual',
818 'description' => 'Test Relationship Type Description',
821 //make sure we have minimum required params.
822 if (!isset($params['label_a_b']) ||
empty($params['label_a_b'])) {
823 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
826 //start the form fill.
827 $this->type('label_a_b', $params['label_a_b']);
828 $this->type('label_b_a', $params['label_b_a']);
829 $this->select('contact_types_a', "value={$params['contact_type_a']}");
830 $this->select('contact_types_b', "value={$params['contact_type_b']}");
831 $this->type('description', $params['description']);
834 $this->click('_qf_RelationshipType_next-bottom');
835 $this->waitForPageToLoad($this->getTimeoutMsec());
838 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
839 "Status message didn't show up after saving!"
842 $this->openCiviPage("admin/reltype", "reset=1");
844 //validate data on selector.
846 if (isset($data['description'])) {
847 unset($data['description']);
849 $this->assertStringsPresent($data);
855 * Create new online contribution page w/ user specified params or defaults.
856 * FIXME: this function take an absurd number of params - very unwieldy :(
860 * @param null $pageTitle
861 * @param array $processor
862 * @param bool $amountSection
863 * @param bool $payLater
864 * @param bool $onBehalf
865 * @param bool $pledges
866 * @param bool $recurring
867 * @param bool $membershipTypes
868 * @param null $memPriceSetId
869 * @param bool $friend
870 * @param int $profilePreId
871 * @param int $profilePostId
872 * @param bool $premiums
873 * @param bool $widget
875 * @param bool $isAddPaymentProcessor
876 * @param bool $isPcpApprovalNeeded
877 * @param bool $isSeparatePayment
878 * @param bool $honoreeSection
879 * @param bool $allowOtherAmount
880 * @param bool $isConfirmEnabled
881 * @param string $financialType
882 * @param bool $fixedAmount
883 * @param bool $membershipsRequired
884 * @internal param \can $User define pageTitle, hash and rand values for later data verification
886 * @return null $pageId of newly created online contribution page.
888 function webtestAddContributionPage($hash = NULL,
891 $processor = array('Dummy Processor' => 'Dummy'),
892 $amountSection = TRUE,
897 $membershipTypes = TRUE,
898 $memPriceSetId = NULL,
905 $isAddPaymentProcessor = TRUE,
906 $isPcpApprovalNeeded = FALSE,
907 $isSeparatePayment = FALSE,
908 $honoreeSection = TRUE,
909 $allowOtherAmount = TRUE,
910 $isConfirmEnabled = TRUE,
911 $financialType = 'Donation',
913 $membershipsRequired = TRUE
916 $hash = substr(sha1(rand()), 0, 7);
919 $pageTitle = 'Donate Online ' . $hash;
923 $rand = 2 * rand(2, 50);
926 // Create a new payment processor if requested
927 if ($isAddPaymentProcessor) {
928 while (list($processorName, $processorType) = each($processor)) {
929 $this->webtestAddPaymentProcessor($processorName, $processorType);
933 // go to the New Contribution Page page
934 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
936 // fill in step 1 (Title and Settings)
937 $this->type('title', $pageTitle);
939 //to select financial type
940 $this->select('financial_type_id', "label={$financialType}");
943 $this->click('is_organization');
944 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
945 $this->type('for_organization', "On behalf $hash");
947 if ($onBehalf == 'required') {
948 $this->click('CIVICRM_QFID_2_4');
950 elseif ($onBehalf == 'optional') {
951 $this->click('CIVICRM_QFID_1_2');
955 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
956 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
958 $this->type('goal_amount', 10 * $rand);
960 // FIXME: handle Start/End Date/Time
961 if ($honoreeSection) {
962 $this->click('honor_block_is_active');
963 $this->type('honor_block_title', "Honoree Section Title $hash");
964 $this->type('honor_block_text', "Honoree Introductory Message $hash");
965 $this->click("//*[@id='s2id_soft_credit_types']/ul");
966 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
967 $this->waitForElementPresent("//*[@class='select2-result-label']");
968 $this->clickAt("//*[@class='select2-results']/li[1]");
971 // is confirm enabled? it starts out enabled, so uncheck it if false
972 if (!$isConfirmEnabled) {
973 $this->click("id=is_confirm_enabled");
977 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
979 // Get contribution page id
980 $pageId = $this->urlArg('id');
982 // fill in step 2 (Processor, Pay Later, Amounts)
983 if (!empty($processor)) {
985 while (list($processorName) = each($processor)) {
986 // select newly created processor
987 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
988 $this->assertTrue($this->isTextPresent($processorName));
989 $this->check($xpath);
993 if ($amountSection && !$memPriceSetId) {
995 $this->click('is_pay_later');
996 $this->type('pay_later_text', "Pay later label $hash");
997 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1001 $this->click('is_pledge_active');
1002 $this->click('pledge_frequency_unit[week]');
1003 $this->click('is_pledge_interval');
1004 $this->type('initial_reminder_day', 3);
1005 $this->type('max_reminders', 2);
1006 $this->type('additional_reminder_day', 1);
1008 elseif ($recurring) {
1009 $this->click('is_recur');
1010 $this->click("is_recur_interval");
1011 $this->click("is_recur_installments");
1013 if ($allowOtherAmount) {
1015 $this->click('is_allow_other_amount');
1017 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1018 //$this->type('min_amount', $rand / 2);
1019 //$this->type('max_amount', $rand * 10);
1021 if ($fixedAmount ||
!$allowOtherAmount) {
1022 $this->type('label_1', "Label $hash");
1023 $this->type('value_1', "$rand");
1025 $this->click('CIVICRM_QFID_1_4');
1028 $this->click('amount_block_is_active');
1031 $this->click('_qf_Amount_next');
1032 $this->waitForElementPresent('_qf_Amount_next-bottom');
1033 $this->waitForPageToLoad($this->getTimeoutMsec());
1034 $text = "'Amount' information has been saved.";
1035 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1037 if ($memPriceSetId ||
(($membershipTypes === TRUE) ||
(is_array($membershipTypes) && !empty($membershipTypes)))) {
1038 // go to step 3 (memberships)
1039 $this->click('link=Memberships');
1040 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1042 // fill in step 3 (Memberships)
1043 $this->click('member_is_active');
1044 $this->waitForElementPresent('displayFee');
1045 $this->type('new_title', "Title - New Membership $hash");
1046 $this->type('renewal_title', "Title - Renewals $hash");
1048 if ($memPriceSetId) {
1049 $this->click('member_price_set_id');
1050 $this->select('member_price_set_id', "value={$memPriceSetId}");
1053 if ($membershipTypes === TRUE) {
1054 $membershipTypes = array(array('id' => 2));
1057 // FIXME: handle Introductory Message - New Memberships/Renewals
1058 foreach ($membershipTypes as $mType) {
1059 $this->click("membership_type_{$mType['id']}");
1060 if (array_key_exists('default', $mType)) {
1063 if (array_key_exists('auto_renew', $mType)) {
1064 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1067 if ($membershipsRequired) {
1068 $this->click('is_required');
1070 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1071 $this->click('CIVICRM_QFID_2_4');
1072 if ($isSeparatePayment) {
1073 $this->click('is_separate_payment');
1076 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1077 $text = "'MembershipBlock' information has been saved.";
1078 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1081 // go to step 4 (thank-you and receipting)
1082 $this->click('link=Receipt');
1083 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1086 $this->type('thankyou_title', "Thank-you Page Title $hash");
1087 // FIXME: handle Thank-you Message/Page Footer
1088 $this->type('receipt_from_name', "Receipt From Name $hash");
1089 $this->type('receipt_from_email', "$hash@example.org");
1090 $this->type('receipt_text', "Receipt Message $hash");
1091 $this->type('cc_receipt', "$hash@example.net");
1092 $this->type('bcc_receipt', "$hash@example.com");
1094 $this->click('_qf_ThankYou_next');
1095 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1096 $this->waitForPageToLoad($this->getTimeoutMsec());
1097 $text = "'ThankYou' information has been saved.";
1098 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1101 // fill in step 5 (Tell a Friend)
1102 $this->click('link=Tell a Friend');
1103 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1104 $this->click('tf_is_active');
1105 $this->type('tf_title', "TaF Title $hash");
1106 $this->type('intro', "TaF Introduction $hash");
1107 $this->type('suggested_message', "TaF Suggested Message $hash");
1108 $this->type('general_link', "TaF Info Page Link $hash");
1109 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1110 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1112 //$this->click('_qf_Contribute_next');
1113 $this->click('_qf_Contribute_next-bottom');
1114 $this->waitForPageToLoad($this->getTimeoutMsec());
1115 $text = "'Friend' information has been saved.";
1116 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1119 if ($profilePreId ||
$profilePostId) {
1120 // fill in step 6 (Include Profiles)
1121 $this->click('css=li#tab_custom a');
1122 $this->waitForElementPresent('_qf_Custom_next-bottom');
1124 if ($profilePreId) {
1125 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1128 if ($profilePostId) {
1129 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1132 $this->click('_qf_Custom_next-bottom');
1133 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1135 $this->waitForPageToLoad($this->getTimeoutMsec());
1136 $text = "'Custom' information has been saved.";
1137 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1141 // fill in step 7 (Premiums)
1142 $this->click('link=Premiums');
1143 $this->waitForElementPresent('_qf_Premium_next-bottom');
1144 $this->click('premiums_active');
1145 $this->type('premiums_intro_title', "Prem Title $hash");
1146 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1147 $this->type('premiums_contact_email', "$hash@example.info");
1148 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1149 $this->click('premiums_display_min_contribution');
1150 $this->type('premiums_nothankyou_label', 'No thank-you');
1151 $this->click('_qf_Premium_next');
1152 $this->waitForElementPresent('_qf_Premium_next-bottom');
1154 $this->waitForPageToLoad($this->getTimeoutMsec());
1155 $text = "'Premium' information has been saved.";
1156 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1160 // fill in step 8 (Widget Settings)
1161 $this->click('link=Widgets');
1162 $this->waitForElementPresent('_qf_Widget_next-bottom');
1164 $this->click('is_active');
1165 $this->type('url_logo', "URL to Logo Image $hash");
1166 $this->type('button_title', "Button Title $hash");
1167 // Type About text in ckEditor (fieldname, text to type, editor)
1168 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1170 $this->click('_qf_Widget_next');
1171 $this->waitForElementPresent('_qf_Widget_next-bottom');
1173 $this->waitForPageToLoad($this->getTimeoutMsec());
1174 $text = "'Widget' information has been saved.";
1175 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1179 // fill in step 9 (Enable Personal Campaign Pages)
1180 $this->click('link=Personal Campaigns');
1181 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1182 $this->click('pcp_active');
1183 if (!$isPcpApprovalNeeded) {
1184 $this->click('is_approval_needed');
1186 $this->type('notify_email', "$hash@example.name");
1187 $this->select('supporter_profile_id', 'value=2');
1188 $this->type('tellfriend_limit', 7);
1189 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1191 $this->click('_qf_Contribute_next-bottom');
1192 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1193 $this->waitForPageToLoad($this->getTimeoutMsec());
1194 $text = "'Pcp' information has been saved.";
1195 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1202 * Function to update default strict rule.
1204 * @params string $contactType Contact type
1205 * @param string $contactType
1206 * @param array $fields Fields to be set for strict rule
1207 * @param Integer $threshold Rule's threshold value
1209 function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1210 // set default strict rule.
1212 if ($contactType == 'Organization') {
1215 elseif ($contactType == 'Household') {
1219 // Default dedupe fields for each Contact type.
1220 if (empty($fields)) {
1221 $fields = array('civicrm_email.email' => 10);
1222 if ($contactType == 'Organization') {
1224 'civicrm_contact.organization_name' => 10,
1225 'civicrm_email.email' => 10,
1228 elseif ($contactType == 'Household') {
1230 'civicrm_contact.household_name' => 10,
1231 'civicrm_email.email' => 10,
1236 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1239 foreach ($fields as $field => $weight) {
1240 $this->select("where_{$count}", "value={$field}");
1241 $this->type("length_{$count}", '');
1242 $this->type("weight_{$count}", $weight);
1247 $this->type('threshold', $threshold);
1249 $this->click('_qf_DedupeRules_next-bottom');
1250 $this->waitForPageToLoad($this->getTimeoutMsec());
1254 for ($i = $count; $i <= 4; $i++
) {
1255 $this->select("where_{$i}", 'label=- none -');
1256 $this->type("length_{$i}", '');
1257 $this->type("weight_{$i}", '');
1260 $this->type('threshold', $threshold);
1263 $this->click('_qf_DedupeRules_next-bottom');
1264 $this->waitForPageToLoad($this->getTimeoutMsec());
1268 * @param string $period_type
1269 * @param int $duration_interval
1270 * @param string $duration_unit
1271 * @param string $auto_renew
1275 function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1276 $membershipTitle = substr(sha1(rand()), 0, 7);
1277 $membershipOrg = $membershipTitle . ' memorg';
1278 $this->webtestAddOrganization($membershipOrg, TRUE);
1280 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1281 $memTypeParams = array(
1282 'membership_type' => $title,
1283 'member_of_contact' => $membershipOrg,
1284 'financial_type' => 2,
1285 'period_type' => $period_type,
1288 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1290 $this->type('name', $memTypeParams['membership_type']);
1292 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1293 // select the radio first since the element id changes after membership org search results are loaded
1294 switch ($auto_renew) {
1296 $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')]");
1300 $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')]");
1304 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1305 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')]")) {
1306 $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')]");
1311 $this->select2('member_of_contact_id',$membershipTitle);
1313 $this->type('minimum_fee', '100');
1314 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1316 $this->type('duration_interval', $duration_interval);
1317 $this->select('duration_unit', "label={$duration_unit}");
1319 $this->select('period_type', "value={$period_type}");
1321 $this->click('_qf_MembershipType_upload-bottom');
1322 $this->waitForElementPresent('link=Add Membership Type');
1323 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1325 return $memTypeParams;
1329 * @param null $groupName
1330 * @param null $parentGroupName
1332 * @return null|string
1334 function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1335 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1339 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1341 $this->type('title', $groupName);
1344 $this->type('description', 'Adding new group.');
1346 // check Access Control
1347 $this->click('group_type[1]');
1349 // check Mailing List
1350 $this->click('group_type[2]');
1352 // select Visibility as Public Pages
1353 $this->select('visibility', 'value=Public Pages');
1355 // select parent group
1356 if ($parentGroupName) {
1357 $this->select('parents', "*$parentGroupName");
1361 $this->clickLink('_qf_Edit_upload-bottom');
1363 // Is status message correct?
1364 $this->waitForText('crm-notification-container', "$groupName");
1369 * @param string $activityType
1373 function WebtestAddActivity($activityType = "Meeting") {
1374 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1375 // We're using Quick Add block on the main page for this.
1376 $firstName1 = substr(sha1(rand()), 0, 7);
1377 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1378 $firstName2 = substr(sha1(rand()), 0, 7);
1379 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1381 $this->click("css=li#tab_activity a");
1383 // waiting for the activity dropdown to show up
1384 $this->waitForElementPresent("other_activity");
1386 // Select the activity type from the activity dropdown
1387 $this->select("other_activity", "label=Meeting");
1389 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1390 $this->waitForElementPresent("s2id_target_contact_id");
1392 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__
);
1394 // Typing contact's name into the field (using typeKeys(), not type()!)...
1395 $this->select2("assignee_contact_id", $firstName1, TRUE);
1397 // ...and verifying if the page contains properly formatted display name for chosen contact.
1398 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__
);
1400 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1401 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1402 // For simple input fields we can use field id as selector
1403 $this->type("subject", $subject);
1404 $this->type("location", "Some location needs to be put in this field.");
1406 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1408 // Setting duration.
1409 $this->type("duration", "30");
1411 // Putting in details.
1412 $this->type("details", "Really brief details information.");
1414 // Making sure that status is set to Scheduled (using value, not label).
1415 $this->select("status_id", "value=1");
1417 // Setting priority.
1418 $this->select("priority_id", "value=1");
1420 // Scheduling follow-up.
1421 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1422 $this->select("followup_activity_type_id", "value=1");
1423 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1424 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1427 $this->click("_qf_Activity_upload-bottom");
1428 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1430 // Is status message correct?
1431 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1433 $this->waitForElementPresent("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1435 // click through to the Activity view screen
1436 $this->click("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1437 $this->waitForElementPresent('_qf_Activity_cancel-bottom');
1439 // parse URL to grab the activity id
1440 // pass id back to any other tests that call this class
1441 return $this->urlArg('id');
1448 function checkDoLocalDBTest() {
1449 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1450 CIVICRM_WEBTEST_LOCAL_DB
1452 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1459 * Generic function to compare expected values after an api call to retrieved
1462 * @daoName string DAO Name of object we're evaluating.
1463 * @id int Id of object
1464 * @match array Associative array of field name => expected value. Empty if asserting
1465 * that a DELETE occurred
1466 * @delete boolean True if we're checking that a DELETE action occurred.
1468 function assertDBState($daoName, $id, $match, $delete = FALSE) {
1469 if (!self
::checkDoLocalDBTest()) {
1473 return CiviDBAssert
::assertDBState($this, $daoName, $id, $match, $delete);
1476 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1479 * @param $searchValue
1480 * @param $returnColumn
1481 * @param $searchColumn
1484 * @return null|string
1486 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1487 if (!self
::checkDoLocalDBTest()) {
1491 return CiviDBAssert
::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1494 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1497 * @param $searchValue
1498 * @param $returnColumn
1499 * @param $searchColumn
1502 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1503 if (!self
::checkDoLocalDBTest()) {
1507 return CiviDBAssert
::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1510 // Request a record from the DB by id. Success if row not found.
1516 function assertDBRowNotExist($daoName, $id, $message) {
1517 if (!self
::checkDoLocalDBTest()) {
1521 return CiviDBAssert
::assertDBRowNotExist($this, $daoName, $id, $message);
1524 // Compare a single column value in a retrieved DB record to an expected value
1527 * @param $searchValue
1528 * @param $returnColumn
1529 * @param $searchColumn
1530 * @param $expectedValue
1531 * @param string $message
1533 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1534 $expectedValue, $message
1536 if (!self
::checkDoLocalDBTest()) {
1540 return CiviDBAssert
::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1541 $expectedValue, $message
1545 // Compare all values in a single retrieved DB record to an array of expected values
1548 * @param $searchParams
1549 * @param $expectedValues
1551 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1552 if (!self
::checkDoLocalDBTest()) {
1556 return CiviDBAssert
::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1560 * @param $expectedValues
1561 * @param $actualValues
1563 function assertAttributesEquals(&$expectedValues, &$actualValues) {
1564 if (!self
::checkDoLocalDBTest()) {
1568 return CiviDBAssert
::assertAttributesEquals($expectedValues, $actualValues);
1574 * @param string $message
1576 function assertType($expected, $actual, $message = '') {
1577 return $this->assertInternalType($expected, $actual, $message);
1581 * Add new Financial Account
1583 function _testAddFinancialAccount($financialAccountTitle,
1584 $financialAccountDescription = FALSE,
1585 $accountingCode = FALSE,
1587 $financialAccountType = FALSE,
1588 $taxDeductible = FALSE,
1595 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1597 $this->click("link=Add Financial Account");
1598 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1600 // Financial Account Name
1601 $this->type('name', $financialAccountTitle);
1603 // Financial Description
1604 if ($financialAccountDescription) {
1605 $this->type('description', $financialAccountDescription);
1609 if ($accountingCode) {
1610 $this->type('accounting_code', $accountingCode);
1613 // Autofill Organization
1615 $this->webtestOrganisationAutocomplete($firstName);
1618 // Financial Account Type
1619 if ($financialAccountType) {
1620 $this->select('financial_account_type_id', "label={$financialAccountType}");
1623 // Is Tax Deductible
1624 if ($taxDeductible) {
1625 $this->check('is_deductible');
1628 $this->uncheck('is_deductible');
1632 $this->check('is_active');
1635 $this->uncheck('is_active');
1639 $this->check('is_tax');
1642 $this->uncheck('is_tax');
1646 $this->type('tax_rate', $taxRate);
1651 $this->check('is_default');
1654 $this->uncheck('is_default');
1656 $this->click('_qf_FinancialAccount_next-botttom');
1660 * Edit Financial Account
1662 function _testEditFinancialAccount($editfinancialAccount,
1663 $financialAccountTitle = FALSE,
1664 $financialAccountDescription = FALSE,
1665 $accountingCode = FALSE,
1667 $financialAccountType = FALSE,
1668 $taxDeductible = FALSE,
1675 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1678 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
1679 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1681 // Change Financial Account Name
1682 if ($financialAccountTitle) {
1683 $this->type('name', $financialAccountTitle);
1686 // Financial Description
1687 if ($financialAccountDescription) {
1688 $this->type('description', $financialAccountDescription);
1692 if ($accountingCode) {
1693 $this->type('accounting_code', $accountingCode);
1696 // Autofill Edit Organization
1698 $this->webtestOrganisationAutocomplete($firstName);
1701 // Financial Account Type
1702 if ($financialAccountType) {
1703 $this->select('financial_account_type_id', "label={$financialAccountType}");
1706 // Is Tax Deductible
1707 if ($taxDeductible) {
1708 $this->check('is_deductible');
1711 $this->uncheck('is_deductible');
1716 $this->check('is_tax');
1719 $this->uncheck('is_tax');
1724 $this->type('tax_rate', $taxRate);
1729 $this->check('is_default');
1732 $this->uncheck('is_default');
1737 $this->check('is_active');
1740 $this->uncheck('is_active');
1742 $this->click('_qf_FinancialAccount_next-botttom');
1743 $this->waitForElementPresent('link=Add Financial Account');
1747 * Delete Financial Account
1749 function _testDeleteFinancialAccount($financialAccountTitle) {
1750 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1751 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1752 $this->click('_qf_FinancialAccount_next-botttom');
1753 $this->waitForElementPresent('link=Add Financial Account');
1754 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1758 * Verify data after ADD and EDIT
1760 function _assertFinancialAccount($verifyData) {
1761 foreach ($verifyData as $key => $expectedValue) {
1762 $actualValue = $this->getValue($key);
1763 if ($key == 'parent_financial_account') {
1764 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1767 $this->assertEquals($expectedValue, $actualValue);
1773 * @param $verifySelectFieldData
1775 function _assertSelectVerify($verifySelectFieldData) {
1776 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1777 $actualvalue = $this->getSelectedLabel($key);
1778 $this->assertEquals($expectedvalue, $actualvalue);
1783 * @param $financialType
1784 * @param string $option
1786 function addeditFinancialType($financialType, $option = 'new') {
1787 $this->openCiviPage("admin/financial/financialType", "reset=1");
1789 if ($option == 'Delete') {
1790 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1791 $this->waitForElementPresent("css=span.btn-slide-active");
1792 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1793 $this->waitForElementPresent("_qf_FinancialType_next");
1794 $this->click("_qf_FinancialType_next");
1795 $this->waitForElementPresent("newFinancialType");
1796 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1799 if ($option == 'new') {
1800 $this->click("link=Add Financial Type");
1803 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1805 $this->waitForElementPresent("name");
1806 $this->type('name', $financialType['name']);
1807 if ($option == 'new') {
1808 $this->type('description', $financialType['name'] . ' description');
1811 if ($financialType['is_reserved']) {
1812 $this->check('is_reserved');
1815 $this->uncheck('is_reserved');
1818 if ($financialType['is_deductible']) {
1819 $this->check('is_deductible');
1822 $this->uncheck('is_deductible');
1825 $this->click('_qf_FinancialType_next');
1826 if ($option == 'new') {
1827 $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.";
1830 $text = "The financial type '{$financialType['name']}' has been saved.";
1832 $this->waitForText('crm-notification-container', $text);
1836 * Give the specified permissions
1837 * Note: this function logs in as 'admin' (logging out if necessary)
1839 function changePermissions($permission) {
1840 $this->webtestLogin('admin');
1841 $this->open("{$this->sboxPath}admin/people/permissions");
1842 $this->waitForElementPresent('edit-submit');
1843 foreach ((array) $permission as $perm) {
1844 $this->check($perm);
1846 $this->click('edit-submit');
1847 $this->waitForPageToLoad($this->getTimeoutMsec());
1848 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
1852 * @param $profileTitle
1853 * @param $profileFields
1855 function addProfile($profileTitle, $profileFields) {
1856 $this->openCiviPage('admin/uf/group', "reset=1");
1858 $this->click('link=Add Profile');
1860 // Add membership custom data field to profile
1861 $this->waitForElementPresent('_qf_Group_cancel-bottom');
1862 $this->type('title', $profileTitle);
1863 $this->click('_qf_Group_next-bottom');
1865 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1866 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now."));
1868 foreach ($profileFields as $field) {
1869 $this->waitForElementPresent('field_name_0');
1870 // $this->waitForPageToLoad($this->getTimeoutMsec());
1871 $this->click("id=field_name_0");
1872 $this->select("id=field_name_0", "label=" . $field['type']);
1873 $this->waitForElementPresent('field_name_1');
1874 $this->click("id=field_name_1");
1875 $this->select("id=field_name_1", "label=" . $field['name']);
1876 $this->waitForElementPresent('label');
1877 $this->type("id=label", $field['label']);
1878 $this->click("id=_qf_Field_next_new-top");
1879 $this->waitForPageToLoad($this->getTimeoutMsec());
1880 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
1890 * @param $financialType
1892 function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
1893 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
1894 $this->type("name", $name);
1895 $this->type("sku", $sku);
1896 $this->click("CIVICRM_QFID_noImage_16");
1897 $this->type("min_contribution", $amount);
1898 $this->type("price", $price);
1899 $this->type("cost", $cost);
1900 if ($financialType) {
1901 $this->select("financial_type_id", "label={$financialType}");
1903 $this->click("_qf_ManagePremiums_upload-bottom");
1904 $this->waitForPageToLoad($this->getTimeoutMsec());
1909 * @param $financialAccount
1911 function addPaymentInstrument($label, $financialAccount) {
1912 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
1913 $this->type("label", $label);
1914 $this->select("financial_account_id", "value=$financialAccount");
1915 $this->click("_qf_Options_next-bottom");
1916 $this->waitForPageToLoad($this->getTimeoutMsec());
1920 * Ensure we have a default mailbox set up for CiviMail
1922 function setupDefaultMailbox() {
1923 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
1924 // Check if it hasn't already been set up
1925 if (!$this->getSelectedValue('protocol')) {
1926 $this->type('name', 'Test Domain');
1927 $this->select('protocol', "IMAP");
1928 $this->type('server', 'localhost');
1929 $this->type('domain', 'example.com');
1930 $this->click('_qf_MailSettings_next-top');
1931 $this->waitForPageToLoad($this->getTimeoutMsec());
1936 * Determine the default time-out in milliseconds.
1938 * @return string, timeout expressed in milliseconds
1940 function getTimeoutMsec() {
1941 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
1942 $timeout = ($this->settings
&& @$this->settings
->timeout
) ?
($this->settings
->timeout
* 1000) : 30000;
1943 return (string) $timeout; // don't know why, but all our old code used a string
1948 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
1951 * @param array $customSets custom sets i.e entity wise sets want to be created and checked
1952 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
1953 'triggerElement' => $triggerElement))
1954 array $triggerElement: the element which is responsible for custom group to load
1956 which uses the entity info as its selection value
1957 * @param array $pageUrl the url which on which the ajax custom group load takes place
1958 * @param $beforeTriggering code to execute before actual element triggering
1961 function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
1962 //add the custom set
1963 $return = $this->addCustomGroupField($customSets);
1965 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
1967 foreach($return as $values) {
1968 foreach ($values as $entityType => $customData) {
1969 //initiate necessary variables
1970 list($entity, $entityData) = explode('_', $entityType);
1971 $elementType = CRM_Utils_Array
::value('type', $customData['triggerElement'], 'select');
1972 $elementName = CRM_Utils_Array
::value('name', $customData['triggerElement']);
1973 if ($beforeTriggering) {
1974 call_user_func($beforeTriggering);
1976 if ($elementType == 'select') {
1977 //reset the select box, so triggering of ajax only happens
1978 //WRT input of value in this function
1979 $this->select($elementName, "index=0");
1981 if (!empty($entityData)) {
1982 if ($elementType == 'select') {
1983 $this->select($elementName, "label=regexp:{$entityData}");
1985 elseif ($elementType == 'checkbox') {
1986 $val = explode(',', $entityData);
1987 foreach($val as $v) {
1988 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
1989 $this->check($checkId);
1992 elseif ($elementType == 'select2') {
1993 $this->select2($elementName, $entityData);
1997 //checking for proper custom data which is loading through ajax
1998 $this->waitForElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]",
1999 "The on the fly custom group has not been rendered for entity : {$entity} => {$entityData}");
2000 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2001 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2007 * @param $customSets
2011 function addCustomGroupField($customSets) {
2012 foreach ($customSets as $customSet) {
2013 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2015 //fill custom group title
2016 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2017 $this->click("title");
2018 $this->type("title", $customGroupTitle);
2020 //custom group extends
2021 $this->click("extends_0");
2022 $this->select("extends_0", "value={$customSet['entity']}");
2023 if (!empty($customSet['subEntity'])) {
2024 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2028 $this->uncheck('collapse_display');
2031 $this->click('_qf_Group_next-bottom');
2032 $this->waitForElementPresent('_qf_Field_cancel-bottom');
2034 //Is custom group created?
2035 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2036 $gid = $this->urlArg('gid');
2038 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2039 $this->type('label', $fieldLabel);
2040 $this->click('_qf_Field_next-bottom');
2041 $this->waitForPageToLoad($this->getTimeoutMsec());
2042 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2045 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
2051 * function to type and select first occurance of autocomplete
2053 function select2($fieldName,$label, $multiple = FALSE, $xpath=FALSE) {
2055 $this->clickAt("//*[@id='$fieldName']/../div/ul/li[1]");
2056 $this->keyDown("//*[@id='$fieldName']/../div/ul/li[1]/input", " ");
2057 $this->type("//*[@id='$fieldName']/../div/ul/li[1]/input", $label);
2058 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li[1]/input", $label);
2059 $this->waitForElementPresent("//*[@class='select2-result-label']");
2060 $this->clickAt("//*[@class='select2-results']/li[1]/div");
2064 $this->clickAt($fieldName);
2066 $this->clickAt("//*[@id='$fieldName']/../div/a");
2067 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2068 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2069 $this->type("//*[@id='select2-drop']/div/input", $label);
2070 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
2071 $this->waitForElementPresent("//*[@class='select2-result-label']");
2072 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2077 * function to select multiple options
2079 function multiselect2($fieldid, $params) {
2080 foreach($params as $value) {
2081 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2082 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2083 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2084 $this->waitForText("xpath=//*[@id='$fieldid']/../div", $value);