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