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