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