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