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