Merge pull request #4939 from colemanw/CRM-15789
[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 */
5896d037
TO
711 function webtestNewDialogContact(
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
TO
811 */
812
00be9182 813 public function webtestAddPaymentProcessor($processorName = 'Test Processor', $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
6a488035
TO
814 if (!$processorName) {
815 $this->fail("webTestAddPaymentProcessor requires $processorName.");
816 }
e8eccbf5
CW
817 // Ensure we are logged in as admin before we proceed
818 $this->webtestLogin('admin');
819
c3ad8633
CW
820 if ($processorName === 'Test Processor') {
821 // Use the default test processor, no need to create a new one
0512e9c6 822 $this->openCiviPage('admin/paymentProcessor', 'action=update&id=1&reset=1', '_qf_PaymentProcessor_cancel-bottom');
c3ad8633 823 $this->check('is_default');
39c74f87 824 $this->select('financial_account_id', "label={$financialAccount}");
c3ad8633
CW
825 $this->clickLink('_qf_PaymentProcessor_next-bottom');
826 return 1;
6a488035 827 }
e8eccbf5
CW
828
829 if ($processorType == 'Dummy') {
830 $processorSettings = array(
831 'user_name' => 'dummy',
832 'url_site' => 'http://dummy.com',
833 'test_user_name' => 'dummytest',
834 'test_url_site' => 'http://dummytest.com',
835 );
836 }
6a488035
TO
837 elseif ($processorType == 'AuthNet') {
838 // FIXME: we 'll need to make a new separate account for testing
839 $processorSettings = array(
840 'test_user_name' => '5ULu56ex',
841 'test_password' => '7ARxW575w736eF5p',
842 );
843 }
844 elseif ($processorType == 'Google_Checkout') {
845 // FIXME: we 'll need to make a new separate account for testing
846 $processorSettings = array(
847 'test_user_name' => '559999327053114',
848 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
849 );
850 }
851 elseif ($processorType == 'PayPal') {
852 $processorSettings = array(
853 'test_user_name' => '559999327053114',
854 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
855 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
856 );
857 }
858 elseif ($processorType == 'PayPal_Standard') {
859 $processorSettings = array(
860 'test_user_name' => 'V18ki@9r5Bf.org',
861 );
862 }
863 elseif (empty($processorSettings)) {
864 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
865 }
866 $pid = CRM_Core_DAO::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
867 if (empty($pid)) {
868 $this->fail("$processorType processortype not found.");
869 }
57d32317 870 $this->openCiviPage('admin/paymentProcessor', 'action=add&reset=1&pp=' . $pid, 'name');
6a488035
TO
871 $this->type('name', $processorName);
872 $this->select('financial_account_id', "label={$financialAccount}");
6c6e6187 873 foreach ($processorSettings as $f => $v) {
6a488035
TO
874 $this->type($f, $v);
875 }
14d071ba 876
57d32317
CW
877 // Save
878 $this->clickLink('_qf_PaymentProcessor_next-bottom');
879
f48a56fc 880 $this->waitForTextPresent($processorName);
6a488035 881
57d32317
CW
882 // Get payment processor id
883 $paymentProcessorLink = $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href");
884 return $this->urlArg('id', $paymentProcessorLink);
6a488035 885 }
5c88df60 886
00be9182 887 public function webtestAddCreditCardDetails() {
6a488035
TO
888 $this->waitForElementPresent('credit_card_type');
889 $this->select('credit_card_type', 'label=Visa');
890 $this->type('credit_card_number', '4807731747657838');
891 $this->type('cvv2', '123');
892 $this->select('credit_card_exp_date[M]', 'label=Feb');
893 $this->select('credit_card_exp_date[Y]', 'label=2019');
894 }
895
4cbe18b8
EM
896 /**
897 * @param null $firstName
898 * @param null $middleName
899 * @param null $lastName
900 *
901 * @return array
902 */
00be9182 903 public function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
6a488035
TO
904 if (!$firstName) {
905 $firstName = 'John';
906 }
907
908 if (!$middleName) {
909 $middleName = 'Apple';
910 }
911
912 if (!$lastName) {
913 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
914 }
915
916 $this->type('billing_first_name', $firstName);
917 $this->type('billing_middle_name', $middleName);
918 $this->type('billing_last_name', $lastName);
919
920 $this->type('billing_street_address-5', '234 Lincoln Ave');
921 $this->type('billing_city-5', 'San Bernadino');
b3d40287
CW
922 $this->select2('billing_country_id-5', 'United States');
923 $this->select2('billing_state_province_id-5', 'California');
6a488035
TO
924 $this->type('billing_postal_code-5', '93245');
925
926 return array($firstName, $middleName, $lastName);
927 }
928
4cbe18b8
EM
929 /**
930 * @param $fieldLocator
931 * @param null $filePath
932 *
933 * @return null|string
934 */
00be9182 935 public function webtestAttachFile($fieldLocator, $filePath = NULL) {
6a488035
TO
936 if (!$filePath) {
937 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
938 $fp = @fopen($filePath, 'w');
939 fputs($fp, 'Test file created by selenium test.');
940 @fclose($fp);
941 }
942
943 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
944
945 $this->attachFile($fieldLocator, "file://{$filePath}");
946
947 return $filePath;
948 }
949
4cbe18b8
EM
950 /**
951 * @param $headers
952 * @param $rows
953 * @param null $filePath
954 *
955 * @return null|string
956 */
00be9182 957 public function webtestCreateCSV($headers, $rows, $filePath = NULL) {
6a488035
TO
958 if (!$filePath) {
959 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
960 }
961
962 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
963
964 foreach ($rows as $row) {
965 $temp = array();
966 foreach ($headers as $field => $header) {
967 $temp[$field] = isset($row[$field]) ? '"' . $row[$field] . '"' : '""';
968 }
969 $data .= implode(', ', $temp) . "\r\n";
970 }
971
972 $fp = @fopen($filePath, 'w');
973 @fwrite($fp, $data);
974 @fclose($fp);
975
976 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
977
978 return $filePath;
979 }
980
981 /**
982 * Create new relationship type w/ user specified params or default.
983 *
5a4f6742 984 * @param array $params
72b3a70c 985 * array of required params.
6a488035 986 *
72b3a70c
CW
987 * @return array
988 * array of saved params values.
6a488035 989 */
00be9182 990 public function webtestAddRelationshipType($params = array()) {
b45c587e 991 $this->openCiviPage("admin/reltype", "reset=1&action=add");
6a488035
TO
992
993 //build the params if not passed.
994 if (!is_array($params) || empty($params)) {
995 $params = array(
996 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
997 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
998 'contact_types_a' => 'Individual',
999 'contact_types_b' => 'Individual',
1000 'description' => 'Test Relationship Type Description',
1001 );
1002 }
1003 //make sure we have minimum required params.
1004 if (!isset($params['label_a_b']) || empty($params['label_a_b'])) {
1005 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
1006 }
1007
1008 //start the form fill.
1009 $this->type('label_a_b', $params['label_a_b']);
1010 $this->type('label_b_a', $params['label_b_a']);
1011 $this->select('contact_types_a', "value={$params['contact_type_a']}");
1012 $this->select('contact_types_b', "value={$params['contact_type_b']}");
1013 $this->type('description', $params['description']);
1014
1015 //save the data.
1016 $this->click('_qf_RelationshipType_next-bottom');
1017 $this->waitForPageToLoad($this->getTimeoutMsec());
1018
1019 //does data saved.
1020 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
1021 "Status message didn't show up after saving!"
1022 );
1023
b45c587e 1024 $this->openCiviPage("admin/reltype", "reset=1");
6a488035
TO
1025
1026 //validate data on selector.
1027 $data = $params;
1028 if (isset($data['description'])) {
1029 unset($data['description']);
1030 }
1031 $this->assertStringsPresent($data);
1032
1033 return $params;
1034 }
1035
1036 /**
1037 * Create new online contribution page w/ user specified params or defaults.
b45c587e 1038 * FIXME: this function take an absurd number of params - very unwieldy :(
6a488035 1039 *
2a6da8d7
EM
1040 * @param null $hash
1041 * @param null $rand
1042 * @param null $pageTitle
1043 * @param array $processor
1044 * @param bool $amountSection
1045 * @param bool $payLater
1046 * @param bool $onBehalf
1047 * @param bool $pledges
1048 * @param bool $recurring
1049 * @param bool $membershipTypes
100fef9d 1050 * @param int $memPriceSetId
2a6da8d7
EM
1051 * @param bool $friend
1052 * @param int $profilePreId
1053 * @param int $profilePostId
1054 * @param bool $premiums
1055 * @param bool $widget
1056 * @param bool $pcp
1057 * @param bool $isAddPaymentProcessor
1058 * @param bool $isPcpApprovalNeeded
1059 * @param bool $isSeparatePayment
1060 * @param bool $honoreeSection
91d49cae 1061 * @param bool $allowOtherAmount
2a6da8d7
EM
1062 * @param bool $isConfirmEnabled
1063 * @param string $financialType
1064 * @param bool $fixedAmount
1065 * @param bool $membershipsRequired
6a488035 1066 *
a6c01b45
CW
1067 * @return null
1068 * of newly created online contribution page.
6a488035 1069 */
5896d037
TO
1070 function webtestAddContributionPage(
1071 $hash = NULL,
1072 $rand = NULL,
1073 $pageTitle = NULL,
1074 $processor = array('Test Processor' => 'Dummy'),
1075 $amountSection = TRUE,
1076 $payLater = TRUE,
1077 $onBehalf = TRUE,
1078 $pledges = TRUE,
1079 $recurring = FALSE,
1080 $membershipTypes = TRUE,
1081 $memPriceSetId = NULL,
1082 $friend = TRUE,
1083 $profilePreId = 1,
1084 $profilePostId = 7,
1085 $premiums = TRUE,
1086 $widget = TRUE,
1087 $pcp = TRUE,
1088 $isAddPaymentProcessor = TRUE,
1089 $isPcpApprovalNeeded = FALSE,
1090 $isSeparatePayment = FALSE,
1091 $honoreeSection = TRUE,
1092 $allowOtherAmount = TRUE,
1093 $isConfirmEnabled = TRUE,
1094 $financialType = 'Donation',
1095 $fixedAmount = TRUE,
1096 $membershipsRequired = TRUE
6a488035
TO
1097 ) {
1098 if (!$hash) {
1099 $hash = substr(sha1(rand()), 0, 7);
1100 }
1101 if (!$pageTitle) {
1102 $pageTitle = 'Donate Online ' . $hash;
1103 }
1104
1105 if (!$rand) {
1106 $rand = 2 * rand(2, 50);
1107 }
1108
1109 // Create a new payment processor if requested
1110 if ($isAddPaymentProcessor) {
1111 while (list($processorName, $processorType) = each($processor)) {
1112 $this->webtestAddPaymentProcessor($processorName, $processorType);
1113 }
1114 }
1115
1116 // go to the New Contribution Page page
b45c587e 1117 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
6a488035
TO
1118
1119 // fill in step 1 (Title and Settings)
1120 $this->type('title', $pageTitle);
1121
1122 //to select financial type
1123 $this->select('financial_type_id', "label={$financialType}");
1124
1125 if ($onBehalf) {
1126 $this->click('is_organization');
d340a0e8 1127 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
6a488035
TO
1128 $this->type('for_organization', "On behalf $hash");
1129
1130 if ($onBehalf == 'required') {
1131 $this->click('CIVICRM_QFID_2_4');
1132 }
1133 elseif ($onBehalf == 'optional') {
1134 $this->click('CIVICRM_QFID_1_2');
1135 }
1136 }
1137
1138 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1139 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1140
1141 $this->type('goal_amount', 10 * $rand);
1142
1143 // FIXME: handle Start/End Date/Time
1144 if ($honoreeSection) {
1145 $this->click('honor_block_is_active');
1146 $this->type('honor_block_title', "Honoree Section Title $hash");
1147 $this->type('honor_block_text', "Honoree Introductory Message $hash");
5ddf4885 1148 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1149 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1150 $this->waitForElementPresent("//*[@class='select2-result-label']");
1151 $this->clickAt("//*[@class='select2-results']/li[1]");
6a488035
TO
1152 }
1153
1154 // is confirm enabled? it starts out enabled, so uncheck it if false
1155 if (!$isConfirmEnabled) {
1156 $this->click("id=is_confirm_enabled");
1157 }
1158
b45c587e
CW
1159 // Submit form
1160 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1161
1162 // Get contribution page id
1163 $pageId = $this->urlArg('id');
6a488035
TO
1164
1165 // fill in step 2 (Processor, Pay Later, Amounts)
1166 if (!empty($processor)) {
1167 reset($processor);
1168 while (list($processorName) = each($processor)) {
1169 // select newly created processor
1170 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1171 $this->assertTrue($this->isTextPresent($processorName));
1172 $this->check($xpath);
1173 }
1174 }
1175
1176 if ($amountSection && !$memPriceSetId) {
1177 if ($payLater) {
1178 $this->click('is_pay_later');
1179 $this->type('pay_later_text', "Pay later label $hash");
3c001b0e 1180 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
6a488035
TO
1181 }
1182
1183 if ($pledges) {
1184 $this->click('is_pledge_active');
1185 $this->click('pledge_frequency_unit[week]');
1186 $this->click('is_pledge_interval');
1187 $this->type('initial_reminder_day', 3);
1188 $this->type('max_reminders', 2);
1189 $this->type('additional_reminder_day', 1);
1190 }
1191 elseif ($recurring) {
1192 $this->click('is_recur');
1193 $this->click("is_recur_interval");
1194 $this->click("is_recur_installments");
1195 }
91d49cae 1196 if ($allowOtherAmount) {
6a488035
TO
1197
1198 $this->click('is_allow_other_amount');
1199
1200 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1201 //$this->type('min_amount', $rand / 2);
1202 //$this->type('max_amount', $rand * 10);
1203 }
91d49cae 1204 if ($fixedAmount || !$allowOtherAmount) {
1019390e
PN
1205 $this->type('label_1', "Label $hash");
1206 $this->type('value_1', "$rand");
1207 }
77f1e6b1 1208 $this->click('CIVICRM_QFID_1_4');
6a488035
TO
1209 }
1210 else {
1211 $this->click('amount_block_is_active');
1212 }
1213
1214 $this->click('_qf_Amount_next');
1215 $this->waitForElementPresent('_qf_Amount_next-bottom');
1216 $this->waitForPageToLoad($this->getTimeoutMsec());
1217 $text = "'Amount' information has been saved.";
1218 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1219
1220 if ($memPriceSetId || (($membershipTypes === TRUE) || (is_array($membershipTypes) && !empty($membershipTypes)))) {
1221 // go to step 3 (memberships)
1222 $this->click('link=Memberships');
1223 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1224
1225 // fill in step 3 (Memberships)
1226 $this->click('member_is_active');
1227 $this->waitForElementPresent('displayFee');
1228 $this->type('new_title', "Title - New Membership $hash");
1229 $this->type('renewal_title', "Title - Renewals $hash");
1230
1231 if ($memPriceSetId) {
1232 $this->click('member_price_set_id');
1233 $this->select('member_price_set_id', "value={$memPriceSetId}");
1234 }
1235 else {
1236 if ($membershipTypes === TRUE) {
1237 $membershipTypes = array(array('id' => 2));
1238 }
1239
1240 // FIXME: handle Introductory Message - New Memberships/Renewals
1241 foreach ($membershipTypes as $mType) {
1242 $this->click("membership_type_{$mType['id']}");
1243 if (array_key_exists('default', $mType)) {
1244 // FIXME:
1245 }
1246 if (array_key_exists('auto_renew', $mType)) {
1247 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1248 }
1249 }
1019390e
PN
1250 if ($membershipsRequired) {
1251 $this->click('is_required');
1252 }
6a488035
TO
1253 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1254 $this->click('CIVICRM_QFID_2_4');
1255 if ($isSeparatePayment) {
1256 $this->click('is_separate_payment');
1257 }
1258 }
225a8648 1259 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
6a488035
TO
1260 $text = "'MembershipBlock' information has been saved.";
1261 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1262 }
1263
1264 // go to step 4 (thank-you and receipting)
1265 $this->click('link=Receipt');
1266 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1267
1268 // fill in step 4
1269 $this->type('thankyou_title', "Thank-you Page Title $hash");
1270 // FIXME: handle Thank-you Message/Page Footer
1271 $this->type('receipt_from_name', "Receipt From Name $hash");
1272 $this->type('receipt_from_email', "$hash@example.org");
1273 $this->type('receipt_text', "Receipt Message $hash");
1274 $this->type('cc_receipt', "$hash@example.net");
1275 $this->type('bcc_receipt', "$hash@example.com");
1276
1277 $this->click('_qf_ThankYou_next');
1278 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1279 $this->waitForPageToLoad($this->getTimeoutMsec());
1280 $text = "'ThankYou' information has been saved.";
1281 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1282
1283 if ($friend) {
1284 // fill in step 5 (Tell a Friend)
1285 $this->click('link=Tell a Friend');
1286 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1287 $this->click('tf_is_active');
1288 $this->type('tf_title', "TaF Title $hash");
1289 $this->type('intro', "TaF Introduction $hash");
1290 $this->type('suggested_message', "TaF Suggested Message $hash");
1291 $this->type('general_link', "TaF Info Page Link $hash");
1292 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1293 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1294
1295 //$this->click('_qf_Contribute_next');
1296 $this->click('_qf_Contribute_next-bottom');
1297 $this->waitForPageToLoad($this->getTimeoutMsec());
1298 $text = "'Friend' information has been saved.";
1299 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1300 }
1301
1302 if ($profilePreId || $profilePostId) {
1303 // fill in step 6 (Include Profiles)
1304 $this->click('css=li#tab_custom a');
1305 $this->waitForElementPresent('_qf_Custom_next-bottom');
1306
1307 if ($profilePreId) {
1421174e 1308 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
6a488035
TO
1309 }
1310
1311 if ($profilePostId) {
1421174e 1312 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
6a488035
TO
1313 }
1314
1315 $this->click('_qf_Custom_next-bottom');
1316 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1317
1318 $this->waitForPageToLoad($this->getTimeoutMsec());
1319 $text = "'Custom' information has been saved.";
1320 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1321 }
1322
1323 if ($premiums) {
1324 // fill in step 7 (Premiums)
1325 $this->click('link=Premiums');
1326 $this->waitForElementPresent('_qf_Premium_next-bottom');
1327 $this->click('premiums_active');
1328 $this->type('premiums_intro_title', "Prem Title $hash");
1329 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1330 $this->type('premiums_contact_email', "$hash@example.info");
1331 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1332 $this->click('premiums_display_min_contribution');
1333 $this->type('premiums_nothankyou_label', 'No thank-you');
1334 $this->click('_qf_Premium_next');
1335 $this->waitForElementPresent('_qf_Premium_next-bottom');
1336
1337 $this->waitForPageToLoad($this->getTimeoutMsec());
1338 $text = "'Premium' information has been saved.";
1339 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1340 }
1341
6a488035
TO
1342 if ($widget) {
1343 // fill in step 8 (Widget Settings)
1344 $this->click('link=Widgets');
1345 $this->waitForElementPresent('_qf_Widget_next-bottom');
1346
1347 $this->click('is_active');
1348 $this->type('url_logo', "URL to Logo Image $hash");
1349 $this->type('button_title', "Button Title $hash");
1350 // Type About text in ckEditor (fieldname, text to type, editor)
1351 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1352
1353 $this->click('_qf_Widget_next');
1354 $this->waitForElementPresent('_qf_Widget_next-bottom');
1355
1356 $this->waitForPageToLoad($this->getTimeoutMsec());
1357 $text = "'Widget' information has been saved.";
1358 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1359 }
1360
1361 if ($pcp) {
1362 // fill in step 9 (Enable Personal Campaign Pages)
1363 $this->click('link=Personal Campaigns');
1364 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1365 $this->click('pcp_active');
1366 if (!$isPcpApprovalNeeded) {
1367 $this->click('is_approval_needed');
1368 }
1369 $this->type('notify_email', "$hash@example.name");
1370 $this->select('supporter_profile_id', 'value=2');
1371 $this->type('tellfriend_limit', 7);
1372 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1373
1374 $this->click('_qf_Contribute_next-bottom');
1375 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1376 $this->waitForPageToLoad($this->getTimeoutMsec());
1377 $text = "'Pcp' information has been saved.";
1378 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1379 }
1380
b45c587e 1381 return $pageId;
6a488035
TO
1382 }
1383
1384 /**
100fef9d 1385 * Update default strict rule.
6a488035 1386 *
2a6da8d7 1387 * @param string $contactType
e16033b4
TO
1388 * @param array $fields
1389 * Fields to be set for strict rule.
1390 * @param int $threshold
1391 * Rule's threshold value.
6a488035 1392 */
00be9182 1393 public function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
6a488035
TO
1394 // set default strict rule.
1395 $strictRuleId = 4;
1396 if ($contactType == 'Organization') {
1397 $strictRuleId = 5;
1398 }
1399 elseif ($contactType == 'Household') {
1400 $strictRuleId = 6;
1401 }
1402
1403 // Default dedupe fields for each Contact type.
1404 if (empty($fields)) {
1405 $fields = array('civicrm_email.email' => 10);
1406 if ($contactType == 'Organization') {
1407 $fields = array(
1408 'civicrm_contact.organization_name' => 10,
1409 'civicrm_email.email' => 10,
1410 );
1411 }
1412 elseif ($contactType == 'Household') {
1413 $fields = array(
1414 'civicrm_contact.household_name' => 10,
1415 'civicrm_email.email' => 10,
1416 );
1417 }
1418 }
1419
b45c587e 1420 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
6a488035
TO
1421
1422 $count = 0;
1423 foreach ($fields as $field => $weight) {
1424 $this->select("where_{$count}", "value={$field}");
1425 $this->type("length_{$count}", '');
1426 $this->type("weight_{$count}", $weight);
1427 $count++;
1428 }
1429
1430 if ($count > 4) {
1431 $this->type('threshold', $threshold);
1432 // click save
1433 $this->click('_qf_DedupeRules_next-bottom');
1434 $this->waitForPageToLoad($this->getTimeoutMsec());
1435 return;
1436 }
1437
1438 for ($i = $count; $i <= 4; $i++) {
1439 $this->select("where_{$i}", 'label=- none -');
1440 $this->type("length_{$i}", '');
1441 $this->type("weight_{$i}", '');
1442 }
1443
1444 $this->type('threshold', $threshold);
1445
1446 // click save
1447 $this->click('_qf_DedupeRules_next-bottom');
1448 $this->waitForPageToLoad($this->getTimeoutMsec());
1449 }
1450
4cbe18b8
EM
1451 /**
1452 * @param string $period_type
1453 * @param int $duration_interval
1454 * @param string $duration_unit
1455 * @param string $auto_renew
1456 *
1457 * @return array
1458 */
00be9182 1459 public function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
6a488035
TO
1460 $membershipTitle = substr(sha1(rand()), 0, 7);
1461 $membershipOrg = $membershipTitle . ' memorg';
1462 $this->webtestAddOrganization($membershipOrg, TRUE);
1463
1464 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1465 $memTypeParams = array(
1466 'membership_type' => $title,
1467 'member_of_contact' => $membershipOrg,
1468 'financial_type' => 2,
1469 'period_type' => $period_type,
1470 );
1471
42daf119 1472 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
6a488035
TO
1473
1474 $this->type('name', $memTypeParams['membership_type']);
1475
1476 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1477 // select the radio first since the element id changes after membership org search results are loaded
1478 switch ($auto_renew) {
1479 case 'optional':
1480 $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')]");
1481 break;
1482
1483 case 'required':
1484 $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')]");
1485 break;
1486
1487 default:
1488 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1489 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')]")) {
1490 $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')]");
1491 }
1492 break;
1493 }
1494
6c6e6187 1495 $this->select2('member_of_contact_id', $membershipTitle);
6a488035
TO
1496
1497 $this->type('minimum_fee', '100');
1498 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1499
1500 $this->type('duration_interval', $duration_interval);
1501 $this->select('duration_unit', "label={$duration_unit}");
1502
5ddf4885 1503 $this->select('period_type', "value={$period_type}");
6a488035
TO
1504
1505 $this->click('_qf_MembershipType_upload-bottom');
1506 $this->waitForElementPresent('link=Add Membership Type');
1507 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1508
1509 return $memTypeParams;
1510 }
1511
4cbe18b8
EM
1512 /**
1513 * @param null $groupName
1514 * @param null $parentGroupName
1515 *
1516 * @return null|string
1517 */
00be9182 1518 public function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
6a488035
TO
1519 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1520
1521 // fill group name
1522 if (!$groupName) {
1523 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1524 }
1525 $this->type('title', $groupName);
1526
1527 // fill description
1528 $this->type('description', 'Adding new group.');
1529
1530 // check Access Control
1531 $this->click('group_type[1]');
1532
1533 // check Mailing List
1534 $this->click('group_type[2]');
1535
1536 // select Visibility as Public Pages
1537 $this->select('visibility', 'value=Public Pages');
1538
1539 // select parent group
1540 if ($parentGroupName) {
1541 $this->select('parents', "*$parentGroupName");
1542 }
1543
1544 // Clicking save.
225a8648 1545 $this->clickLink('_qf_Edit_upload-bottom');
6a488035
TO
1546
1547 // Is status message correct?
6c5f7368 1548 $this->waitForText('crm-notification-container', "$groupName");
6a488035
TO
1549 return $groupName;
1550 }
1551
4cbe18b8
EM
1552 /**
1553 * @param string $activityType
1554 *
1555 * @return null
1556 */
00be9182 1557 public function WebtestAddActivity($activityType = "Meeting") {
6a488035
TO
1558 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1559 // We're using Quick Add block on the main page for this.
1560 $firstName1 = substr(sha1(rand()), 0, 7);
1561 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1562 $firstName2 = substr(sha1(rand()), 0, 7);
1563 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1564
6a488035
TO
1565 $this->click("css=li#tab_activity a");
1566
1567 // waiting for the activity dropdown to show up
1568 $this->waitForElementPresent("other_activity");
1569
1570 // Select the activity type from the activity dropdown
1571 $this->select("other_activity", "label=Meeting");
1572
1573 $this->waitForElementPresent("_qf_Activity_upload-bottom");
44a0d8ea 1574 $this->waitForElementPresent("s2id_target_contact_id");
6a488035
TO
1575
1576 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__);
1577
1578 // Typing contact's name into the field (using typeKeys(), not type()!)...
44a0d8ea 1579 $this->select2("assignee_contact_id", $firstName1, TRUE);
6a488035
TO
1580
1581 // ...and verifying if the page contains properly formatted display name for chosen contact.
1582 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__);
1583
1584 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1585 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1586 // For simple input fields we can use field id as selector
1587 $this->type("subject", $subject);
1588 $this->type("location", "Some location needs to be put in this field.");
1589
1590 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1591
1592 // Setting duration.
1593 $this->type("duration", "30");
1594
1595 // Putting in details.
1596 $this->type("details", "Really brief details information.");
1597
1598 // Making sure that status is set to Scheduled (using value, not label).
1599 $this->select("status_id", "value=1");
1600
1601 // Setting priority.
1602 $this->select("priority_id", "value=1");
1603
1604 // Scheduling follow-up.
1605 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1606 $this->select("followup_activity_type_id", "value=1");
1607 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1608 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1609
1610 // Clicking save.
1611 $this->click("_qf_Activity_upload-bottom");
44a0d8ea 1612 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
6a488035
TO
1613
1614 // Is status message correct?
44a0d8ea 1615 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
6a488035 1616
bf333c47 1617 $this->waitForElementPresent("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
6a488035
TO
1618
1619 // click through to the Activity view screen
b3d40287 1620 $this->clickLinkSuppressPopup("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']", '_qf_Activity_cancel-bottom');
76e86fd8 1621
efb29358
CW
1622 // parse URL to grab the activity id
1623 // pass id back to any other tests that call this class
1624 return $this->urlArg('id');
6a488035
TO
1625 }
1626
4cbe18b8
EM
1627 /**
1628 * @return bool
1629 */
6a488035 1630 static
00be9182 1631 public function checkDoLocalDBTest() {
6a488035
TO
1632 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1633 CIVICRM_WEBTEST_LOCAL_DB
1634 ) {
1635 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1636 return TRUE;
1637 }
1638 return FALSE;
1639 }
1640
1641 /**
1642 * Generic function to compare expected values after an api call to retrieved
1643 * DB values.
1644 *
fcb93467
EM
1645 * @param string $daoName
1646 * DAO Name of object we're evaluating.
1647 * @param int $id
1648 * Id of object
1649 * @param array $match
1650 * Associative array of field name => expected value. Empty if asserting
6a488035 1651 * that a DELETE occurred
fcb93467
EM
1652 * @param boolean $delete
1653 * are we checking that a DELETE action occurred?
6a488035 1654 */
00be9182 1655 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
fcb93467
EM
1656 if (self::checkDoLocalDBTest()) {
1657 CiviDBAssert::assertDBState($this, $daoName, $id, $match, $delete);
6a488035 1658 }
6a488035
TO
1659 }
1660
4cbe18b8 1661 /**
4f1f1f2a 1662 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
c490a46a 1663 * @param string $daoName
08caad8e
EM
1664 * @param string $searchValue
1665 * @param string $returnColumn
1666 * @param string $searchColumn
1667 * @param string $message
4cbe18b8 1668 */
00be9182 1669 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
08caad8e
EM
1670 if (self::checkDoLocalDBTest()) {
1671 CiviDBAssert::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
6a488035 1672 }
6a488035
TO
1673 }
1674
4cbe18b8 1675 /**
08caad8e 1676 * Request a record from the DB by searchColumn+searchValue. Success if returnColumn value is NULL.
c490a46a 1677 * @param string $daoName
08caad8e
EM
1678 * @param string $searchValue
1679 * @param string $returnColumn
1680 * @param string $searchColumn
1681 * @param string $message
4cbe18b8 1682 */
00be9182 1683 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
08caad8e
EM
1684 if (self::checkDoLocalDBTest()) {
1685 CiviDBAssert::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
6a488035 1686 }
6a488035
TO
1687 }
1688
4cbe18b8 1689 /**
4f1f1f2a 1690 * Request a record from the DB by id. Success if row not found.
c490a46a 1691 * @param string $daoName
100fef9d 1692 * @param int $id
9d06e7e6 1693 * @param string $message
4cbe18b8 1694 */
08caad8e
EM
1695 public function assertDBRowNotExist($daoName, $id, $message) {
1696 if (self::checkDoLocalDBTest()) {
1697 CiviDBAssert::assertDBRowNotExist($this, $daoName, $id, $message);
6a488035 1698 }
6a488035
TO
1699 }
1700
4cbe18b8 1701 /**
4f1f1f2a 1702 * Compare all values in a single retrieved DB record to an array of expected values
c490a46a 1703 * @param string $daoName
100fef9d 1704 * @param array $searchParams
4cbe18b8
EM
1705 * @param $expectedValues
1706 */
00be9182 1707 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
b7d77cba
EM
1708 if (self::checkDoLocalDBTest()) {
1709 CiviDBAssert::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
6a488035 1710 }
6a488035
TO
1711 }
1712
4cbe18b8
EM
1713 /**
1714 * @param $expected
1715 * @param $actual
1716 * @param string $message
1717 */
00be9182 1718 public function assertType($expected, $actual, $message = '') {
b7d77cba 1719 $this->assertInternalType($expected, $actual, $message);
6a488035
TO
1720 }
1721
6a488035
TO
1722 /**
1723 * Add new Financial Account
f0be539a
EM
1724 * @param $financialAccountTitle
1725 * @param bool $financialAccountDescription
1726 * @param bool $accountingCode
1727 * @param bool $firstName
1728 * @param bool $financialAccountType
1729 * @param bool $taxDeductible
1730 * @param bool $isActive
1731 * @param bool $isTax
1732 * @param bool $taxRate
1733 * @param bool $isDefault
6a488035 1734 */
5896d037
TO
1735 function _testAddFinancialAccount(
1736 $financialAccountTitle,
1737 $financialAccountDescription = FALSE,
1738 $accountingCode = FALSE,
1739 $firstName = FALSE,
1740 $financialAccountType = FALSE,
1741 $taxDeductible = FALSE,
1742 $isActive = FALSE,
1743 $isTax = FALSE,
1744 $taxRate = FALSE,
1745 $isDefault = FALSE
6a488035
TO
1746 ) {
1747
b45c587e 1748 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
6a488035
TO
1749
1750 $this->click("link=Add Financial Account");
1751 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1752
1753 // Financial Account Name
1754 $this->type('name', $financialAccountTitle);
1755
1756 // Financial Description
1757 if ($financialAccountDescription) {
1758 $this->type('description', $financialAccountDescription);
1759 }
1760
1761 //Accounting Code
1762 if ($accountingCode) {
1763 $this->type('accounting_code', $accountingCode);
1764 }
1765
1766 // Autofill Organization
1767 if ($firstName) {
1768 $this->webtestOrganisationAutocomplete($firstName);
1769 }
1770
1771 // Financial Account Type
1772 if ($financialAccountType) {
1773 $this->select('financial_account_type_id', "label={$financialAccountType}");
1774 }
1775
1776 // Is Tax Deductible
1777 if ($taxDeductible) {
1778 $this->check('is_deductible');
1779 }
1780 else {
1781 $this->uncheck('is_deductible');
1782 }
1783 // Is Active
1784 if (!$isActive) {
1785 $this->check('is_active');
1786 }
1787 else {
1788 $this->uncheck('is_active');
1789 }
1790 // Is Tax
1791 if ($isTax) {
1792 $this->check('is_tax');
1793 }
1794 else {
1795 $this->uncheck('is_tax');
1796 }
1797 // Tax Rate
1798 if ($taxRate) {
1799 $this->type('tax_rate', $taxRate);
1800 }
1801
1802 // Set Default
1803 if ($isDefault) {
1804 $this->check('is_default');
1805 }
1806 else {
1807 $this->uncheck('is_default');
1808 }
1809 $this->click('_qf_FinancialAccount_next-botttom');
6a488035
TO
1810 }
1811
6a488035
TO
1812 /**
1813 * Edit Financial Account
1e1fdcf6
EM
1814 * @param $editfinancialAccount
1815 * @param bool $financialAccountTitle
1816 * @param bool $financialAccountDescription
1817 * @param bool $accountingCode
1818 * @param bool $firstName
1819 * @param bool $financialAccountType
1820 * @param bool $taxDeductible
1821 * @param bool $isActive
1822 * @param bool $isTax
1823 * @param bool $taxRate
1824 * @param bool $isDefault
6a488035 1825 */
5896d037
TO
1826 function _testEditFinancialAccount(
1827 $editfinancialAccount,
92915c55
TO
1828 $financialAccountTitle = FALSE,
1829 $financialAccountDescription = FALSE,
1830 $accountingCode = FALSE,
1831 $firstName = FALSE,
1832 $financialAccountType = FALSE,
1833 $taxDeductible = FALSE,
1834 $isActive = TRUE,
1835 $isTax = FALSE,
1836 $taxRate = FALSE,
1837 $isDefault = FALSE
6a488035
TO
1838 ) {
1839 if ($firstName) {
b45c587e 1840 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
6a488035
TO
1841 }
1842
4a058f26
WA
1843 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']");
1844 $this->clickLink("xpath=//table/tbody//tr/td[1]/div[text()='{$editfinancialAccount}']/../../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
6a488035
TO
1845
1846 // Change Financial Account Name
1847 if ($financialAccountTitle) {
1848 $this->type('name', $financialAccountTitle);
1849 }
1850
1851 // Financial Description
1852 if ($financialAccountDescription) {
1853 $this->type('description', $financialAccountDescription);
1854 }
1855
1856 //Accounting Code
1857 if ($accountingCode) {
1858 $this->type('accounting_code', $accountingCode);
1859 }
1860
6a488035
TO
1861 // Autofill Edit Organization
1862 if ($firstName) {
1863 $this->webtestOrganisationAutocomplete($firstName);
1864 }
1865
1866 // Financial Account Type
1867 if ($financialAccountType) {
1868 $this->select('financial_account_type_id', "label={$financialAccountType}");
1869 }
1870
1871 // Is Tax Deductible
1872 if ($taxDeductible) {
1873 $this->check('is_deductible');
1874 }
1875 else {
1876 $this->uncheck('is_deductible');
1877 }
1878
1879 // Is Tax
1880 if ($isTax) {
1881 $this->check('is_tax');
1882 }
1883 else {
1884 $this->uncheck('is_tax');
1885 }
1886
1887 // Tax Rate
1888 if ($taxRate) {
1889 $this->type('tax_rate', $taxRate);
1890 }
1891
1892 // Set Default
1893 if ($isDefault) {
1894 $this->check('is_default');
1895 }
1896 else {
1897 $this->uncheck('is_default');
1898 }
1899
1900 // Is Active
1901 if ($isActive) {
1902 $this->check('is_active');
1903 }
1904 else {
1905 $this->uncheck('is_active');
1906 }
1907 $this->click('_qf_FinancialAccount_next-botttom');
6cbe4dc3 1908 $this->waitForElementPresent('link=Add Financial Account');
6a488035
TO
1909 }
1910
6a488035
TO
1911 /**
1912 * Delete Financial Account
1e1fdcf6 1913 * @param $financialAccountTitle
6a488035 1914 */
00be9182 1915 public function _testDeleteFinancialAccount($financialAccountTitle) {
4a058f26 1916 $this->click("xpath=//table/tbody//tr/td[1]/div[text()='{$financialAccountTitle}']/../../td[9]/span/a[text()='Delete']");
6a488035
TO
1917 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1918 $this->click('_qf_FinancialAccount_next-botttom');
1919 $this->waitForElementPresent('link=Add Financial Account');
6cbe4dc3 1920 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
6a488035
TO
1921 }
1922
1923 /**
1924 * Verify data after ADD and EDIT
1e1fdcf6 1925 * @param $verifyData
6a488035 1926 */
00be9182 1927 public function _assertFinancialAccount($verifyData) {
6a488035
TO
1928 foreach ($verifyData as $key => $expectedValue) {
1929 $actualValue = $this->getValue($key);
1930 if ($key == 'parent_financial_account') {
1931 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1932 }
1933 else {
1934 $this->assertEquals($expectedValue, $actualValue);
1935 }
1936 }
1937 }
1938
4cbe18b8
EM
1939 /**
1940 * @param $verifySelectFieldData
1941 */
00be9182 1942 public function _assertSelectVerify($verifySelectFieldData) {
6a488035
TO
1943 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1944 $actualvalue = $this->getSelectedLabel($key);
1945 $this->assertEquals($expectedvalue, $actualvalue);
1946 }
1947 }
1948
4cbe18b8
EM
1949 /**
1950 * @param $financialType
1951 * @param string $option
1952 */
00be9182 1953 public function addeditFinancialType($financialType, $option = 'new') {
b45c587e 1954 $this->openCiviPage("admin/financial/financialType", "reset=1");
6a488035
TO
1955
1956 if ($option == 'Delete') {
4a058f26 1957 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[name]']/../../td[7]/span[2]");
6a488035 1958 $this->waitForElementPresent("css=span.btn-slide-active");
4a058f26 1959 $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
1960 $this->waitForElementPresent("_qf_FinancialType_next");
1961 $this->click("_qf_FinancialType_next");
6cbe4dc3
AS
1962 $this->waitForElementPresent("newFinancialType");
1963 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
6a488035
TO
1964 return;
1965 }
1966 if ($option == 'new') {
1967 $this->click("link=Add Financial Type");
1968 }
1969 else {
4a058f26 1970 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1]/div[text()='$financialType[oldname]']/../../td[7]/span/a[text()='Edit']");
6a488035 1971 }
c1d1bf14 1972 $this->waitForElementPresent("name");
6a488035
TO
1973 $this->type('name', $financialType['name']);
1974 if ($option == 'new') {
1975 $this->type('description', $financialType['name'] . ' description');
1976 }
1977
1978 if ($financialType['is_reserved']) {
1979 $this->check('is_reserved');
1980 }
1981 else {
1982 $this->uncheck('is_reserved');
1983 }
1984
1985 if ($financialType['is_deductible']) {
1986 $this->check('is_deductible');
1987 }
1988 else {
1989 $this->uncheck('is_deductible');
1990 }
1991
1992 $this->click('_qf_FinancialType_next');
6a488035 1993 if ($option == 'new') {
ba6f320f 1994 $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
1995 }
1996 else {
c51f8adb 1997 $text = "The financial type \"{$financialType['name']}\" has been updated.";
6a488035 1998 }
5c88df60 1999 $this->checkCRMAlert($text);
6a488035
TO
2000 }
2001
42daf119
CW
2002 /**
2003 * Give the specified permissions
b45c587e 2004 * Note: this function logs in as 'admin' (logging out if necessary)
1e1fdcf6 2005 * @param $permission
42daf119 2006 */
00be9182 2007 public function changePermissions($permission) {
42daf119
CW
2008 $this->webtestLogin('admin');
2009 $this->open("{$this->sboxPath}admin/people/permissions");
6a488035 2010 $this->waitForElementPresent('edit-submit');
42daf119
CW
2011 foreach ((array) $permission as $perm) {
2012 $this->check($perm);
6a488035
TO
2013 }
2014 $this->click('edit-submit');
2015 $this->waitForPageToLoad($this->getTimeoutMsec());
2016 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
6a488035
TO
2017 }
2018
4cbe18b8
EM
2019 /**
2020 * @param $profileTitle
2021 * @param $profileFields
2022 */
00be9182 2023 public function addProfile($profileTitle, $profileFields) {
42daf119 2024 $this->openCiviPage('admin/uf/group', "reset=1");
6a488035 2025
39a2888d 2026 $this->clickLink('link=Add Profile', '_qf_Group_cancel-bottom');
6a488035 2027 $this->type('title', $profileTitle);
7df6dc24 2028 $this->clickLink('_qf_Group_next-bottom');
6a488035 2029
39a2888d 2030 $this->waitForText('crm-notification-container', "Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now.");
6a488035
TO
2031
2032 foreach ($profileFields as $field) {
2033 $this->waitForElementPresent('field_name_0');
6a488035
TO
2034 $this->click("id=field_name_0");
2035 $this->select("id=field_name_0", "label=" . $field['type']);
2036 $this->waitForElementPresent('field_name_1');
2037 $this->click("id=field_name_1");
2038 $this->select("id=field_name_1", "label=" . $field['name']);
2039 $this->waitForElementPresent('label');
2040 $this->type("id=label", $field['label']);
2041 $this->click("id=_qf_Field_next_new-top");
bf2c3b74 2042 $this->waitForElementPresent("xpath=//select[@id='field_name_1'][@style='display: none;']");
6a488035
TO
2043 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
2044 }
2045 }
2046
4cbe18b8 2047 /**
100fef9d 2048 * @param string $name
4cbe18b8
EM
2049 * @param $sku
2050 * @param $amount
2051 * @param $price
2052 * @param $cost
2053 * @param $financialType
2054 */
00be9182 2055 public function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
022def1d 2056 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
6a488035
TO
2057 $this->type("name", $name);
2058 $this->type("sku", $sku);
2059 $this->click("CIVICRM_QFID_noImage_16");
2060 $this->type("min_contribution", $amount);
2061 $this->type("price", $price);
2062 $this->type("cost", $cost);
2063 if ($financialType) {
2064 $this->select("financial_type_id", "label={$financialType}");
2065 }
022def1d 2066 $this->click("_qf_ManagePremiums_upload-bottom");
6a488035
TO
2067 $this->waitForPageToLoad($this->getTimeoutMsec());
2068 }
2069
4cbe18b8
EM
2070 /**
2071 * @param $label
2072 * @param $financialAccount
2073 */
00be9182 2074 public function addPaymentInstrument($label, $financialAccount) {
118e964e 2075 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
6a488035
TO
2076 $this->type("label", $label);
2077 $this->select("financial_account_id", "value=$financialAccount");
2078 $this->click("_qf_Options_next-bottom");
2079 $this->waitForPageToLoad($this->getTimeoutMsec());
2080 }
2081
5ff68892
CW
2082 /**
2083 * Ensure we have a default mailbox set up for CiviMail
2084 */
00be9182 2085 public function setupDefaultMailbox() {
5ff68892
CW
2086 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
2087 // Check if it hasn't already been set up
2088 if (!$this->getSelectedValue('protocol')) {
2089 $this->type('name', 'Test Domain');
2090 $this->select('protocol', "IMAP");
2091 $this->type('server', 'localhost');
2092 $this->type('domain', 'example.com');
e739afc3 2093 $this->clickLink('_qf_MailSettings_next-top');
5ff68892
CW
2094 }
2095 }
2096
6a488035
TO
2097 /**
2098 * Determine the default time-out in milliseconds.
2099 *
2100 * @return string, timeout expressed in milliseconds
2101 */
00be9182 2102 public function getTimeoutMsec() {
6a488035
TO
2103 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
2104 $timeout = ($this->settings && @$this->settings->timeout) ? ($this->settings->timeout * 1000) : 30000;
2105 return (string) $timeout; // don't know why, but all our old code used a string
2106 }
6a488035 2107
c4e6d4e8
PJ
2108 /**
2109 * CRM-12378
2110 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
2111 *
2112 *
e16033b4
TO
2113 * @param array $customSets
2114 * Custom sets i.e entity wise sets want to be created and checked.
16b10e64 2115 * e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
5896d037
TO
2116 * 'triggerElement' => $triggerElement))
2117 * array $triggerElement: the element which is responsible for custom group to load
2118 *
2119 * which uses the entity info as its selection value
e16033b4
TO
2120 * @param array $pageUrl
2121 * The url which on which the ajax custom group load takes place.
b7d77cba 2122 * @param string $beforeTriggering
c4e6d4e8
PJ
2123 * @return void
2124 */
00be9182 2125 public function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
a40669b6
CW
2126 // FIXME: Testing a theory that these failures have something to do with permissions
2127 $this->webtestLogin('admin');
2128
c4e6d4e8
PJ
2129 //add the custom set
2130 $return = $this->addCustomGroupField($customSets);
2131
87f534f9 2132 // FIXME: Hack to ensure caches are properly cleared
dc499911
CW
2133 if (TRUE) {
2134 $userName = $this->loggedInAs;
e42c089b 2135 $this->webtestLogout();
dc499911 2136 $this->webtestLogin($userName);
e42c089b
CW
2137 }
2138
87f534f9 2139 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
b50973e8
CW
2140
2141 // FIXME: Try to find out what the heck is going on with these tests
2142 $this->waitForAjaxContent();
2143 $this->checkForErrorsOnPage();
2144
5896d037 2145 foreach ($return as $values) {
c4e6d4e8
PJ
2146 foreach ($values as $entityType => $customData) {
2147 //initiate necessary variables
2148 list($entity, $entityData) = explode('_', $entityType);
2149 $elementType = CRM_Utils_Array::value('type', $customData['triggerElement'], 'select');
2150 $elementName = CRM_Utils_Array::value('name', $customData['triggerElement']);
e42c089b 2151 if (is_callable($beforeTriggering)) {
5b8ddc60
PJ
2152 call_user_func($beforeTriggering);
2153 }
c4e6d4e8
PJ
2154 if ($elementType == 'select') {
2155 //reset the select box, so triggering of ajax only happens
2156 //WRT input of value in this function
2157 $this->select($elementName, "index=0");
2158 }
2159 if (!empty($entityData)) {
2160 if ($elementType == 'select') {
2161 $this->select($elementName, "label=regexp:{$entityData}");
2162 }
2163 elseif ($elementType == 'checkbox') {
2164 $val = explode(',', $entityData);
5896d037 2165 foreach ($val as $v) {
c4e6d4e8
PJ
2166 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2167 $this->check($checkId);
2168 }
2169 }
16345393
AS
2170 elseif ($elementType == 'select2') {
2171 $this->select2($elementName, $entityData);
2172 }
c4e6d4e8 2173 }
a2cfaf9e
CW
2174 // FIXME: Try to find out what the heck is going on with these tests
2175 $this->waitForAjaxContent();
2176 $this->checkForErrorsOnPage();
a40669b6 2177
c4e6d4e8 2178 //checking for proper custom data which is loading through ajax
a40669b6 2179 $this->waitForElementPresent("css=.custom-group-{$customData['cgtitle']}");
16345393 2180 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
c4e6d4e8
PJ
2181 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2182 }
2183 }
2184 }
2185
4cbe18b8
EM
2186 /**
2187 * @param $customSets
2188 *
2189 * @return array
2190 */
00be9182 2191 public function addCustomGroupField($customSets) {
57d32317 2192 $return = array();
c4e6d4e8
PJ
2193 foreach ($customSets as $customSet) {
2194 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2195
2196 //fill custom group title
2197 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2198 $this->click("title");
2199 $this->type("title", $customGroupTitle);
2200
2201 //custom group extends
2202 $this->click("extends_0");
2203 $this->select("extends_0", "value={$customSet['entity']}");
2204 if (!empty($customSet['subEntity'])) {
2205 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2206 }
2207
2208 // Don't collapse
2209 $this->uncheck('collapse_display');
2210
2211 // Save
2212 $this->click('_qf_Group_next-bottom');
c4e6d4e8
PJ
2213
2214 //Is custom group created?
2215 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
5dac229e 2216
c4e6d4e8 2217 $gid = $this->urlArg('gid');
5dac229e 2218 $this->waitForTextPresent("{$customGroupTitle} - New Field");
c4e6d4e8
PJ
2219
2220 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
c3ad8633 2221 $this->waitForElementPresent('label');
c4e6d4e8 2222 $this->type('label', $fieldLabel);
50d95825 2223 $this->click('_qf_Field_done-bottom');
c4e6d4e8 2224
c3ad8633
CW
2225 $this->waitForText('crm-notification-container', $fieldLabel);
2226 $this->waitForAjaxContent();
2227
2228 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
c4e6d4e8 2229 $return[] = array(
5896d037
TO
2230 "{$customSet['entity']}_{$customSet['subEntity']}" => array(
2231 'cgtitle' => $customGroupTitle,
2232 'gid' => $gid,
21dfd5f5
TO
2233 'triggerElement' => $customSet['triggerElement'],
2234 ),
5896d037 2235 );
e739afc3
CW
2236
2237 // Go home for a sec to give time for caches to clear
2238 $this->openCiviPage('');
c4e6d4e8
PJ
2239 }
2240 return $return;
2241 }
5320adf4
WA
2242
2243 /**
100fef9d 2244 * Type and select first occurance of autocomplete
1e1fdcf6
EM
2245 * @param $fieldName
2246 * @param $label
2247 * @param bool $multiple
2248 * @param bool $xpath
5320adf4 2249 */
6c6e6187 2250 public function select2($fieldName, $label, $multiple = FALSE, $xpath = FALSE) {
57d32317
CW
2251 // In the case of chainSelect, wait for options to load
2252 $this->waitForElementNotPresent('css=select.loading');
2af8120a 2253 if ($multiple) {
48ebbfbe 2254 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2255 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2256 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2257 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2af8120a 2258 $this->waitForElementPresent("//*[@class='select2-result-label']");
88a6f4b3 2259 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2af8120a
AS
2260 }
2261 else {
3e60ff7f
JP
2262 if ($xpath) {
2263 $this->clickAt($fieldName);
2264 }
2265 else {
2266 $this->clickAt("//*[@id='$fieldName']/../div/a");
2267 }
2af8120a
AS
2268 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2269 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2270 $this->type("//*[@id='select2-drop']/div/input", $label);
2271 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
2272 $this->waitForElementPresent("//*[@class='select2-result-label']");
e9322446 2273 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2af8120a 2274 }
e739afc3
CW
2275 // Wait a sec for select2 to update the original element
2276 sleep(1);
5320adf4 2277 }
f1690d4a 2278
2279 /**
100fef9d 2280 * Select multiple options
1e1fdcf6
EM
2281 * @param $fieldid
2282 * @param $params
f1690d4a 2283 */
00be9182 2284 public function multiselect2($fieldid, $params) {
50d95825
CW
2285 // In the case of chainSelect, wait for options to load
2286 $this->waitForElementNotPresent('css=select.loading');
5896d037 2287 foreach ($params as $value) {
f1690d4a 2288 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2289 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2290 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
3e60ff7f 2291 $this->assertElementContainsText("xpath=//*[@id='$fieldid']/preceding-sibling::div[1]/", $value);
f1690d4a 2292 }
e739afc3
CW
2293 // Wait a sec for select2 to update the original element
2294 sleep(1);
f1690d4a 2295 }
c41b442d
CW
2296
2297 /**
5c88df60 2298 * Check for unobtrusive status message as set by CRM.status
1e1fdcf6 2299 * @param null $text
c41b442d 2300 */
6c6e6187 2301 public function checkCRMStatus($text = NULL) {
c41b442d 2302 $this->waitForElementPresent("css=.crm-status-box-outer.status-success");
5c88df60
CW
2303 if ($text) {
2304 $this->assertElementContainsText("css=.crm-status-box-outer.status-success", $text);
2305 }
c41b442d 2306 }
5c88df60 2307
dcba1580 2308 /**
5c88df60 2309 * Check for obtrusive status message as set by CRM.alert
1e1fdcf6
EM
2310 * @param $text
2311 * @param string $type
dcba1580 2312 */
6c6e6187 2313 public function checkCRMAlert($text, $type = 'success') {
5c88df60
CW
2314 $this->waitForElementPresent("css=div.ui-notify-message.$type");
2315 $this->waitForText("css=div.ui-notify-message.$type", $text);
9c5c0056
CW
2316 // We got the message, now let's close it so the webtest doesn't get confused by lots of open alerts
2317 $this->click('css=.ui-notify-cross');
dcba1580 2318 }
5c88df60 2319
d8d3508a 2320 /**
100fef9d 2321 * Enable or disable Pop-ups via Display Preferences
b7d77cba 2322 * @param bool $enabled
d8d3508a 2323 */
00be9182 2324 public function enableDisablePopups($enabled = TRUE) {
d8d3508a
DG
2325 $this->openCiviPage('admin/setting/preferences/display', 'reset=1');
2326 $isChecked = $this->isChecked('ajaxPopupsEnabled');
2327 if (($isChecked && !$enabled) || (!$isChecked && $enabled)) {
6c6e6187 2328 $this->click('ajaxPopupsEnabled');
d8d3508a
DG
2329 }
2330 if ($enabled) {
5c88df60 2331 $this->assertChecked('ajaxPopupsEnabled');
d8d3508a
DG
2332 }
2333 else {
2334 $this->assertNotChecked('ajaxPopupsEnabled');
2335 }
c41b442d 2336 $this->clickLink("_qf_Display_next-bottom");
d8d3508a 2337 }
b50973e8
CW
2338
2339 /**
2340 * Attempt to get information about what went wrong if we encounter an error when loading a page
2341 */
00be9182 2342 public function checkForErrorsOnPage() {
b50973e8 2343 foreach (array('Access denied', 'Page not found') as $err) {
037454ae
CW
2344 if ($this->isElementPresent("xpath=//h1[contains(., '$err')]")) {
2345 $this->fail("'$err' encountered at " . $this->getLocation() . "\nwhile logged in as '{$this->loggedInAs}'");
b50973e8
CW
2346 }
2347 }
2348 if ($this->isElementPresent("xpath=//span[text()='Sorry but we are not able to provide this at the moment.']")) {
2349 $msg = '"Fatal Error" encountered at ' . $this->getLocation();
2350 if ($this->isElementPresent('css=div.crm-section.crm-error-message')) {
2351 $msg .= "\nError Message: " . $this->getText('css=div.crm-section.crm-error-message');
2352 }
2353 $this->fail($msg);
2354 }
2355 }
65c1908a 2356}