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