WebTestFix
[civicrm-core.git] / tests / phpunit / CiviTest / CiviSeleniumTestCase.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
29
30 /**
31 * Include configuration
32 */
33 define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
34 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
35
36 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
37 require_once CIVICRM_SETTINGS_LOCAL_PATH;
38 }
39 require_once CIVICRM_SETTINGS_PATH;
40
41 /**
42 * Base class for CiviCRM Selenium tests
43 *
44 * Common functions for unit tests
45 * @package CiviCRM
46 */
47 class CiviSeleniumTestCase extends PHPUnit_Extensions_SeleniumTestCase {
48
49 // Current logged-in user
50 protected $loggedInAs = NULL;
51
52 /**
53 * Constructor
54 *
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.
61 *
62 * @param string $name
63 * @param array $data
64 * @param string $dataName
65 * @param array $browser
66 */
67 function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
68 parent::__construct($name, $data, $dataName, $browser);
69 $this->loggedInAs = NULL;
70
71 require_once 'CiviSeleniumSettings.php';
72 $this->settings = new CiviSeleniumSettings();
73 if (property_exists($this->settings, 'serverStartupTimeOut') && $this->settings->serverStartupTimeOut) {
74 global $CiviSeleniumTestCase_polled;
75 if (!$CiviSeleniumTestCase_polled) {
76 $CiviSeleniumTestCase_polled = TRUE;
77 CRM_Utils_Network::waitForServiceStartup(
78 $this->drivers[0]->getHost(),
79 $this->drivers[0]->getPort(),
80 $this->settings->serverStartupTimeOut
81 );
82 }
83 }
84
85 // autoload
86 require_once 'CRM/Core/ClassLoader.php';
87 CRM_Core_ClassLoader::singleton()->register();
88
89 // also initialize a connection to the db
90 // FIXME: not necessary for most tests, consider moving into functions that need this
91 $config = CRM_Core_Config::singleton();
92 }
93
94 protected function setUp() {
95 $this->setBrowser($this->settings->browser);
96 // Make sure that below strings have path separator at the end
97 $this->setBrowserUrl($this->settings->sandboxURL);
98 $this->sboxPath = $this->settings->sandboxPATH;
99 if (property_exists($this->settings, 'rcHost') && $this->settings->rcHost) {
100 $this->setHost($this->settings->rcHost);
101 }
102 if (property_exists($this->settings, 'rcPort') && $this->settings->rcPort) {
103 $this->setPort($this->settings->rcPort);
104 }
105 }
106
107 protected function tearDown() {
108 }
109
110 /**
111 * Authenticate as drupal user
112 * @param $user: (str) the key 'user' or 'admin', or a literal username
113 * @param $pass: (str) if $user is a literal username and not 'user' or 'admin', supply the password
114 */
115 function webtestLogin($user = 'user', $pass = NULL) {
116 // If already logged in as correct user, do nothing
117 if ($this->loggedInAs === $user) {
118 return;
119 }
120 // If we are logged in as a different user, log out first
121 if ($this->loggedInAs) {
122 $this->webtestLogout();
123 }
124 $this->open("{$this->sboxPath}user");
125 // Lookup username & password if not supplied
126 $username = $user;
127 if ($pass === NULL) {
128 $pass = $user == 'admin' ? $this->settings->adminPassword : $this->settings->password;
129 $username = $user == 'admin' ? $this->settings->adminUsername : $this->settings->username;
130 }
131 // Make sure login form is available
132 $this->waitForElementPresent('edit-submit');
133 $this->type('edit-name', $username);
134 $this->type('edit-pass', $pass);
135 $this->click('edit-submit');
136 $this->waitForPageToLoad($this->getTimeoutMsec());
137 $this->loggedInAs = $user;
138 }
139
140 function webtestLogout() {
141 if ($this->loggedInAs) {
142 $this->open($this->sboxPath . "user/logout");
143 $this->waitForPageToLoad($this->getTimeoutMsec());
144 }
145 $this->loggedInAs = NULL;
146 }
147
148 /**
149 * Open an internal path beginning with 'civicrm/'
150 *
151 * @param $url (str) omit the 'civicrm/' it will be added for you
152 * @param $args (str|array) optional url arguments
153 * @param $waitFor - page element to wait for - using this is recommended to ensure the document is fully loaded
154 *
155 * Although it doesn't seem to do much now, using this function is recommended for
156 * opening all civi pages, and using the $args param is also strongly encouraged
157 * This will make it much easier to run webtests in other CMSs in the future
158 */
159 function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
160 // Construct full url with args
161 // This could be extended in future to work with other CMS style urls
162 if ($args) {
163 if (is_array($args)) {
164 $sep = '?';
165 foreach ($args as $key => $val) {
166 $url .= $sep . $key . '=' . $val;
167 $sep = '&';
168 }
169 }
170 else {
171 $url .= "?$args";
172 }
173 }
174 $this->open("{$this->sboxPath}civicrm/$url");
175 $this->waitForPageToLoad($this->getTimeoutMsec());
176 if ($waitFor) {
177 $this->waitForElementPresent($waitFor);
178 }
179 }
180
181 /**
182 * Click on a link or button
183 * Wait for the page to load
184 * Wait for an element to be present
185 */
186 function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
187 $this->click($element);
188 // conditional wait for page load e.g for ajax form save
189 if ($waitForPageLoad) {
190 $this->waitForPageToLoad($this->getTimeoutMsec());
191 }
192 if ($waitFor) {
193 $this->waitForElementPresent($waitFor);
194 }
195 }
196
197 /**
198 * Call the API on the local server
199 * (kind of defeats the point of a webtest - see CRM-11889)
200 */
201 function webtest_civicrm_api($entity, $action, $params) {
202 if (!isset($params['version'])) {
203 $params['version'] = 3;
204 }
205
206 $result = civicrm_api($entity, $action, $params);
207 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
208 return $result;
209 }
210
211 /**
212 * Call the API on the remote server
213 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
214 * @see CRM-11889
215 */
216 function rest_civicrm_api($entity, $action, $params = array()) {
217 $params += array(
218 'version' => 3,
219 );
220 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
221 $request = array(
222 'http' => array(
223 'method' => 'POST',
224 // Naughty sidestep of civi's security checks
225 'header' => "X-Requested-With: XMLHttpRequest",
226 ),
227 );
228 $ctx = stream_context_create($request);
229 $result = file_get_contents($url, FALSE, $ctx);
230 return json_decode($result, TRUE);
231 }
232
233 function webtestGetFirstValueForOptionGroup($option_group_name) {
234 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
235 'option_group_name' => $option_group_name,
236 'option.limit' => 1,
237 'return' => 'value'
238 ));
239 return $result;
240 }
241
242 function webtestGetValidCountryID() {
243 static $_country_id;
244 if (is_null($_country_id)) {
245 $config_backend = $this->webtestGetConfig('countryLimit');
246 $_country_id = current($config_backend);
247 }
248 return $_country_id;
249 }
250
251 function webtestGetValidEntityID($entity) {
252 // michaelmcandrew: would like to use getvalue but there is a bug
253 // for e.g. group where option.limit not working at the moment CRM-9110
254 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
255 if (!empty($result['values'])) {
256 return current(array_keys($result['values']));
257 }
258 return NULL;
259 }
260
261 function webtestGetConfig($field) {
262 static $_config_backend;
263 if (is_null($_config_backend)) {
264 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
265 'current_domain' => 1,
266 'option.limit' => 1,
267 'return' => 'config_backend'
268 ));
269 $_config_backend = unserialize($result);
270 }
271 return $_config_backend[$field];
272 }
273
274 /**
275 * Ensures the required CiviCRM components are enabled
276 */
277 function enableComponents($components) {
278 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
279 $enabledComponents = $this->getSelectOptions("enableComponents-t");
280 $added = FALSE;
281 foreach ((array) $components as $comp) {
282 if (!in_array($comp, $enabledComponents)) {
283 $this->addSelection("enableComponents-f", "label=$comp");
284 $this->click("//option[@value='$comp']");
285 $this->click("add");
286 $added = TRUE;
287 }
288 }
289 if ($added) {
290 $this->click("_qf_Component_next-bottom");
291 $this->waitForPageToLoad($this->getTimeoutMsec());
292 $this->waitForText('crm-notification-container', "Saved");
293 }
294 }
295
296 /**
297 * Add a contact with the given first and last names and either a given email
298 * (when specified), a random email (when true) or no email (when unspecified or null).
299 *
300 * @param string $fname contact’s first name
301 * @param string $lname contact’s last name
302 * @param mixed $email contact’s email (when string) or random email (when true) or no email (when null)
303 *
304 * @param null $contactSubtype
305 *
306 * @return mixed either a string with the (either generated or provided) email or null (if no email)
307 */
308 function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
309 $url = $this->sboxPath . 'civicrm/contact/add?reset=1&ct=Individual';
310 if ($contactSubtype) {
311 $url = $url . "&cst={$contactSubtype}";
312 }
313 $this->open($url);
314 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
315 $this->type('first_name', $fname);
316 $this->type('last_name', $lname);
317 if ($email === TRUE) {
318 $email = substr(sha1(rand()), 0, 7) . '@example.org';
319 }
320 if ($email) {
321 $this->type('email_1_email', $email);
322 }
323 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
324 $this->click('_qf_Contact_upload_view-bottom');
325 $this->waitForPageToLoad($this->getTimeoutMsec());
326 return $email;
327 }
328
329 function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
330
331 $this->openCiviPage("contact/add", "reset=1&ct=Household");
332 $this->click('household_name');
333 $this->type('household_name', $householdName);
334
335 if ($email === TRUE) {
336 $email = substr(sha1(rand()), 0, 7) . '@example.org';
337 }
338 if ($email) {
339 $this->type('email_1_email', $email);
340 }
341
342 $this->click('_qf_Contact_upload_view');
343 $this->waitForPageToLoad($this->getTimeoutMsec());
344 return $email;
345 }
346
347 function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
348
349 $url = $this->sboxPath . 'civicrm/contact/add?reset=1&ct=Organization';
350 if ($contactSubtype) {
351 $url = $url . "&cst={$contactSubtype}";
352 }
353 $this->open($url);
354 $this->click('organization_name');
355 $this->type('organization_name', $organizationName);
356
357 if ($email === TRUE) {
358 $email = substr(sha1(rand()), 0, 7) . '@example.org';
359 }
360 if ($email) {
361 $this->type('email_1_email', $email);
362 }
363 $this->click('_qf_Contact_upload_view');
364 $this->waitForPageToLoad($this->getTimeoutMsec());
365 return $email;
366 }
367
368 /**
369 */
370 function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
371 $this->select2($fieldName,$sortName);
372 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
373 }
374
375 /**
376 */
377 function webtestOrganisationAutocomplete($sortName) {
378 $this->clickAt("//*[@id='contact_id']/../div/a");
379 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
380 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
381 $this->type("//*[@id='select2-drop']/div/input", $sortName);
382 $this->typeKeys("//*[@id='select2-drop']/div/input", $sortName);
383 $this->waitForElementPresent("//*[@class='select2-result-label']");
384 $this->clickAt("//*[@class='select2-results']/li[1]");
385 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
386 }
387
388 /*
389 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
390 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
391 * 3. Examples of $strToTime arguments -
392 * webtestFillDate('start_date',"now")
393 * webtestFillDate('start_date',"10 September 2000")
394 * webtestFillDate('start_date',"+1 day")
395 * webtestFillDate('start_date',"+1 week")
396 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
397 * webtestFillDate('start_date',"next Thursday")
398 * webtestFillDate('start_date',"last Monday")
399 */
400 function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
401 $timeStamp = strtotime($strToTimeArgs ? $strToTimeArgs : '+1 month');
402
403 $year = date('Y', $timeStamp);
404 // -1 ensures month number is inline with calender widget's month
405 $mon = date('n', $timeStamp) - 1;
406 $day = date('j', $timeStamp);
407
408 $this->click("{$dateElement}_display");
409 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
410 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
411 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
412 $this->click("link=$day");
413 }
414
415 // 1. set both date and time.
416 function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
417 $this->webtestFillDate($dateElement, $strToTimeArgs);
418
419 $timeStamp = strtotime($strToTimeArgs ? $strToTimeArgs : '+1 month');
420 $hour = date('h', $timeStamp);
421 $min = date('i', $timeStamp);
422 $meri = date('A', $timeStamp);
423
424 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
425 }
426
427 /**
428 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
429 *
430 * @param array $expected Array of key/value pairs (like Status/Registered) to be checked
431 * @param string $xpathPrefix Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath
432 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
433 * @param string $tableId Pass in the id attribute of a table to be verified if you want to only check a specific table
434 * on the web page.
435 */
436 function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
437 $tableLocator = "";
438 if ($tableId) {
439 $tableLocator = "[@id='$tableId']";
440 }
441 foreach ($expected as $label => $value) {
442 if ($xpathPrefix) {
443 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
444 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
445 }
446 else {
447 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
448 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
449 }
450 }
451 }
452
453 /**
454 * Types text into a ckEditor rich text field in a form
455 *
456 * @param string $fieldName form field name (as assigned by PHP buildForm class)
457 * @param string $text text to type into the field
458 * @param string $editor which text editor (valid values are 'CKEditor', 'TinyMCE')
459 *
460 * @return void
461 */
462 function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor') {
463 // make sure cursor focuses on the field
464 $this->fireEvent($fieldName, 'focus');
465 if ($editor == 'CKEditor') {
466 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
467 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
468 }
469 elseif ($editor == 'TinyMCE') {
470 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
471 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
472 }
473 else {
474 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
475 }
476 $this->selectFrame('relative=top');
477 }
478
479 /**
480 * Types option label and name into a table of multiple choice options
481 * (for price set fields of type select, radio, or checkbox)
482 * TODO: extend for custom field multiple choice table input
483 *
484 * @param array $options form field name (as assigned by PHP buildForm class)
485 * @param array $validateStrings appends label and name strings to this array so they can be validated later
486 *
487 * @return void
488 */
489 function addMultipleChoiceOptions($options, &$validateStrings) {
490 foreach ($options as $oIndex => $oValue) {
491 $validateStrings[] = $oValue['label'];
492 $validateStrings[] = $oValue['amount'];
493 if (!empty($oValue['membership_type_id'])) {
494 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
495 }
496 if (!empty($oValue['financial_type_id'])) {
497 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
498 }
499 $this->type("option_label_{$oIndex}", $oValue['label']);
500 $this->type("option_amount_{$oIndex}", $oValue['amount']);
501 $this->click('link=another choice');
502 }
503 }
504
505 /**
506 */
507 function webtestNewDialogContact($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
508 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
509 // 4 - Individual profile
510 // 5 - Organization profile
511 // 6 - Household profile
512 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
513 $this->clickAt("xpath=//div[@id='$selectId']/a");
514 $this->click("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]");
515
516 $this->waitForElementPresent('_qf_Edit_next');
517
518 switch ($type) {
519 case 4:
520 $this->type('first_name', $fname);
521 $this->type('last_name', $lname);
522 break;
523
524 case 5:
525 $this->type('organization_name', $fname);
526 break;
527
528 case 6:
529 $this->type('household_name', $fname);
530 break;
531 }
532
533 $this->type('email-Primary', $email);
534 $this->click('_qf_Edit_next');
535
536 // Is new contact created?
537 if ($lname) {
538 $this->waitForText("xpath=//div[@id='$selectId']","$lname, $fname");
539 }
540 else {
541 $this->waitForText("xpath=//div[@id='$selectId']","$fname");
542 }
543 }
544
545 /**
546 * Generic function to check that strings are present in the page
547 *
548 * @strings array array of strings or a single string
549 *
550 * @param $strings
551 * @return void
552 */
553 function assertStringsPresent($strings) {
554 foreach ((array) $strings as $string) {
555 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
556 }
557 }
558
559 /**
560 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
561 *
562 * @url string url to parse or retrieve current url if null
563 *
564 * @param null $url
565 * @return array returns an associative array containing any of the various components
566 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
567 * http://php.net/manual/en/function.parse-url.php
568 */
569 function parseURL($url = NULL) {
570 if (!$url) {
571 $url = $this->getLocation();
572 }
573
574 $elements = parse_url($url);
575 if (!empty($elements['query'])) {
576 $elements['queryString'] = array();
577 parse_str($elements['query'], $elements['queryString']);
578 }
579 return $elements;
580 }
581
582 /**
583 * Returns a single argument from the url query
584 */
585 function urlArg($arg, $url = NULL) {
586 $elements = $this->parseURL($url);
587 return isset($elements['queryString'][$arg]) ? $elements['queryString'][$arg] : NULL;
588 }
589
590 /**
591 * Define a payment processor for use by a webtest. Default is to create Dummy processor
592 * which is useful for testing online public forms (online contribution pages and event registration)
593 *
594 * @param string $processorName Name assigned to new processor
595 * @param string $processorType Name for processor type (e.g. PayPal, Dummy, etc.)
596 * @param array $processorSettings Array of fieldname => value for required settings for the processor
597 *
598 * @param string $financialAccount
599 * @throws PHPUnit_Framework_AssertionFailedError
600 * @return void
601 */
602
603 function webtestAddPaymentProcessor($processorName, $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
604 if (!$processorName) {
605 $this->fail("webTestAddPaymentProcessor requires $processorName.");
606 }
607 if ($processorType == 'Dummy') {
608 $processorSettings = array(
609 'user_name' => 'dummy',
610 'url_site' => 'http://dummy.com',
611 'test_user_name' => 'dummytest',
612 'test_url_site' => 'http://dummytest.com',
613 );
614 }
615 elseif ($processorType == 'AuthNet') {
616 // FIXME: we 'll need to make a new separate account for testing
617 $processorSettings = array(
618 'test_user_name' => '5ULu56ex',
619 'test_password' => '7ARxW575w736eF5p',
620 );
621 }
622 elseif ($processorType == 'Google_Checkout') {
623 // FIXME: we 'll need to make a new separate account for testing
624 $processorSettings = array(
625 'test_user_name' => '559999327053114',
626 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
627 );
628 }
629 elseif ($processorType == 'PayPal') {
630 $processorSettings = array(
631 'test_user_name' => '559999327053114',
632 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
633 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
634 );
635 }
636 elseif ($processorType == 'PayPal_Standard') {
637 $processorSettings = array(
638 'test_user_name' => 'V18ki@9r5Bf.org',
639 );
640 }
641 elseif (empty($processorSettings)) {
642 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
643 }
644 $pid = CRM_Core_DAO::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
645 if (empty($pid)) {
646 $this->fail("$processorType processortype not found.");
647 }
648 $this->open($this->sboxPath . 'civicrm/admin/paymentProcessor?action=add&reset=1&pp=' . $pid);
649 $this->waitForPageToLoad($this->getTimeoutMsec());
650 $this->type('name', $processorName);
651 $this->select('financial_account_id', "label={$financialAccount}");
652
653 foreach ($processorSettings AS $f => $v) {
654 $this->type($f, $v);
655 }
656 $this->click('_qf_PaymentProcessor_next-bottom');
657 $this->waitForPageToLoad($this->getTimeoutMsec());
658 // Is new processor created?
659 $this->assertTrue($this->isTextPresent($processorName), 'Processor name not found in selector after adding payment processor (webTestAddPaymentProcessor).');
660
661 $paymentProcessorId = explode('&id=', $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href"));
662 $paymentProcessorId = explode('&', $paymentProcessorId[1]);
663 return $paymentProcessorId[0];
664 }
665
666 function webtestAddCreditCardDetails() {
667 $this->waitForElementPresent('credit_card_type');
668 $this->select('credit_card_type', 'label=Visa');
669 $this->type('credit_card_number', '4807731747657838');
670 $this->type('cvv2', '123');
671 $this->select('credit_card_exp_date[M]', 'label=Feb');
672 $this->select('credit_card_exp_date[Y]', 'label=2019');
673 }
674
675 function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
676 if (!$firstName) {
677 $firstName = 'John';
678 }
679
680 if (!$middleName) {
681 $middleName = 'Apple';
682 }
683
684 if (!$lastName) {
685 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
686 }
687
688 $this->type('billing_first_name', $firstName);
689 $this->type('billing_middle_name', $middleName);
690 $this->type('billing_last_name', $lastName);
691
692 $this->type('billing_street_address-5', '234 Lincoln Ave');
693 $this->type('billing_city-5', 'San Bernadino');
694 $this->select('billing_country_id-5', 'value=1228');
695 $this->click('billing_state_province_id-5');
696 $this->select('billing_state_province_id-5', 'label=California');
697 $this->type('billing_postal_code-5', '93245');
698
699 return array($firstName, $middleName, $lastName);
700 }
701
702 function webtestAttachFile($fieldLocator, $filePath = NULL) {
703 if (!$filePath) {
704 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
705 $fp = @fopen($filePath, 'w');
706 fputs($fp, 'Test file created by selenium test.');
707 @fclose($fp);
708 }
709
710 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
711
712 $this->attachFile($fieldLocator, "file://{$filePath}");
713
714 return $filePath;
715 }
716
717 function webtestCreateCSV($headers, $rows, $filePath = NULL) {
718 if (!$filePath) {
719 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
720 }
721
722 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
723
724 foreach ($rows as $row) {
725 $temp = array();
726 foreach ($headers as $field => $header) {
727 $temp[$field] = isset($row[$field]) ? '"' . $row[$field] . '"' : '""';
728 }
729 $data .= implode(', ', $temp) . "\r\n";
730 }
731
732 $fp = @fopen($filePath, 'w');
733 @fwrite($fp, $data);
734 @fclose($fp);
735
736 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
737
738 return $filePath;
739 }
740
741 /**
742 * Create new relationship type w/ user specified params or default.
743 *
744 * @param $params array of required params.
745 *
746 * @return an array of saved params values.
747 */
748 function webtestAddRelationshipType($params = array()) {
749 $this->openCiviPage("admin/reltype", "reset=1&action=add");
750
751 //build the params if not passed.
752 if (!is_array($params) || empty($params)) {
753 $params = array(
754 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
755 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
756 'contact_types_a' => 'Individual',
757 'contact_types_b' => 'Individual',
758 'description' => 'Test Relationship Type Description',
759 );
760 }
761 //make sure we have minimum required params.
762 if (!isset($params['label_a_b']) || empty($params['label_a_b'])) {
763 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
764 }
765
766 //start the form fill.
767 $this->type('label_a_b', $params['label_a_b']);
768 $this->type('label_b_a', $params['label_b_a']);
769 $this->select('contact_types_a', "value={$params['contact_type_a']}");
770 $this->select('contact_types_b', "value={$params['contact_type_b']}");
771 $this->type('description', $params['description']);
772
773 //save the data.
774 $this->click('_qf_RelationshipType_next-bottom');
775 $this->waitForPageToLoad($this->getTimeoutMsec());
776
777 //does data saved.
778 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
779 "Status message didn't show up after saving!"
780 );
781
782 $this->openCiviPage("admin/reltype", "reset=1");
783
784 //validate data on selector.
785 $data = $params;
786 if (isset($data['description'])) {
787 unset($data['description']);
788 }
789 $this->assertStringsPresent($data);
790
791 return $params;
792 }
793
794 /**
795 * Create new online contribution page w/ user specified params or defaults.
796 * FIXME: this function take an absurd number of params - very unwieldy :(
797 *
798 * @param null $hash
799 * @param null $rand
800 * @param null $pageTitle
801 * @param array $processor
802 * @param bool $amountSection
803 * @param bool $payLater
804 * @param bool $onBehalf
805 * @param bool $pledges
806 * @param bool $recurring
807 * @param bool $membershipTypes
808 * @param null $memPriceSetId
809 * @param bool $friend
810 * @param int $profilePreId
811 * @param int $profilePostId
812 * @param bool $premiums
813 * @param bool $widget
814 * @param bool $pcp
815 * @param bool $isAddPaymentProcessor
816 * @param bool $isPcpApprovalNeeded
817 * @param bool $isSeparatePayment
818 * @param bool $honoreeSection
819 * @param bool $allowOtherAmmount
820 * @param bool $isConfirmEnabled
821 * @param string $financialType
822 * @param bool $fixedAmount
823 * @param bool $membershipsRequired
824 * @internal param \can $User define pageTitle, hash and rand values for later data verification
825 *
826 * @return null $pageId of newly created online contribution page.
827 */
828 function webtestAddContributionPage($hash = NULL,
829 $rand = NULL,
830 $pageTitle = NULL,
831 $processor = array('Dummy Processor' => 'Dummy'),
832 $amountSection = TRUE,
833 $payLater = TRUE,
834 $onBehalf = TRUE,
835 $pledges = TRUE,
836 $recurring = FALSE,
837 $membershipTypes = TRUE,
838 $memPriceSetId = NULL,
839 $friend = TRUE,
840 $profilePreId = 1,
841 $profilePostId = 7,
842 $premiums = TRUE,
843 $widget = TRUE,
844 $pcp = TRUE,
845 $isAddPaymentProcessor = TRUE,
846 $isPcpApprovalNeeded = FALSE,
847 $isSeparatePayment = FALSE,
848 $honoreeSection = TRUE,
849 $allowOtherAmmount = TRUE,
850 $isConfirmEnabled = TRUE,
851 $financialType = 'Donation',
852 $fixedAmount = TRUE,
853 $membershipsRequired = TRUE
854 ) {
855 if (!$hash) {
856 $hash = substr(sha1(rand()), 0, 7);
857 }
858 if (!$pageTitle) {
859 $pageTitle = 'Donate Online ' . $hash;
860 }
861
862 if (!$rand) {
863 $rand = 2 * rand(2, 50);
864 }
865
866 // Create a new payment processor if requested
867 if ($isAddPaymentProcessor) {
868 while (list($processorName, $processorType) = each($processor)) {
869 $this->webtestAddPaymentProcessor($processorName, $processorType);
870 }
871 }
872
873 // go to the New Contribution Page page
874 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
875
876 // fill in step 1 (Title and Settings)
877 $this->type('title', $pageTitle);
878
879 //to select financial type
880 $this->select('financial_type_id', "label={$financialType}");
881
882 if ($onBehalf) {
883 $this->click('is_organization');
884 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
885 $this->type('for_organization', "On behalf $hash");
886
887 if ($onBehalf == 'required') {
888 $this->click('CIVICRM_QFID_2_4');
889 }
890 elseif ($onBehalf == 'optional') {
891 $this->click('CIVICRM_QFID_1_2');
892 }
893 }
894
895 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
896 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
897
898 $this->type('goal_amount', 10 * $rand);
899
900 // FIXME: handle Start/End Date/Time
901 if ($honoreeSection) {
902 $this->click('honor_block_is_active');
903 $this->type('honor_block_title', "Honoree Section Title $hash");
904 $this->type('honor_block_text', "Honoree Introductory Message $hash");
905 $this->click("//*[@id='s2id_soft_credit_types']/ul");
906 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
907 $this->waitForElementPresent("//*[@class='select2-result-label']");
908 $this->clickAt("//*[@class='select2-results']/li[1]");
909 }
910
911 // is confirm enabled? it starts out enabled, so uncheck it if false
912 if (!$isConfirmEnabled) {
913 $this->click("id=is_confirm_enabled");
914 }
915
916 // Submit form
917 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
918
919 // Get contribution page id
920 $pageId = $this->urlArg('id');
921
922 // fill in step 2 (Processor, Pay Later, Amounts)
923 if (!empty($processor)) {
924 reset($processor);
925 while (list($processorName) = each($processor)) {
926 // select newly created processor
927 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
928 $this->assertTrue($this->isTextPresent($processorName));
929 $this->check($xpath);
930 }
931 }
932
933 if ($amountSection && !$memPriceSetId) {
934 if ($payLater) {
935 $this->click('is_pay_later');
936 $this->type('pay_later_text', "Pay later label $hash");
937 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
938 }
939
940 if ($pledges) {
941 $this->click('is_pledge_active');
942 $this->click('pledge_frequency_unit[week]');
943 $this->click('is_pledge_interval');
944 $this->type('initial_reminder_day', 3);
945 $this->type('max_reminders', 2);
946 $this->type('additional_reminder_day', 1);
947 }
948 elseif ($recurring) {
949 $this->click('is_recur');
950 $this->click("is_recur_interval");
951 $this->click("is_recur_installments");
952 }
953 if ($allowOtherAmmount) {
954
955 $this->click('is_allow_other_amount');
956
957 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
958 //$this->type('min_amount', $rand / 2);
959 //$this->type('max_amount', $rand * 10);
960 }
961 if ($fixedAmount || !$allowOtherAmmount) {
962 $this->type('label_1', "Label $hash");
963 $this->type('value_1', "$rand");
964 }
965 $this->click('CIVICRM_QFID_1_4');
966 }
967 else {
968 $this->click('amount_block_is_active');
969 }
970
971 $this->click('_qf_Amount_next');
972 $this->waitForElementPresent('_qf_Amount_next-bottom');
973 $this->waitForPageToLoad($this->getTimeoutMsec());
974 $text = "'Amount' information has been saved.";
975 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
976
977 if ($memPriceSetId || (($membershipTypes === TRUE) || (is_array($membershipTypes) && !empty($membershipTypes)))) {
978 // go to step 3 (memberships)
979 $this->click('link=Memberships');
980 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
981
982 // fill in step 3 (Memberships)
983 $this->click('member_is_active');
984 $this->waitForElementPresent('displayFee');
985 $this->type('new_title', "Title - New Membership $hash");
986 $this->type('renewal_title', "Title - Renewals $hash");
987
988 if ($memPriceSetId) {
989 $this->click('member_price_set_id');
990 $this->select('member_price_set_id', "value={$memPriceSetId}");
991 }
992 else {
993 if ($membershipTypes === TRUE) {
994 $membershipTypes = array(array('id' => 2));
995 }
996
997 // FIXME: handle Introductory Message - New Memberships/Renewals
998 foreach ($membershipTypes as $mType) {
999 $this->click("membership_type_{$mType['id']}");
1000 if (array_key_exists('default', $mType)) {
1001 // FIXME:
1002 }
1003 if (array_key_exists('auto_renew', $mType)) {
1004 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1005 }
1006 }
1007 if ($membershipsRequired) {
1008 $this->click('is_required');
1009 }
1010 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1011 $this->click('CIVICRM_QFID_2_4');
1012 if ($isSeparatePayment) {
1013 $this->click('is_separate_payment');
1014 }
1015 }
1016 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1017 $text = "'MembershipBlock' information has been saved.";
1018 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1019 }
1020
1021 // go to step 4 (thank-you and receipting)
1022 $this->click('link=Receipt');
1023 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1024
1025 // fill in step 4
1026 $this->type('thankyou_title', "Thank-you Page Title $hash");
1027 // FIXME: handle Thank-you Message/Page Footer
1028 $this->type('receipt_from_name', "Receipt From Name $hash");
1029 $this->type('receipt_from_email', "$hash@example.org");
1030 $this->type('receipt_text', "Receipt Message $hash");
1031 $this->type('cc_receipt', "$hash@example.net");
1032 $this->type('bcc_receipt', "$hash@example.com");
1033
1034 $this->click('_qf_ThankYou_next');
1035 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1036 $this->waitForPageToLoad($this->getTimeoutMsec());
1037 $text = "'ThankYou' information has been saved.";
1038 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1039
1040 if ($friend) {
1041 // fill in step 5 (Tell a Friend)
1042 $this->click('link=Tell a Friend');
1043 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1044 $this->click('tf_is_active');
1045 $this->type('tf_title', "TaF Title $hash");
1046 $this->type('intro', "TaF Introduction $hash");
1047 $this->type('suggested_message', "TaF Suggested Message $hash");
1048 $this->type('general_link', "TaF Info Page Link $hash");
1049 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1050 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1051
1052 //$this->click('_qf_Contribute_next');
1053 $this->click('_qf_Contribute_next-bottom');
1054 $this->waitForPageToLoad($this->getTimeoutMsec());
1055 $text = "'Friend' information has been saved.";
1056 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1057 }
1058
1059 if ($profilePreId || $profilePostId) {
1060 // fill in step 6 (Include Profiles)
1061 $this->click('css=li#tab_custom a');
1062 $this->waitForElementPresent('_qf_Custom_next-bottom');
1063
1064 if ($profilePreId) {
1065 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1066 }
1067
1068 if ($profilePostId) {
1069 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1070 }
1071
1072 $this->click('_qf_Custom_next-bottom');
1073 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1074
1075 $this->waitForPageToLoad($this->getTimeoutMsec());
1076 $text = "'Custom' information has been saved.";
1077 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1078 }
1079
1080 if ($premiums) {
1081 // fill in step 7 (Premiums)
1082 $this->click('link=Premiums');
1083 $this->waitForElementPresent('_qf_Premium_next-bottom');
1084 $this->click('premiums_active');
1085 $this->type('premiums_intro_title', "Prem Title $hash");
1086 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1087 $this->type('premiums_contact_email', "$hash@example.info");
1088 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1089 $this->click('premiums_display_min_contribution');
1090 $this->type('premiums_nothankyou_label', 'No thank-you');
1091 $this->click('_qf_Premium_next');
1092 $this->waitForElementPresent('_qf_Premium_next-bottom');
1093
1094 $this->waitForPageToLoad($this->getTimeoutMsec());
1095 $text = "'Premium' information has been saved.";
1096 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1097 }
1098
1099 if ($widget) {
1100 // fill in step 8 (Widget Settings)
1101 $this->click('link=Widgets');
1102 $this->waitForElementPresent('_qf_Widget_next-bottom');
1103
1104 $this->click('is_active');
1105 $this->type('url_logo', "URL to Logo Image $hash");
1106 $this->type('button_title', "Button Title $hash");
1107 // Type About text in ckEditor (fieldname, text to type, editor)
1108 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1109
1110 $this->click('_qf_Widget_next');
1111 $this->waitForElementPresent('_qf_Widget_next-bottom');
1112
1113 $this->waitForPageToLoad($this->getTimeoutMsec());
1114 $text = "'Widget' information has been saved.";
1115 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1116 }
1117
1118 if ($pcp) {
1119 // fill in step 9 (Enable Personal Campaign Pages)
1120 $this->click('link=Personal Campaigns');
1121 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1122 $this->click('pcp_active');
1123 if (!$isPcpApprovalNeeded) {
1124 $this->click('is_approval_needed');
1125 }
1126 $this->type('notify_email', "$hash@example.name");
1127 $this->select('supporter_profile_id', 'value=2');
1128 $this->type('tellfriend_limit', 7);
1129 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1130
1131 $this->click('_qf_Contribute_next-bottom');
1132 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1133 $this->waitForPageToLoad($this->getTimeoutMsec());
1134 $text = "'Pcp' information has been saved.";
1135 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1136 }
1137
1138 return $pageId;
1139 }
1140
1141 /**
1142 * Function to update default strict rule.
1143 *
1144 * @params string $contactType Contact type
1145 * @param string $contactType
1146 * @param array $fields Fields to be set for strict rule
1147 * @param Integer $threshold Rule's threshold value
1148 */
1149 function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1150 // set default strict rule.
1151 $strictRuleId = 4;
1152 if ($contactType == 'Organization') {
1153 $strictRuleId = 5;
1154 }
1155 elseif ($contactType == 'Household') {
1156 $strictRuleId = 6;
1157 }
1158
1159 // Default dedupe fields for each Contact type.
1160 if (empty($fields)) {
1161 $fields = array('civicrm_email.email' => 10);
1162 if ($contactType == 'Organization') {
1163 $fields = array(
1164 'civicrm_contact.organization_name' => 10,
1165 'civicrm_email.email' => 10,
1166 );
1167 }
1168 elseif ($contactType == 'Household') {
1169 $fields = array(
1170 'civicrm_contact.household_name' => 10,
1171 'civicrm_email.email' => 10,
1172 );
1173 }
1174 }
1175
1176 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1177
1178 $count = 0;
1179 foreach ($fields as $field => $weight) {
1180 $this->select("where_{$count}", "value={$field}");
1181 $this->type("length_{$count}", '');
1182 $this->type("weight_{$count}", $weight);
1183 $count++;
1184 }
1185
1186 if ($count > 4) {
1187 $this->type('threshold', $threshold);
1188 // click save
1189 $this->click('_qf_DedupeRules_next-bottom');
1190 $this->waitForPageToLoad($this->getTimeoutMsec());
1191 return;
1192 }
1193
1194 for ($i = $count; $i <= 4; $i++) {
1195 $this->select("where_{$i}", 'label=- none -');
1196 $this->type("length_{$i}", '');
1197 $this->type("weight_{$i}", '');
1198 }
1199
1200 $this->type('threshold', $threshold);
1201
1202 // click save
1203 $this->click('_qf_DedupeRules_next-bottom');
1204 $this->waitForPageToLoad($this->getTimeoutMsec());
1205 }
1206
1207 function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1208 $membershipTitle = substr(sha1(rand()), 0, 7);
1209 $membershipOrg = $membershipTitle . ' memorg';
1210 $this->webtestAddOrganization($membershipOrg, TRUE);
1211
1212 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1213 $memTypeParams = array(
1214 'membership_type' => $title,
1215 'member_of_contact' => $membershipOrg,
1216 'financial_type' => 2,
1217 'period_type' => $period_type,
1218 );
1219
1220 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1221
1222 $this->type('name', $memTypeParams['membership_type']);
1223
1224 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1225 // select the radio first since the element id changes after membership org search results are loaded
1226 switch ($auto_renew) {
1227 case 'optional':
1228 $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')]");
1229 break;
1230
1231 case 'required':
1232 $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')]");
1233 break;
1234
1235 default:
1236 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1237 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')]")) {
1238 $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')]");
1239 }
1240 break;
1241 }
1242
1243 $this->select2('member_of_contact_id',$membershipTitle);
1244
1245 $this->type('minimum_fee', '100');
1246 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1247
1248 $this->type('duration_interval', $duration_interval);
1249 $this->select('duration_unit', "label={$duration_unit}");
1250
1251 $this->select('period_type', "value={$period_type}");
1252
1253 $this->click('_qf_MembershipType_upload-bottom');
1254 $this->waitForElementPresent('link=Add Membership Type');
1255 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1256
1257 return $memTypeParams;
1258 }
1259
1260 function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1261 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1262
1263 // fill group name
1264 if (!$groupName) {
1265 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1266 }
1267 $this->type('title', $groupName);
1268
1269 // fill description
1270 $this->type('description', 'Adding new group.');
1271
1272 // check Access Control
1273 $this->click('group_type[1]');
1274
1275 // check Mailing List
1276 $this->click('group_type[2]');
1277
1278 // select Visibility as Public Pages
1279 $this->select('visibility', 'value=Public Pages');
1280
1281 // select parent group
1282 if ($parentGroupName) {
1283 $this->select('parents', "*$parentGroupName");
1284 }
1285
1286 // Clicking save.
1287 $this->clickLink('_qf_Edit_upload-bottom');
1288
1289 // Is status message correct?
1290 $this->waitForText('crm-notification-container', "$groupName");
1291 return $groupName;
1292 }
1293
1294 function WebtestAddActivity($activityType = "Meeting") {
1295 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1296 // We're using Quick Add block on the main page for this.
1297 $firstName1 = substr(sha1(rand()), 0, 7);
1298 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1299 $firstName2 = substr(sha1(rand()), 0, 7);
1300 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1301
1302 $this->click("css=li#tab_activity a");
1303
1304 // waiting for the activity dropdown to show up
1305 $this->waitForElementPresent("other_activity");
1306
1307 // Select the activity type from the activity dropdown
1308 $this->select("other_activity", "label=Meeting");
1309
1310 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1311 $this->waitForElementPresent("s2id_target_contact_id");
1312
1313 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__);
1314
1315 // Typing contact's name into the field (using typeKeys(), not type()!)...
1316 $this->select2("assignee_contact_id", $firstName1, TRUE);
1317
1318 // ...and verifying if the page contains properly formatted display name for chosen contact.
1319 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__);
1320
1321 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1322 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1323 // For simple input fields we can use field id as selector
1324 $this->type("subject", $subject);
1325 $this->type("location", "Some location needs to be put in this field.");
1326
1327 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1328
1329 // Setting duration.
1330 $this->type("duration", "30");
1331
1332 // Putting in details.
1333 $this->type("details", "Really brief details information.");
1334
1335 // Making sure that status is set to Scheduled (using value, not label).
1336 $this->select("status_id", "value=1");
1337
1338 // Setting priority.
1339 $this->select("priority_id", "value=1");
1340
1341 // Scheduling follow-up.
1342 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1343 $this->select("followup_activity_type_id", "value=1");
1344 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1345 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1346
1347 // Clicking save.
1348 $this->click("_qf_Activity_upload-bottom");
1349 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1350
1351 // Is status message correct?
1352 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1353
1354 $this->waitForElementPresent("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1355
1356 // click through to the Activity view screen
1357 $this->click("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1358 $this->waitForElementPresent('_qf_Activity_cancel-bottom');
1359
1360 // parse URL to grab the activity id
1361 // pass id back to any other tests that call this class
1362 return $this->urlArg('id');
1363 }
1364
1365 static
1366 function checkDoLocalDBTest() {
1367 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1368 CIVICRM_WEBTEST_LOCAL_DB
1369 ) {
1370 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1371 return TRUE;
1372 }
1373 return FALSE;
1374 }
1375
1376 /**
1377 * Generic function to compare expected values after an api call to retrieved
1378 * DB values.
1379 *
1380 * @daoName string DAO Name of object we're evaluating.
1381 * @id int Id of object
1382 * @match array Associative array of field name => expected value. Empty if asserting
1383 * that a DELETE occurred
1384 * @delete boolean True if we're checking that a DELETE action occurred.
1385 */
1386 function assertDBState($daoName, $id, $match, $delete = FALSE) {
1387 if (!self::checkDoLocalDBTest()) {
1388 return;
1389 }
1390
1391 return CiviDBAssert::assertDBState($this, $daoName, $id, $match, $delete);
1392 }
1393
1394 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1395 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1396 if (!self::checkDoLocalDBTest()) {
1397 return;
1398 }
1399
1400 return CiviDBAssert::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1401 }
1402
1403 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1404 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1405 if (!self::checkDoLocalDBTest()) {
1406 return;
1407 }
1408
1409 return CiviDBAssert::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1410 }
1411
1412 // Request a record from the DB by id. Success if row not found.
1413 function assertDBRowNotExist($daoName, $id, $message) {
1414 if (!self::checkDoLocalDBTest()) {
1415 return;
1416 }
1417
1418 return CiviDBAssert::assertDBRowNotExist($this, $daoName, $id, $message);
1419 }
1420
1421 // Compare a single column value in a retrieved DB record to an expected value
1422 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1423 $expectedValue, $message
1424 ) {
1425 if (!self::checkDoLocalDBTest()) {
1426 return;
1427 }
1428
1429 return CiviDBAssert::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1430 $expectedValue, $message
1431 );
1432 }
1433
1434 // Compare all values in a single retrieved DB record to an array of expected values
1435 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1436 if (!self::checkDoLocalDBTest()) {
1437 return;
1438 }
1439
1440 return CiviDBAssert::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1441 }
1442
1443 function assertAttributesEquals(&$expectedValues, &$actualValues) {
1444 if (!self::checkDoLocalDBTest()) {
1445 return;
1446 }
1447
1448 return CiviDBAssert::assertAttributesEquals($expectedValues, $actualValues);
1449 }
1450
1451 function assertType($expected, $actual, $message = '') {
1452 return $this->assertInternalType($expected, $actual, $message);
1453 }
1454
1455 /**
1456 * Add new Financial Account
1457 */
1458 function _testAddFinancialAccount($financialAccountTitle,
1459 $financialAccountDescription = FALSE,
1460 $accountingCode = FALSE,
1461 $firstName = FALSE,
1462 $financialAccountType = FALSE,
1463 $taxDeductible = FALSE,
1464 $isActive = FALSE,
1465 $isTax = FALSE,
1466 $taxRate = FALSE,
1467 $isDefault = FALSE
1468 ) {
1469
1470 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1471
1472 $this->click("link=Add Financial Account");
1473 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1474
1475 // Financial Account Name
1476 $this->type('name', $financialAccountTitle);
1477
1478 // Financial Description
1479 if ($financialAccountDescription) {
1480 $this->type('description', $financialAccountDescription);
1481 }
1482
1483 //Accounting Code
1484 if ($accountingCode) {
1485 $this->type('accounting_code', $accountingCode);
1486 }
1487
1488 // Autofill Organization
1489 if ($firstName) {
1490 $this->webtestOrganisationAutocomplete($firstName);
1491 }
1492
1493 // Financial Account Type
1494 if ($financialAccountType) {
1495 $this->select('financial_account_type_id', "label={$financialAccountType}");
1496 }
1497
1498 // Is Tax Deductible
1499 if ($taxDeductible) {
1500 $this->check('is_deductible');
1501 }
1502 else {
1503 $this->uncheck('is_deductible');
1504 }
1505 // Is Active
1506 if (!$isActive) {
1507 $this->check('is_active');
1508 }
1509 else {
1510 $this->uncheck('is_active');
1511 }
1512 // Is Tax
1513 if ($isTax) {
1514 $this->check('is_tax');
1515 }
1516 else {
1517 $this->uncheck('is_tax');
1518 }
1519 // Tax Rate
1520 if ($taxRate) {
1521 $this->type('tax_rate', $taxRate);
1522 }
1523
1524 // Set Default
1525 if ($isDefault) {
1526 $this->check('is_default');
1527 }
1528 else {
1529 $this->uncheck('is_default');
1530 }
1531 $this->click('_qf_FinancialAccount_next-botttom');
1532 }
1533
1534 /**
1535 * Edit Financial Account
1536 */
1537 function _testEditFinancialAccount($editfinancialAccount,
1538 $financialAccountTitle = FALSE,
1539 $financialAccountDescription = FALSE,
1540 $accountingCode = FALSE,
1541 $firstName = FALSE,
1542 $financialAccountType = FALSE,
1543 $taxDeductible = FALSE,
1544 $isActive = TRUE,
1545 $isTax = FALSE,
1546 $taxRate = FALSE,
1547 $isDefault = FALSE
1548 ) {
1549 if ($firstName) {
1550 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1551 }
1552
1553 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
1554 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1555
1556 // Change Financial Account Name
1557 if ($financialAccountTitle) {
1558 $this->type('name', $financialAccountTitle);
1559 }
1560
1561 // Financial Description
1562 if ($financialAccountDescription) {
1563 $this->type('description', $financialAccountDescription);
1564 }
1565
1566 //Accounting Code
1567 if ($accountingCode) {
1568 $this->type('accounting_code', $accountingCode);
1569 }
1570
1571 // Autofill Edit Organization
1572 if ($firstName) {
1573 $this->webtestOrganisationAutocomplete($firstName);
1574 }
1575
1576 // Financial Account Type
1577 if ($financialAccountType) {
1578 $this->select('financial_account_type_id', "label={$financialAccountType}");
1579 }
1580
1581 // Is Tax Deductible
1582 if ($taxDeductible) {
1583 $this->check('is_deductible');
1584 }
1585 else {
1586 $this->uncheck('is_deductible');
1587 }
1588
1589 // Is Tax
1590 if ($isTax) {
1591 $this->check('is_tax');
1592 }
1593 else {
1594 $this->uncheck('is_tax');
1595 }
1596
1597 // Tax Rate
1598 if ($taxRate) {
1599 $this->type('tax_rate', $taxRate);
1600 }
1601
1602 // Set Default
1603 if ($isDefault) {
1604 $this->check('is_default');
1605 }
1606 else {
1607 $this->uncheck('is_default');
1608 }
1609
1610 // Is Active
1611 if ($isActive) {
1612 $this->check('is_active');
1613 }
1614 else {
1615 $this->uncheck('is_active');
1616 }
1617 $this->click('_qf_FinancialAccount_next-botttom');
1618 $this->waitForElementPresent('link=Add Financial Account');
1619 }
1620
1621 /**
1622 * Delete Financial Account
1623 */
1624 function _testDeleteFinancialAccount($financialAccountTitle) {
1625 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1626 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1627 $this->click('_qf_FinancialAccount_next-botttom');
1628 $this->waitForElementPresent('link=Add Financial Account');
1629 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1630 }
1631
1632 /**
1633 * Verify data after ADD and EDIT
1634 */
1635 function _assertFinancialAccount($verifyData) {
1636 foreach ($verifyData as $key => $expectedValue) {
1637 $actualValue = $this->getValue($key);
1638 if ($key == 'parent_financial_account') {
1639 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1640 }
1641 else {
1642 $this->assertEquals($expectedValue, $actualValue);
1643 }
1644 }
1645 }
1646
1647 function _assertSelectVerify($verifySelectFieldData) {
1648 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1649 $actualvalue = $this->getSelectedLabel($key);
1650 $this->assertEquals($expectedvalue, $actualvalue);
1651 }
1652 }
1653
1654 function addeditFinancialType($financialType, $option = 'new') {
1655 $this->openCiviPage("admin/financial/financialType", "reset=1");
1656
1657 if ($option == 'Delete') {
1658 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1659 $this->waitForElementPresent("css=span.btn-slide-active");
1660 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1661 $this->waitForElementPresent("_qf_FinancialType_next");
1662 $this->click("_qf_FinancialType_next");
1663 $this->waitForElementPresent("newFinancialType");
1664 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1665 return;
1666 }
1667 if ($option == 'new') {
1668 $this->click("link=Add Financial Type");
1669 }
1670 else {
1671 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1672 }
1673 $this->waitForElementPresent("name");
1674 $this->type('name', $financialType['name']);
1675 if ($option == 'new') {
1676 $this->type('description', $financialType['name'] . ' description');
1677 }
1678
1679 if ($financialType['is_reserved']) {
1680 $this->check('is_reserved');
1681 }
1682 else {
1683 $this->uncheck('is_reserved');
1684 }
1685
1686 if ($financialType['is_deductible']) {
1687 $this->check('is_deductible');
1688 }
1689 else {
1690 $this->uncheck('is_deductible');
1691 }
1692
1693 $this->click('_qf_FinancialType_next');
1694 if ($option == 'new') {
1695 $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.";
1696 }
1697 else {
1698 $text = "The financial type '{$financialType['name']}' has been saved.";
1699 }
1700 $this->waitForText('crm-notification-container', $text);
1701 }
1702
1703 /**
1704 * Give the specified permissions
1705 * Note: this function logs in as 'admin' (logging out if necessary)
1706 */
1707 function changePermissions($permission) {
1708 $this->webtestLogin('admin');
1709 $this->open("{$this->sboxPath}admin/people/permissions");
1710 $this->waitForElementPresent('edit-submit');
1711 foreach ((array) $permission as $perm) {
1712 $this->check($perm);
1713 }
1714 $this->click('edit-submit');
1715 $this->waitForPageToLoad($this->getTimeoutMsec());
1716 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
1717 }
1718
1719 function addProfile($profileTitle, $profileFields) {
1720 $this->openCiviPage('admin/uf/group', "reset=1");
1721
1722 $this->click('link=Add Profile');
1723
1724 // Add membership custom data field to profile
1725 $this->waitForElementPresent('_qf_Group_cancel-bottom');
1726 $this->type('title', $profileTitle);
1727 $this->click('_qf_Group_next-bottom');
1728
1729 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1730 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now."));
1731
1732 foreach ($profileFields as $field) {
1733 $this->waitForElementPresent('field_name_0');
1734 // $this->waitForPageToLoad($this->getTimeoutMsec());
1735 $this->click("id=field_name_0");
1736 $this->select("id=field_name_0", "label=" . $field['type']);
1737 $this->waitForElementPresent('field_name_1');
1738 $this->click("id=field_name_1");
1739 $this->select("id=field_name_1", "label=" . $field['name']);
1740 $this->waitForElementPresent('label');
1741 $this->type("id=label", $field['label']);
1742 $this->click("id=_qf_Field_next_new-top");
1743 $this->waitForPageToLoad($this->getTimeoutMsec());
1744 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
1745 }
1746 }
1747
1748 function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
1749 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
1750 $this->type("name", $name);
1751 $this->type("sku", $sku);
1752 $this->click("CIVICRM_QFID_noImage_16");
1753 $this->type("min_contribution", $amount);
1754 $this->type("price", $price);
1755 $this->type("cost", $cost);
1756 if ($financialType) {
1757 $this->select("financial_type_id", "label={$financialType}");
1758 }
1759 $this->click("_qf_ManagePremiums_upload-bottom");
1760 $this->waitForPageToLoad($this->getTimeoutMsec());
1761 }
1762
1763 function addPaymentInstrument($label, $financialAccount) {
1764 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
1765 $this->type("label", $label);
1766 $this->select("financial_account_id", "value=$financialAccount");
1767 $this->click("_qf_Options_next-bottom");
1768 $this->waitForPageToLoad($this->getTimeoutMsec());
1769 }
1770
1771 /**
1772 * Ensure we have a default mailbox set up for CiviMail
1773 */
1774 function setupDefaultMailbox() {
1775 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
1776 // Check if it hasn't already been set up
1777 if (!$this->getSelectedValue('protocol')) {
1778 $this->type('name', 'Test Domain');
1779 $this->select('protocol', "IMAP");
1780 $this->type('server', 'localhost');
1781 $this->type('domain', 'example.com');
1782 $this->click('_qf_MailSettings_next-top');
1783 $this->waitForPageToLoad($this->getTimeoutMsec());
1784 }
1785 }
1786
1787 /**
1788 * Determine the default time-out in milliseconds.
1789 *
1790 * @return string, timeout expressed in milliseconds
1791 */
1792 function getTimeoutMsec() {
1793 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
1794 $timeout = ($this->settings && @$this->settings->timeout) ? ($this->settings->timeout * 1000) : 30000;
1795 return (string) $timeout; // don't know why, but all our old code used a string
1796 }
1797
1798 /**
1799 * CRM-12378
1800 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
1801 *
1802 *
1803 * @param array $customSets custom sets i.e entity wise sets want to be created and checked
1804 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
1805 'triggerElement' => $triggerElement))
1806 array $triggerElement: the element which is responsible for custom group to load
1807
1808 which uses the entity info as its selection value
1809 * @param array $pageUrl the url which on which the ajax custom group load takes place
1810 * @param $beforeTriggering code to execute before actual element triggering
1811 * @return void
1812 */
1813 function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
1814 //add the custom set
1815 $return = $this->addCustomGroupField($customSets);
1816
1817 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
1818
1819 foreach($return as $values) {
1820 foreach ($values as $entityType => $customData) {
1821 //initiate necessary variables
1822 list($entity, $entityData) = explode('_', $entityType);
1823 $elementType = CRM_Utils_Array::value('type', $customData['triggerElement'], 'select');
1824 $elementName = CRM_Utils_Array::value('name', $customData['triggerElement']);
1825 if ($beforeTriggering) {
1826 call_user_func($beforeTriggering);
1827 }
1828 if ($elementType == 'select') {
1829 //reset the select box, so triggering of ajax only happens
1830 //WRT input of value in this function
1831 $this->select($elementName, "index=0");
1832 }
1833 if (!empty($entityData)) {
1834 if ($elementType == 'select') {
1835 $this->select($elementName, "label=regexp:{$entityData}");
1836 }
1837 elseif ($elementType == 'checkbox') {
1838 $val = explode(',', $entityData);
1839 foreach($val as $v) {
1840 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
1841 $this->check($checkId);
1842 }
1843 }
1844 elseif ($elementType == 'select2') {
1845 $this->select2($elementName, $entityData);
1846 }
1847 }
1848
1849 //checking for proper custom data which is loading through ajax
1850 $this->waitForElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]",
1851 "The on the fly custom group has not been rendered for entity : {$entity} => {$entityData}");
1852 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
1853 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
1854 }
1855 }
1856 }
1857
1858 function addCustomGroupField($customSets) {
1859 foreach ($customSets as $customSet) {
1860 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
1861
1862 //fill custom group title
1863 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
1864 $this->click("title");
1865 $this->type("title", $customGroupTitle);
1866
1867 //custom group extends
1868 $this->click("extends_0");
1869 $this->select("extends_0", "value={$customSet['entity']}");
1870 if (!empty($customSet['subEntity'])) {
1871 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
1872 }
1873
1874 // Don't collapse
1875 $this->uncheck('collapse_display');
1876
1877 // Save
1878 $this->click('_qf_Group_next-bottom');
1879 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1880
1881 //Is custom group created?
1882 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
1883 $gid = $this->urlArg('gid');
1884
1885 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
1886 $this->type('label', $fieldLabel);
1887 $this->click('_qf_Field_next-bottom');
1888 $this->waitForPageToLoad($this->getTimeoutMsec());
1889 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
1890
1891 $return[] = array(
1892 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
1893 }
1894 return $return;
1895 }
1896
1897 /**
1898 * function to type and select first occurance of autocomplete
1899 */
1900 function select2($fieldName,$label, $multiple = FALSE, $xpath=FALSE) {
1901 if ($multiple) {
1902 $this->clickAt("//*[@id='$fieldName']/../div/ul/li[1]");
1903 $this->keyDown("//*[@id='$fieldName']/../div/ul/li[1]/input", " ");
1904 $this->type("//*[@id='$fieldName']/../div/ul/li[1]/input", $label);
1905 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li[1]/input", $label);
1906 $this->waitForElementPresent("//*[@class='select2-result-label']");
1907 $this->clickAt("//*[@class='select2-results']/li[1]/div");
1908 }
1909 else {
1910 if ($xpath)
1911 $this->clickAt($fieldName);
1912 else
1913 $this->clickAt("//*[@id='$fieldName']/../div/a");
1914 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
1915 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
1916 $this->type("//*[@id='select2-drop']/div/input", $label);
1917 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
1918 $this->waitForElementPresent("//*[@class='select2-result-label']");
1919 $this->clickAt("//*[contains(@class,'select2-result-selectable ')]/div[contains(@class, 'select2-result-label')]");
1920 }
1921 }
1922
1923 /**
1924 * function to select multiple options
1925 */
1926 function multiselect2($fieldid, $params) {
1927 foreach($params as $value) {
1928 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
1929 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
1930 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
1931 $this->waitForText("xpath=//*[@id='$fieldid']/../div", $value);
1932 }
1933 }
1934 }