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