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