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