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');
36 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH
)) {
37 require_once CIVICRM_SETTINGS_LOCAL_PATH
;
39 require_once CIVICRM_SETTINGS_PATH
;
42 * Base class for CiviCRM Selenium tests
44 * Common functions for unit tests
47 class CiviSeleniumTestCase
extends PHPUnit_Extensions_SeleniumTestCase
{
49 // Current logged-in user
50 protected $loggedInAs = NULL;
55 * Because we are overriding the parent class constructor, we
56 * need to show the same arguments as exist in the constructor of
57 * PHPUnit_Framework_TestCase, since
58 * PHPUnit_Framework_TestSuite::createTest() creates a
59 * ReflectionClass of the Test class and checks the constructor
60 * of that class to decide how to set up the test.
64 * @param string $dataName
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 tearDown() {
110 * Authenticate as drupal user
111 * @param $user: (str) the key 'user' or 'admin', or a literal username
112 * @param $pass: (str) if $user is a literal username and not 'user' or 'admin', supply the password
114 function webtestLogin($user = 'user', $pass = NULL) {
115 // If already logged in as correct user, do nothing
116 if ($this->loggedInAs
=== $user) {
119 // If we are logged in as a different user, log out first
120 if ($this->loggedInAs
) {
121 $this->webtestLogout();
123 $this->open("{$this->sboxPath}user");
124 // Lookup username & password if not supplied
126 if ($pass === NULL) {
127 $pass = $user == 'admin' ?
$this->settings
->adminPassword
: $this->settings
->password
;
128 $username = $user == 'admin' ?
$this->settings
->adminUsername
: $this->settings
->username
;
130 // Make sure login form is available
131 $this->waitForElementPresent('edit-submit');
132 $this->type('edit-name', $username);
133 $this->type('edit-pass', $pass);
134 $this->click('edit-submit');
135 $this->waitForPageToLoad($this->getTimeoutMsec());
136 $this->loggedInAs
= $user;
139 function webtestLogout() {
140 if ($this->loggedInAs
) {
141 $this->open($this->sboxPath
. "user/logout");
142 $this->waitForPageToLoad($this->getTimeoutMsec());
144 $this->loggedInAs
= NULL;
148 * Open an internal path beginning with 'civicrm/'
150 * @param $url (str) omit the 'civicrm/' it will be added for you
151 * @param $args (str|array) optional url arguments
152 * @param $waitFor - page element to wait for - using this is recommended to ensure the document is fully loaded
154 * Although it doesn't seem to do much now, using this function is recommended for
155 * opening all civi pages, and using the $args param is also strongly encouraged
156 * This will make it much easier to run webtests in other CMSs in the future
158 function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
159 // Construct full url with args
160 // This could be extended in future to work with other CMS style urls
162 if (is_array($args)) {
164 foreach ($args as $key => $val) {
165 $url .= $sep . $key . '=' . $val;
173 $this->open("{$this->sboxPath}civicrm/$url");
174 $this->waitForPageToLoad($this->getTimeoutMsec());
176 $this->waitForElementPresent($waitFor);
181 * Click on a link or button
182 * Wait for the page to load
183 * Wait for an element to be present
185 function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
186 $this->click($element);
187 // conditional wait for page load e.g for ajax form save
188 if ($waitForPageLoad) {
189 $this->waitForPageToLoad($this->getTimeoutMsec());
192 $this->waitForElementPresent($waitFor);
197 * Call the API on the local server
198 * (kind of defeats the point of a webtest - see CRM-11889)
200 function webtest_civicrm_api($entity, $action, $params) {
201 if (!isset($params['version'])) {
202 $params['version'] = 3;
205 $result = civicrm_api($entity, $action, $params);
206 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
211 * Call the API on the remote server
212 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
215 function rest_civicrm_api($entity, $action, $params = array()) {
219 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
223 // Naughty sidestep of civi's security checks
224 'header' => "X-Requested-With: XMLHttpRequest",
227 $ctx = stream_context_create($request);
228 $result = file_get_contents($url, FALSE, $ctx);
229 return json_decode($result, TRUE);
232 function webtestGetFirstValueForOptionGroup($option_group_name) {
233 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
234 'option_group_name' => $option_group_name,
241 function webtestGetValidCountryID() {
243 if (is_null($_country_id)) {
244 $config_backend = $this->webtestGetConfig('countryLimit');
245 $_country_id = current($config_backend);
250 function webtestGetValidEntityID($entity) {
251 // michaelmcandrew: would like to use getvalue but there is a bug
252 // for e.g. group where option.limit not working at the moment CRM-9110
253 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
254 if (!empty($result['values'])) {
255 return current(array_keys($result['values']));
260 function webtestGetConfig($field) {
261 static $_config_backend;
262 if (is_null($_config_backend)) {
263 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
264 'current_domain' => 1,
266 'return' => 'config_backend'
268 $_config_backend = unserialize($result);
270 return $_config_backend[$field];
274 * Ensures the required CiviCRM components are enabled
276 function enableComponents($components) {
277 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
278 $enabledComponents = $this->getSelectOptions("enableComponents-t");
280 foreach ((array) $components as $comp) {
281 if (!in_array($comp, $enabledComponents)) {
282 $this->addSelection("enableComponents-f", "label=$comp");
283 $this->click("//option[@value='$comp']");
289 $this->click("_qf_Component_next-bottom");
290 $this->waitForPageToLoad($this->getTimeoutMsec());
291 $this->waitForText('crm-notification-container', "Saved");
296 * Add a contact with the given first and last names and either a given email
297 * (when specified), a random email (when true) or no email (when unspecified or null).
299 * @param string $fname contact’s first name
300 * @param string $lname contact’s last name
301 * @param mixed $email contact’s email (when string) or random email (when true) or no email (when null)
303 * @return mixed either a string with the (either generated or provided) email or null (if no email)
305 function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
306 $url = $this->sboxPath
. 'civicrm/contact/add?reset=1&ct=Individual';
307 if ($contactSubtype) {
308 $url = $url . "&cst={$contactSubtype}";
311 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
312 $this->type('first_name', $fname);
313 $this->type('last_name', $lname);
314 if ($email === TRUE) {
315 $email = substr(sha1(rand()), 0, 7) . '@example.org';
318 $this->type('email_1_email', $email);
320 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
321 $this->click('_qf_Contact_upload_view-bottom');
322 $this->waitForPageToLoad($this->getTimeoutMsec());
326 function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
328 $this->openCiviPage("contact/add", "reset=1&ct=Household");
329 $this->click('household_name');
330 $this->type('household_name', $householdName);
332 if ($email === TRUE) {
333 $email = substr(sha1(rand()), 0, 7) . '@example.org';
336 $this->type('email_1_email', $email);
339 $this->click('_qf_Contact_upload_view');
340 $this->waitForPageToLoad($this->getTimeoutMsec());
344 function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
346 $url = $this->sboxPath
. 'civicrm/contact/add?reset=1&ct=Organization';
347 if ($contactSubtype) {
348 $url = $url . "&cst={$contactSubtype}";
351 $this->click('organization_name');
352 $this->type('organization_name', $organizationName);
354 if ($email === TRUE) {
355 $email = substr(sha1(rand()), 0, 7) . '@example.org';
358 $this->type('email_1_email', $email);
360 $this->click('_qf_Contact_upload_view');
361 $this->waitForPageToLoad($this->getTimeoutMsec());
367 function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
368 $this->select2($fieldName,$sortName);
369 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
374 function webtestOrganisationAutocomplete($sortName) {
375 $this->clickAt("//*[@id='contact_id']/../div/a");
376 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
377 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
378 $this->type("//*[@id='select2-drop']/div/input", $sortName);
379 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
380 $this->waitForElementPresent("//*[@class='select2-result-label']");
381 $this->clickAt("//*[@class='select2-results']/li[1]");
382 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
386 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
387 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
388 * 3. Examples of $strToTime arguments -
389 * webtestFillDate('start_date',"now")
390 * webtestFillDate('start_date',"10 September 2000")
391 * webtestFillDate('start_date',"+1 day")
392 * webtestFillDate('start_date',"+1 week")
393 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
394 * webtestFillDate('start_date',"next Thursday")
395 * webtestFillDate('start_date',"last Monday")
397 function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
398 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
400 $year = date('Y', $timeStamp);
401 // -1 ensures month number is inline with calender widget's month
402 $mon = date('n', $timeStamp) - 1;
403 $day = date('j', $timeStamp);
405 $this->click("{$dateElement}_display");
406 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
407 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
408 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
409 $this->click("link=$day");
412 // 1. set both date and time.
413 function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
414 $this->webtestFillDate($dateElement, $strToTimeArgs);
416 $timeStamp = strtotime($strToTimeArgs ?
$strToTimeArgs : '+1 month');
417 $hour = date('h', $timeStamp);
418 $min = date('i', $timeStamp);
419 $meri = date('A', $timeStamp);
421 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
425 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
427 * @param array $expected Array of key/value pairs (like Status/Registered) to be checked
428 * @param string $xpathPrefix Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath
429 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
430 * @param string $tableId Pass in the id attribute of a table to be verified if you want to only check a specific table
433 function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
436 $tableLocator = "[@id='$tableId']";
438 foreach ($expected as $label => $value) {
440 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
441 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
444 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
445 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__
);
451 * Types text into a ckEditor rich text field in a form
453 * @param string $fieldName form field name (as assigned by PHP buildForm class)
454 * @param string $text text to type into the field
455 * @param string $editor which text editor (valid values are 'CKEditor', 'TinyMCE')
459 function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor') {
460 // make sure cursor focuses on the field
461 $this->fireEvent($fieldName, 'focus');
462 if ($editor == 'CKEditor') {
463 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
464 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
466 elseif ($editor == 'TinyMCE') {
467 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
468 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
471 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
473 $this->selectFrame('relative=top');
477 * Types option label and name into a table of multiple choice options
478 * (for price set fields of type select, radio, or checkbox)
479 * TODO: extend for custom field multiple choice table input
481 * @param array $options form field name (as assigned by PHP buildForm class)
482 * @param array $validateStrings appends label and name strings to this array so they can be validated later
486 function addMultipleChoiceOptions($options, &$validateStrings) {
487 foreach ($options as $oIndex => $oValue) {
488 $validateStrings[] = $oValue['label'];
489 $validateStrings[] = $oValue['amount'];
490 if (!empty($oValue['membership_type_id'])) {
491 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
493 if (!empty($oValue['financial_type_id'])) {
494 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
496 $this->type("option_label_{$oIndex}", $oValue['label']);
497 $this->type("option_amount_{$oIndex}", $oValue['amount']);
498 $this->click('link=another choice');
504 function webtestNewDialogContact($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
505 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
506 // 4 - Individual profile
507 // 5 - Organization profile
508 // 6 - Household profile
509 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
510 $this->clickAt("xpath=//div[@id='$selectId']/a");
511 $this->click("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]");
513 $this->waitForElementPresent('_qf_Edit_next');
517 $this->type('first_name', $fname);
518 $this->type('last_name', $lname);
522 $this->type('organization_name', $fname);
526 $this->type('household_name', $fname);
530 $this->type('email-Primary', $email);
531 $this->click('_qf_Edit_next');
533 // Is new contact created?
535 $this->waitForText("xpath=//div[@id='$selectId']","$lname, $fname");
538 $this->waitForText("xpath=//div[@id='$selectId']","$fname");
543 * Generic function to check that strings are present in the page
545 * @strings array array of strings or a single string
549 function assertStringsPresent($strings) {
550 foreach ((array) $strings as $string) {
551 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
556 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
558 * @url string url to parse or retrieve current url if null
560 * @return array returns an associative array containing any of the various components
561 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
562 * http://php.net/manual/en/function.parse-url.php
565 function parseURL($url = NULL) {
567 $url = $this->getLocation();
570 $elements = parse_url($url);
571 if (!empty($elements['query'])) {
572 $elements['queryString'] = array();
573 parse_str($elements['query'], $elements['queryString']);
579 * Returns a single argument from the url query
581 function urlArg($arg, $url = NULL) {
582 $elements = $this->parseURL($url);
583 return isset($elements['queryString'][$arg]) ?
$elements['queryString'][$arg] : NULL;
587 * Define a payment processor for use by a webtest. Default is to create Dummy processor
588 * which is useful for testing online public forms (online contribution pages and event registration)
590 * @param string $processorName Name assigned to new processor
591 * @param string $processorType Name for processor type (e.g. PayPal, Dummy, etc.)
592 * @param array $processorSettings Array of fieldname => value for required settings for the processor
597 function webtestAddPaymentProcessor($processorName, $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
598 if (!$processorName) {
599 $this->fail("webTestAddPaymentProcessor requires $processorName.");
601 if ($processorType == 'Dummy') {
602 $processorSettings = array(
603 'user_name' => 'dummy',
604 'url_site' => 'http://dummy.com',
605 'test_user_name' => 'dummytest',
606 'test_url_site' => 'http://dummytest.com',
609 elseif ($processorType == 'AuthNet') {
610 // FIXME: we 'll need to make a new separate account for testing
611 $processorSettings = array(
612 'test_user_name' => '5ULu56ex',
613 'test_password' => '7ARxW575w736eF5p',
616 elseif ($processorType == 'Google_Checkout') {
617 // FIXME: we 'll need to make a new separate account for testing
618 $processorSettings = array(
619 'test_user_name' => '559999327053114',
620 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
623 elseif ($processorType == 'PayPal') {
624 $processorSettings = array(
625 'test_user_name' => '559999327053114',
626 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
627 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
630 elseif ($processorType == 'PayPal_Standard') {
631 $processorSettings = array(
632 'test_user_name' => 'V18ki@9r5Bf.org',
635 elseif (empty($processorSettings)) {
636 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
638 $pid = CRM_Core_DAO
::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
640 $this->fail("$processorType processortype not found.");
642 $this->open($this->sboxPath
. 'civicrm/admin/paymentProcessor?action=add&reset=1&pp=' . $pid);
643 $this->waitForPageToLoad($this->getTimeoutMsec());
644 $this->waitForElementPresent('name');
645 $this->type('name', $processorName);
646 $this->select('financial_account_id', "label={$financialAccount}");
648 foreach ($processorSettings AS $f => $v) {
651 $this->click('_qf_PaymentProcessor_next-bottom');
652 $this->waitForPageToLoad($this->getTimeoutMsec());
653 // Is new processor created?
654 $this->assertTrue($this->isTextPresent($processorName), 'Processor name not found in selector after adding payment processor (webTestAddPaymentProcessor).');
656 $paymentProcessorId = explode('&id=', $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href"));
657 $paymentProcessorId = explode('&', $paymentProcessorId[1]);
658 return $paymentProcessorId[0];
661 function webtestAddCreditCardDetails() {
662 $this->waitForElementPresent('credit_card_type');
663 $this->select('credit_card_type', 'label=Visa');
664 $this->type('credit_card_number', '4807731747657838');
665 $this->type('cvv2', '123');
666 $this->select('credit_card_exp_date[M]', 'label=Feb');
667 $this->select('credit_card_exp_date[Y]', 'label=2019');
670 function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
676 $middleName = 'Apple';
680 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
683 $this->type('billing_first_name', $firstName);
684 $this->type('billing_middle_name', $middleName);
685 $this->type('billing_last_name', $lastName);
687 $this->type('billing_street_address-5', '234 Lincoln Ave');
688 $this->type('billing_city-5', 'San Bernadino');
689 $this->click('billing_state_province_id-5');
690 $this->select('billing_state_province_id-5', 'label=California');
691 $this->select('billing_country_id-5', 'value=1228');
692 $this->type('billing_postal_code-5', '93245');
694 return array($firstName, $middleName, $lastName);
697 function webtestAttachFile($fieldLocator, $filePath = NULL) {
699 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
700 $fp = @fopen
($filePath, 'w');
701 fputs($fp, 'Test file created by selenium test.');
705 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
707 $this->attachFile($fieldLocator, "file://{$filePath}");
712 function webtestCreateCSV($headers, $rows, $filePath = NULL) {
714 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
717 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
719 foreach ($rows as $row) {
721 foreach ($headers as $field => $header) {
722 $temp[$field] = isset($row[$field]) ?
'"' . $row[$field] . '"' : '""';
724 $data .= implode(', ', $temp) . "\r\n";
727 $fp = @fopen
($filePath, 'w');
731 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
737 * Create new relationship type w/ user specified params or default.
739 * @param $params array of required params.
741 * @return an array of saved params values.
743 function webtestAddRelationshipType($params = array()) {
744 $this->openCiviPage("admin/reltype", "reset=1&action=add");
746 //build the params if not passed.
747 if (!is_array($params) ||
empty($params)) {
749 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
750 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
751 'contact_types_a' => 'Individual',
752 'contact_types_b' => 'Individual',
753 'description' => 'Test Relationship Type Description',
756 //make sure we have minimum required params.
757 if (!isset($params['label_a_b']) ||
empty($params['label_a_b'])) {
758 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
761 //start the form fill.
762 $this->type('label_a_b', $params['label_a_b']);
763 $this->type('label_b_a', $params['label_b_a']);
764 $this->select('contact_types_a', "value={$params['contact_type_a']}");
765 $this->select('contact_types_b', "value={$params['contact_type_b']}");
766 $this->type('description', $params['description']);
769 $this->click('_qf_RelationshipType_next-bottom');
770 $this->waitForPageToLoad($this->getTimeoutMsec());
773 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
774 "Status message didn't show up after saving!"
777 $this->openCiviPage("admin/reltype", "reset=1");
779 //validate data on selector.
781 if (isset($data['description'])) {
782 unset($data['description']);
784 $this->assertStringsPresent($data);
790 * Create new online contribution page w/ user specified params or defaults.
791 * FIXME: this function take an absurd number of params - very unwieldy :(
793 * @param User can define pageTitle, hash and rand values for later data verification
795 * @return $pageId of newly created online contribution page.
797 function webtestAddContributionPage($hash = NULL,
800 $processor = array('Dummy Processor' => 'Dummy'),
801 $amountSection = TRUE,
806 $membershipTypes = TRUE,
807 $memPriceSetId = NULL,
814 $isAddPaymentProcessor = TRUE,
815 $isPcpApprovalNeeded = FALSE,
816 $isSeparatePayment = FALSE,
817 $honoreeSection = TRUE,
818 $allowOtherAmmount = TRUE,
819 $isConfirmEnabled = TRUE,
820 $financialType = 'Donation',
822 $membershipsRequired = TRUE
825 $hash = substr(sha1(rand()), 0, 7);
828 $pageTitle = 'Donate Online ' . $hash;
832 $rand = 2 * rand(2, 50);
835 // Create a new payment processor if requested
836 if ($isAddPaymentProcessor) {
837 while (list($processorName, $processorType) = each($processor)) {
838 $this->webtestAddPaymentProcessor($processorName, $processorType);
842 // go to the New Contribution Page page
843 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
845 // fill in step 1 (Title and Settings)
846 $this->type('title', $pageTitle);
848 //to select financial type
849 $this->select('financial_type_id', "label={$financialType}");
852 $this->click('is_organization');
853 $this->select('onbehalf_profile_id', 'label=On Behalf Of Organization');
854 $this->type('for_organization', "On behalf $hash");
856 if ($onBehalf == 'required') {
857 $this->click('CIVICRM_QFID_2_4');
859 elseif ($onBehalf == 'optional') {
860 $this->click('CIVICRM_QFID_1_2');
864 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
865 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
867 $this->type('goal_amount', 10 * $rand);
869 // FIXME: handle Start/End Date/Time
870 if ($honoreeSection) {
871 $this->click('honor_block_is_active');
872 $this->type('honor_block_title', "Honoree Section Title $hash");
873 $this->type('honor_block_text', "Honoree Introductory Message $hash");
874 $this->click("//*[@id='s2id_soft_credit_types']/ul");
875 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
876 $this->waitForElementPresent("//*[@class='select2-result-label']");
877 $this->clickAt("//*[@class='select2-results']/li[1]");
880 // is confirm enabled? it starts out enabled, so uncheck it if false
881 if (!$isConfirmEnabled) {
882 $this->click("id=is_confirm_enabled");
886 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
888 // Get contribution page id
889 $pageId = $this->urlArg('id');
891 // fill in step 2 (Processor, Pay Later, Amounts)
892 if (!empty($processor)) {
894 while (list($processorName) = each($processor)) {
895 // select newly created processor
896 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
897 $this->assertTrue($this->isTextPresent($processorName));
898 $this->check($xpath);
902 if ($amountSection && !$memPriceSetId) {
904 $this->click('is_pay_later');
905 $this->type('pay_later_text', "Pay later label $hash");
906 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
910 $this->click('is_pledge_active');
911 $this->click('pledge_frequency_unit[week]');
912 $this->click('is_pledge_interval');
913 $this->type('initial_reminder_day', 3);
914 $this->type('max_reminders', 2);
915 $this->type('additional_reminder_day', 1);
917 elseif ($recurring) {
918 $this->click('is_recur');
919 $this->click("is_recur_interval");
920 $this->click("is_recur_installments");
922 if ($allowOtherAmmount) {
924 $this->click('is_allow_other_amount');
926 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
927 //$this->type('min_amount', $rand / 2);
928 //$this->type('max_amount', $rand * 10);
930 if ($fixedAmount ||
!$allowOtherAmmount) {
931 $this->type('label_1', "Label $hash");
932 $this->type('value_1', "$rand");
934 $this->click('CIVICRM_QFID_1_4');
937 $this->click('amount_block_is_active');
940 $this->click('_qf_Amount_next');
941 $this->waitForElementPresent('_qf_Amount_next-bottom');
942 $this->waitForPageToLoad($this->getTimeoutMsec());
943 $text = "'Amount' information has been saved.";
944 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
946 if ($memPriceSetId ||
(($membershipTypes === TRUE) ||
(is_array($membershipTypes) && !empty($membershipTypes)))) {
947 // go to step 3 (memberships)
948 $this->click('link=Memberships');
949 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
951 // fill in step 3 (Memberships)
952 $this->click('member_is_active');
953 $this->waitForElementPresent('displayFee');
954 $this->type('new_title', "Title - New Membership $hash");
955 $this->type('renewal_title', "Title - Renewals $hash");
957 if ($memPriceSetId) {
958 $this->click('member_price_set_id');
959 $this->select('member_price_set_id', "value={$memPriceSetId}");
962 if ($membershipTypes === TRUE) {
963 $membershipTypes = array(array('id' => 2));
966 // FIXME: handle Introductory Message - New Memberships/Renewals
967 foreach ($membershipTypes as $mType) {
968 $this->click("membership_type_{$mType['id']}");
969 if (array_key_exists('default', $mType)) {
972 if (array_key_exists('auto_renew', $mType)) {
973 $this->select("auto_renew_{$mType['id']}", "label=Give option");
976 if ($membershipsRequired) {
977 $this->click('is_required');
979 $this->waitForElementPresent('CIVICRM_QFID_2_4');
980 $this->click('CIVICRM_QFID_2_4');
981 if ($isSeparatePayment) {
982 $this->click('is_separate_payment');
985 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
986 $text = "'MembershipBlock' information has been saved.";
987 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
990 // go to step 4 (thank-you and receipting)
991 $this->click('link=Receipt');
992 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
995 $this->type('thankyou_title', "Thank-you Page Title $hash");
996 // FIXME: handle Thank-you Message/Page Footer
997 $this->type('receipt_from_name', "Receipt From Name $hash");
998 $this->type('receipt_from_email', "$hash@example.org");
999 $this->type('receipt_text', "Receipt Message $hash");
1000 $this->type('cc_receipt', "$hash@example.net");
1001 $this->type('bcc_receipt', "$hash@example.com");
1003 $this->click('_qf_ThankYou_next');
1004 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1005 $this->waitForPageToLoad($this->getTimeoutMsec());
1006 $text = "'ThankYou' information has been saved.";
1007 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1010 // fill in step 5 (Tell a Friend)
1011 $this->click('link=Tell a Friend');
1012 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1013 $this->click('tf_is_active');
1014 $this->type('tf_title', "TaF Title $hash");
1015 $this->type('intro', "TaF Introduction $hash");
1016 $this->type('suggested_message', "TaF Suggested Message $hash");
1017 $this->type('general_link', "TaF Info Page Link $hash");
1018 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1019 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1021 //$this->click('_qf_Contribute_next');
1022 $this->click('_qf_Contribute_next-bottom');
1023 $this->waitForPageToLoad($this->getTimeoutMsec());
1024 $text = "'Friend' information has been saved.";
1025 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1028 if ($profilePreId ||
$profilePostId) {
1029 // fill in step 6 (Include Profiles)
1030 $this->click('css=li#tab_custom a');
1031 $this->waitForElementPresent('_qf_Custom_next-bottom');
1033 if ($profilePreId) {
1034 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1037 if ($profilePostId) {
1038 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1041 $this->click('_qf_Custom_next-bottom');
1042 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1044 $this->waitForPageToLoad($this->getTimeoutMsec());
1045 $text = "'Custom' information has been saved.";
1046 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1050 // fill in step 7 (Premiums)
1051 $this->click('link=Premiums');
1052 $this->waitForElementPresent('_qf_Premium_next-bottom');
1053 $this->click('premiums_active');
1054 $this->type('premiums_intro_title', "Prem Title $hash");
1055 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1056 $this->type('premiums_contact_email', "$hash@example.info");
1057 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1058 $this->click('premiums_display_min_contribution');
1059 $this->type('premiums_nothankyou_label', 'No thank-you');
1060 $this->click('_qf_Premium_next');
1061 $this->waitForElementPresent('_qf_Premium_next-bottom');
1063 $this->waitForPageToLoad($this->getTimeoutMsec());
1064 $text = "'Premium' information has been saved.";
1065 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1069 // fill in step 8 (Widget Settings)
1070 $this->click('link=Widgets');
1071 $this->waitForElementPresent('_qf_Widget_next-bottom');
1073 $this->click('is_active');
1074 $this->type('url_logo', "URL to Logo Image $hash");
1075 $this->type('button_title', "Button Title $hash");
1076 // Type About text in ckEditor (fieldname, text to type, editor)
1077 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1079 $this->click('_qf_Widget_next');
1080 $this->waitForElementPresent('_qf_Widget_next-bottom');
1082 $this->waitForPageToLoad($this->getTimeoutMsec());
1083 $text = "'Widget' information has been saved.";
1084 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1088 // fill in step 9 (Enable Personal Campaign Pages)
1089 $this->click('link=Personal Campaigns');
1090 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1091 $this->click('pcp_active');
1092 if (!$isPcpApprovalNeeded) {
1093 $this->click('is_approval_needed');
1095 $this->type('notify_email', "$hash@example.name");
1096 $this->select('supporter_profile_id', 'value=2');
1097 $this->type('tellfriend_limit', 7);
1098 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1100 $this->click('_qf_Contribute_next-bottom');
1101 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1102 $this->waitForPageToLoad($this->getTimeoutMsec());
1103 $text = "'Pcp' information has been saved.";
1104 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1111 * Function to update default strict rule.
1113 * @params string $contactType Contact type
1114 * @param array $fields Fields to be set for strict rule
1115 * @param Integer $threshold Rule's threshold value
1117 function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1118 // set default strict rule.
1120 if ($contactType == 'Organization') {
1123 elseif ($contactType == 'Household') {
1127 // Default dedupe fields for each Contact type.
1128 if (empty($fields)) {
1129 $fields = array('civicrm_email.email' => 10);
1130 if ($contactType == 'Organization') {
1132 'civicrm_contact.organization_name' => 10,
1133 'civicrm_email.email' => 10,
1136 elseif ($contactType == 'Household') {
1138 'civicrm_contact.household_name' => 10,
1139 'civicrm_email.email' => 10,
1144 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1147 foreach ($fields as $field => $weight) {
1148 $this->select("where_{$count}", "value={$field}");
1149 $this->type("length_{$count}", '');
1150 $this->type("weight_{$count}", $weight);
1155 $this->type('threshold', $threshold);
1157 $this->click('_qf_DedupeRules_next-bottom');
1158 $this->waitForPageToLoad($this->getTimeoutMsec());
1162 for ($i = $count; $i <= 4; $i++
) {
1163 $this->select("where_{$i}", 'label=- none -');
1164 $this->type("length_{$i}", '');
1165 $this->type("weight_{$i}", '');
1168 $this->type('threshold', $threshold);
1171 $this->click('_qf_DedupeRules_next-bottom');
1172 $this->waitForPageToLoad($this->getTimeoutMsec());
1175 function webtestAddMembershipType($period_type = 'Rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1176 $membershipTitle = substr(sha1(rand()), 0, 7);
1177 $membershipOrg = $membershipTitle . ' memorg';
1178 $this->webtestAddOrganization($membershipOrg, TRUE);
1180 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1181 $memTypeParams = array(
1182 'membership_type' => $title,
1183 'member_of_contact' => $membershipOrg,
1184 'financial_type' => 2,
1185 'period_type' => $period_type,
1188 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1190 $this->type('name', $memTypeParams['membership_type']);
1192 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1193 // select the radio first since the element id changes after membership org search results are loaded
1194 switch ($auto_renew) {
1196 $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')]");
1200 $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')]");
1204 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1205 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')]")) {
1206 $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')]");
1211 $this->select2('member_of_contact_id',$membershipTitle);
1213 $this->type('minimum_fee', '100');
1214 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1216 $this->type('duration_interval', $duration_interval);
1217 $this->select('duration_unit', "label={$duration_unit}");
1219 $this->select('period_type', "value={$period_type}");
1221 $this->click('_qf_MembershipType_upload-bottom');
1222 $this->waitForElementPresent('link=Add Membership Type');
1223 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1225 return $memTypeParams;
1228 function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1229 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1233 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1235 $this->type('title', $groupName);
1238 $this->type('description', 'Adding new group.');
1240 // check Access Control
1241 $this->click('group_type[1]');
1243 // check Mailing List
1244 $this->click('group_type[2]');
1246 // select Visibility as Public Pages
1247 $this->select('visibility', 'value=Public Pages');
1249 // select parent group
1250 if ($parentGroupName) {
1251 $this->select('parents', "*$parentGroupName");
1255 $this->clickLink('_qf_Edit_upload-bottom');
1257 // Is status message correct?
1258 $this->waitForText('crm-notification-container', "$groupName");
1262 function WebtestAddActivity($activityType = "Meeting") {
1263 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1264 // We're using Quick Add block on the main page for this.
1265 $firstName1 = substr(sha1(rand()), 0, 7);
1266 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1267 $firstName2 = substr(sha1(rand()), 0, 7);
1268 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1270 $this->click("css=li#tab_activity a");
1272 // waiting for the activity dropdown to show up
1273 $this->waitForElementPresent("other_activity");
1275 // Select the activity type from the activity dropdown
1276 $this->select("other_activity", "label=Meeting");
1278 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1280 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__
);
1282 // Typing contact's name into the field (using typeKeys(), not type()!)...
1283 $this->click("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id");
1284 $this->type("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id", $firstName1);
1285 $this->typeKeys("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id", $firstName1);
1287 // ...waiting for drop down with results to show up...
1288 $this->waitForElementPresent("css=div.token-input-dropdown-facebook");
1289 $this->waitForElementPresent("css=li.token-input-input-token-facebook");
1291 //.need to use mouseDown on first result (which is a li element), click does not work
1292 // Note that if you are using firebug this appears at the bottom of the html source, before the closing </body> tag, not where the <li> referred to above is, which is a different <li>.
1293 $this->waitForElementPresent("css=div.token-input-dropdown-facebook li");
1294 $this->mouseDown("css=div.token-input-dropdown-facebook li");
1296 // ...again, waiting for the box with contact name to show up...
1297 $this->waitForElementPresent("css=tr.crm-activity-form-block-assignee_contact_id td ul li span.token-input-delete-token-facebook");
1299 // ...and verifying if the page contains properly formatted display name for chosen contact.
1300 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__
);
1302 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1303 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1304 // For simple input fields we can use field id as selector
1305 $this->type("subject", $subject);
1306 $this->type("location", "Some location needs to be put in this field.");
1308 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1310 // Setting duration.
1311 $this->type("duration", "30");
1313 // Putting in details.
1314 $this->type("details", "Really brief details information.");
1316 // Making sure that status is set to Scheduled (using value, not label).
1317 $this->select("status_id", "value=1");
1319 // Setting priority.
1320 $this->select("priority_id", "value=1");
1322 // Scheduling follow-up.
1323 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1324 $this->select("followup_activity_type_id", "value=1");
1325 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1326 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1329 $this->click("_qf_Activity_upload-bottom");
1330 $this->waitForPageToLoad($this->getTimeoutMsec());
1332 // Is status message correct?
1333 $this->assertTrue($this->isTextPresent("Activity '$subject' has been saved."), "Status message didn't show up after saving!");
1335 $this->waitForElementPresent("xpath=//div[@id='Activities']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1337 // click through to the Activity view screen
1338 $this->click("xpath=//div[@id='Activities']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1339 $this->waitForElementPresent('_qf_Activity_cancel-bottom');
1341 // parse URL to grab the activity id
1342 // pass id back to any other tests that call this class
1343 return $this->urlArg('id');
1347 function checkDoLocalDBTest() {
1348 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1349 CIVICRM_WEBTEST_LOCAL_DB
1351 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1358 * Generic function to compare expected values after an api call to retrieved
1361 * @daoName string DAO Name of object we're evaluating.
1362 * @id int Id of object
1363 * @match array Associative array of field name => expected value. Empty if asserting
1364 * that a DELETE occurred
1365 * @delete boolean True if we're checking that a DELETE action occurred.
1367 function assertDBState($daoName, $id, $match, $delete = FALSE) {
1368 if (!self
::checkDoLocalDBTest()) {
1372 return CiviDBAssert
::assertDBState($this, $daoName, $id, $match, $delete);
1375 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1376 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1377 if (!self
::checkDoLocalDBTest()) {
1381 return CiviDBAssert
::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1384 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1385 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1386 if (!self
::checkDoLocalDBTest()) {
1390 return CiviDBAssert
::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1393 // Request a record from the DB by id. Success if row not found.
1394 function assertDBRowNotExist($daoName, $id, $message) {
1395 if (!self
::checkDoLocalDBTest()) {
1399 return CiviDBAssert
::assertDBRowNotExist($this, $daoName, $id, $message);
1402 // Compare a single column value in a retrieved DB record to an expected value
1403 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1404 $expectedValue, $message
1406 if (!self
::checkDoLocalDBTest()) {
1410 return CiviDBAssert
::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1411 $expectedValue, $message
1415 // Compare all values in a single retrieved DB record to an array of expected values
1416 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1417 if (!self
::checkDoLocalDBTest()) {
1421 return CiviDBAssert
::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1424 function assertAttributesEquals(&$expectedValues, &$actualValues) {
1425 if (!self
::checkDoLocalDBTest()) {
1429 return CiviDBAssert
::assertAttributesEquals($expectedValues, $actualValues);
1432 function assertType($expected, $actual, $message = '') {
1433 return $this->assertInternalType($expected, $actual, $message);
1437 * Add new Financial Account
1439 function _testAddFinancialAccount($financialAccountTitle,
1440 $financialAccountDescription = FALSE,
1441 $accountingCode = FALSE,
1443 $financialAccountType = FALSE,
1444 $taxDeductible = FALSE,
1451 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1453 $this->click("link=Add Financial Account");
1454 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1456 // Financial Account Name
1457 $this->type('name', $financialAccountTitle);
1459 // Financial Description
1460 if ($financialAccountDescription) {
1461 $this->type('description', $financialAccountDescription);
1465 if ($accountingCode) {
1466 $this->type('accounting_code', $accountingCode);
1469 // Autofill Organization
1471 $this->webtestOrganisationAutocomplete($firstName);
1474 // Financial Account Type
1475 if ($financialAccountType) {
1476 $this->select('financial_account_type_id', "label={$financialAccountType}");
1479 // Is Tax Deductible
1480 if ($taxDeductible) {
1481 $this->check('is_deductible');
1484 $this->uncheck('is_deductible');
1488 $this->check('is_active');
1491 $this->uncheck('is_active');
1495 $this->check('is_tax');
1498 $this->uncheck('is_tax');
1502 $this->type('tax_rate', $taxRate);
1507 $this->check('is_default');
1510 $this->uncheck('is_default');
1512 $this->click('_qf_FinancialAccount_next-botttom');
1516 * Edit Financial Account
1518 function _testEditFinancialAccount($editfinancialAccount,
1519 $financialAccountTitle = FALSE,
1520 $financialAccountDescription = FALSE,
1521 $accountingCode = FALSE,
1523 $financialAccountType = FALSE,
1524 $taxDeductible = FALSE,
1531 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1534 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
1535 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom');
1537 // Change Financial Account Name
1538 if ($financialAccountTitle) {
1539 $this->type('name', $financialAccountTitle);
1542 // Financial Description
1543 if ($financialAccountDescription) {
1544 $this->type('description', $financialAccountDescription);
1548 if ($accountingCode) {
1549 $this->type('accounting_code', $accountingCode);
1552 // Autofill Edit Organization
1554 $this->webtestOrganisationAutocomplete($firstName);
1557 // Financial Account Type
1558 if ($financialAccountType) {
1559 $this->select('financial_account_type_id', "label={$financialAccountType}");
1562 // Is Tax Deductible
1563 if ($taxDeductible) {
1564 $this->check('is_deductible');
1567 $this->uncheck('is_deductible');
1572 $this->check('is_tax');
1575 $this->uncheck('is_tax');
1580 $this->type('tax_rate', $taxRate);
1585 $this->check('is_default');
1588 $this->uncheck('is_default');
1593 $this->check('is_active');
1596 $this->uncheck('is_active');
1598 $this->click('_qf_FinancialAccount_next-botttom');
1599 $this->waitForPageToLoad($this->getTimeoutMsec());
1603 * Delete Financial Account
1605 function _testDeleteFinancialAccount($financialAccountTitle) {
1606 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1607 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1608 $this->click('_qf_FinancialAccount_next-botttom');
1609 $this->waitForElementPresent('link=Add Financial Account');
1610 $this->assertTrue($this->isTextPresent("Selected Financial Account has been deleted."));
1614 * Verify data after ADD and EDIT
1616 function _assertFinancialAccount($verifyData) {
1617 foreach ($verifyData as $key => $expectedValue) {
1618 $actualValue = $this->getValue($key);
1619 if ($key == 'parent_financial_account') {
1620 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1623 $this->assertEquals($expectedValue, $actualValue);
1628 function _assertSelectVerify($verifySelectFieldData) {
1629 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1630 $actualvalue = $this->getSelectedLabel($key);
1631 $this->assertEquals($expectedvalue, $actualvalue);
1635 function addeditFinancialType($financialType, $option = 'new') {
1636 $this->openCiviPage("admin/financial/financialType", "reset=1");
1638 if ($option == 'Delete') {
1639 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1640 $this->waitForElementPresent("css=span.btn-slide-active");
1641 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1642 $this->waitForElementPresent("_qf_FinancialType_next");
1643 $this->click("_qf_FinancialType_next");
1644 $this->waitForPageToLoad($this->getTimeoutMsec());
1645 $this->assertTrue($this->isTextPresent('Selected financial type has been deleted.'), 'Missing text: ' . 'Selected financial type has been deleted.');
1648 if ($option == 'new') {
1649 $this->click("link=Add Financial Type");
1652 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1654 $this->waitForElementPresent("name");
1655 $this->type('name', $financialType['name']);
1656 if ($option == 'new') {
1657 $this->type('description', $financialType['name'] . ' description');
1660 if ($financialType['is_reserved']) {
1661 $this->check('is_reserved');
1664 $this->uncheck('is_reserved');
1667 if ($financialType['is_deductible']) {
1668 $this->check('is_deductible');
1671 $this->uncheck('is_deductible');
1674 $this->click('_qf_FinancialType_next');
1675 if ($option == 'new') {
1676 $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.";
1679 $text = "The financial type '{$financialType['name']}' has been saved.";
1681 $this->waitForText('crm-notification-container', $text);
1685 * Give the specified permissions
1686 * Note: this function logs in as 'admin' (logging out if necessary)
1688 function changePermissions($permission) {
1689 $this->webtestLogin('admin');
1690 $this->open("{$this->sboxPath}admin/people/permissions");
1691 $this->waitForElementPresent('edit-submit');
1692 foreach ((array) $permission as $perm) {
1693 $this->check($perm);
1695 $this->click('edit-submit');
1696 $this->waitForPageToLoad($this->getTimeoutMsec());
1697 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
1700 function addProfile($profileTitle, $profileFields) {
1701 $this->openCiviPage('admin/uf/group', "reset=1");
1703 $this->click('link=Add Profile');
1705 // Add membership custom data field to profile
1706 $this->waitForElementPresent('_qf_Group_cancel-bottom');
1707 $this->type('title', $profileTitle);
1708 $this->click('_qf_Group_next-bottom');
1710 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1711 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now."));
1713 foreach ($profileFields as $field) {
1714 $this->waitForElementPresent('field_name_0');
1715 // $this->waitForPageToLoad($this->getTimeoutMsec());
1716 $this->click("id=field_name_0");
1717 $this->select("id=field_name_0", "label=" . $field['type']);
1718 $this->waitForElementPresent('field_name_1');
1719 $this->click("id=field_name_1");
1720 $this->select("id=field_name_1", "label=" . $field['name']);
1721 $this->waitForElementPresent('label');
1722 $this->type("id=label", $field['label']);
1723 $this->click("id=_qf_Field_next_new-top");
1724 $this->waitForPageToLoad($this->getTimeoutMsec());
1725 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
1729 function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
1730 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
1731 $this->type("name", $name);
1732 $this->type("sku", $sku);
1733 $this->click("CIVICRM_QFID_noImage_16");
1734 $this->type("min_contribution", $amount);
1735 $this->type("price", $price);
1736 $this->type("cost", $cost);
1737 if ($financialType) {
1738 $this->select("financial_type_id", "label={$financialType}");
1740 $this->click("_qf_ManagePremiums_upload-bottom");
1741 $this->waitForPageToLoad($this->getTimeoutMsec());
1744 function addPaymentInstrument($label, $financialAccount) {
1745 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
1746 $this->type("label", $label);
1747 $this->select("financial_account_id", "value=$financialAccount");
1748 $this->click("_qf_Options_next-bottom");
1749 $this->waitForPageToLoad($this->getTimeoutMsec());
1753 * Ensure we have a default mailbox set up for CiviMail
1755 function setupDefaultMailbox() {
1756 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
1757 // Check if it hasn't already been set up
1758 if (!$this->getSelectedValue('protocol')) {
1759 $this->type('name', 'Test Domain');
1760 $this->select('protocol', "IMAP");
1761 $this->type('server', 'localhost');
1762 $this->type('domain', 'example.com');
1763 $this->click('_qf_MailSettings_next-top');
1764 $this->waitForPageToLoad($this->getTimeoutMsec());
1769 * Determine the default time-out in milliseconds.
1771 * @return string, timeout expressed in milliseconds
1773 function getTimeoutMsec() {
1774 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
1775 $timeout = ($this->settings
&& @$this->settings
->timeout
) ?
($this->settings
->timeout
* 1000) : 30000;
1776 return (string) $timeout; // don't know why, but all our old code used a string
1781 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
1784 * @param array $customSets custom sets i.e entity wise sets want to be created and checked
1785 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
1786 'triggerElement' => $triggerElement))
1787 array $triggerElement: the element which is responsible for custom group to load
1789 which uses the entity info as its selection value
1790 * @param array $pageUrl the url which on which the ajax custom group load takes place
1791 * @param $beforeTriggering code to execute before actual element triggering
1794 function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
1795 //add the custom set
1796 $return = $this->addCustomGroupField($customSets);
1798 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
1800 foreach($return as $values) {
1801 foreach ($values as $entityType => $customData) {
1802 //initiate necessary variables
1803 list($entity, $entityData) = explode('_', $entityType);
1804 $elementType = CRM_Utils_Array
::value('type', $customData['triggerElement'], 'select');
1805 $elementName = CRM_Utils_Array
::value('name', $customData['triggerElement']);
1806 if ($beforeTriggering) {
1807 call_user_func($beforeTriggering);
1809 if ($elementType == 'select') {
1810 //reset the select box, so triggering of ajax only happens
1811 //WRT input of value in this function
1812 $this->select($elementName, "index=0");
1814 if (!empty($entityData)) {
1815 if ($elementType == 'select') {
1816 $this->select($elementName, "label=regexp:{$entityData}");
1818 elseif ($elementType == 'checkbox') {
1819 $val = explode(',', $entityData);
1820 foreach($val as $v) {
1821 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
1822 $this->check($checkId);
1825 elseif ($elementType == 'select2') {
1826 $this->select2($elementName, $entityData);
1830 //checking for proper custom data which is loading through ajax
1831 $this->waitForElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]",
1832 "The on the fly custom group has not been rendered for entity : {$entity} => {$entityData}");
1833 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
1834 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
1839 function addCustomGroupField($customSets) {
1840 foreach ($customSets as $customSet) {
1841 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
1843 //fill custom group title
1844 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
1845 $this->click("title");
1846 $this->type("title", $customGroupTitle);
1848 //custom group extends
1849 $this->click("extends_0");
1850 $this->select("extends_0", "value={$customSet['entity']}");
1851 if (!empty($customSet['subEntity'])) {
1852 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
1856 $this->uncheck('collapse_display');
1859 $this->click('_qf_Group_next-bottom');
1860 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1862 //Is custom group created?
1863 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
1864 $gid = $this->urlArg('gid');
1866 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
1867 $this->type('label', $fieldLabel);
1868 $this->click('_qf_Field_next-bottom');
1869 $this->waitForPageToLoad($this->getTimeoutMsec());
1870 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
1873 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
1879 * function to type and select first occurance of autocomplete
1881 function select2($fieldName,$label) {
1882 $this->clickAt("//*[@id='$fieldName']/../div/a");
1883 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
1884 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
1885 $this->type("//*[@id='select2-drop']/div/input", $label);
1886 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
1887 $this->waitForElementPresent("//*[@class='select2-result-label']");
1888 $this->clickAt("//*[@class='select2-results']/li[1]");