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