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