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