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