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