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