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