INFRA-132 - tests/ - Convert single-line @param to multi-line
[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($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
688 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
689 // 4 - Individual profile
690 // 5 - Organization profile
691 // 6 - Household profile
692 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
693 $this->clickAt("xpath=//div[@id='$selectId']/a");
694 $this->clickPopupLink("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]", '_qf_Edit_next');
695
696 switch ($type) {
697 case 4:
698 $this->type('first_name', $fname);
699 $this->type('last_name', $lname);
700 break;
701
702 case 5:
703 $this->type('organization_name', $fname);
704 break;
705
706 case 6:
707 $this->type('household_name', $fname);
708 break;
709 }
710
711 $this->type('email-Primary', $email);
712 $this->clickAjaxLink('_qf_Edit_next');
713
714 // Is new contact created?
715 if ($lname) {
716 $this->waitForText("xpath=//div[@id='$selectId']","$lname, $fname");
717 }
718 else {
719 $this->waitForText("xpath=//div[@id='$selectId']","$fname");
720 }
721 }
722
723 /**
724 * Generic function to check that strings are present in the page
725 *
726 * @strings array array of strings or a single string
727 *
728 * @param $strings
729 * @return void
730 */
731 public function assertStringsPresent($strings) {
732 foreach ((array) $strings as $string) {
733 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
734 }
735 }
736
737 /**
738 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
739 *
740 * @url string url to parse or retrieve current url if null
741 *
742 * @param null $url
743 * @return array returns an associative array containing any of the various components
744 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
745 * http://php.net/manual/en/function.parse-url.php
746 */
747 public function parseURL($url = NULL) {
748 if (!$url) {
749 $url = $this->getLocation();
750 }
751
752 $elements = parse_url($url);
753 if (!empty($elements['query'])) {
754 $elements['queryString'] = array();
755 parse_str($elements['query'], $elements['queryString']);
756 }
757 return $elements;
758 }
759
760 /**
761 * Returns a single argument from the url query
762 */
763 public function urlArg($arg, $url = NULL) {
764 $elements = $this->parseURL($url);
765 return isset($elements['queryString'][$arg]) ? $elements['queryString'][$arg] : NULL;
766 }
767
768 /**
769 * Define a payment processor for use by a webtest. Default is to create Dummy processor
770 * which is useful for testing online public forms (online contribution pages and event registration)
771 *
772 * @param string $processorName
773 * Name assigned to new processor.
774 * @param string $processorType
775 * Name for processor type (e.g. PayPal, Dummy, etc.).
776 * @param array $processorSettings
777 * Array of fieldname => value for required settings for the processor.
778 *
779 * @param string $financialAccount
780 * @throws PHPUnit_Framework_AssertionFailedError
781 * @return int
782 */
783
784 public function webtestAddPaymentProcessor($processorName = 'Test Processor', $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
785 if (!$processorName) {
786 $this->fail("webTestAddPaymentProcessor requires $processorName.");
787 }
788 // Ensure we are logged in as admin before we proceed
789 $this->webtestLogin('admin');
790
791 if ($processorName === 'Test Processor') {
792 // Use the default test processor, no need to create a new one
793 $this->openCiviPage('admin/paymentProcessor', 'action=update&id=1&reset=1', '_qf_PaymentProcessor_cancel-bottom');
794 $this->check('is_default');
795 $this->select('financial_account_id', "label={$financialAccount}");
796 $this->clickLink('_qf_PaymentProcessor_next-bottom');
797 return 1;
798 }
799
800 if ($processorType == 'Dummy') {
801 $processorSettings = array(
802 'user_name' => 'dummy',
803 'url_site' => 'http://dummy.com',
804 'test_user_name' => 'dummytest',
805 'test_url_site' => 'http://dummytest.com',
806 );
807 }
808 elseif ($processorType == 'AuthNet') {
809 // FIXME: we 'll need to make a new separate account for testing
810 $processorSettings = array(
811 'test_user_name' => '5ULu56ex',
812 'test_password' => '7ARxW575w736eF5p',
813 );
814 }
815 elseif ($processorType == 'Google_Checkout') {
816 // FIXME: we 'll need to make a new separate account for testing
817 $processorSettings = array(
818 'test_user_name' => '559999327053114',
819 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
820 );
821 }
822 elseif ($processorType == 'PayPal') {
823 $processorSettings = array(
824 'test_user_name' => '559999327053114',
825 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
826 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
827 );
828 }
829 elseif ($processorType == 'PayPal_Standard') {
830 $processorSettings = array(
831 'test_user_name' => 'V18ki@9r5Bf.org',
832 );
833 }
834 elseif (empty($processorSettings)) {
835 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
836 }
837 $pid = CRM_Core_DAO::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
838 if (empty($pid)) {
839 $this->fail("$processorType processortype not found.");
840 }
841 $this->openCiviPage('admin/paymentProcessor', 'action=add&reset=1&pp=' . $pid, 'name');
842 $this->type('name', $processorName);
843 $this->select('financial_account_id', "label={$financialAccount}");
844 foreach ($processorSettings AS $f => $v) {
845 $this->type($f, $v);
846 }
847
848 // Save
849 $this->clickLink('_qf_PaymentProcessor_next-bottom');
850
851 $this->waitForTextPresent($processorName);
852
853 // Get payment processor id
854 $paymentProcessorLink = $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href");
855 return $this->urlArg('id', $paymentProcessorLink);
856 }
857
858 public function webtestAddCreditCardDetails() {
859 $this->waitForElementPresent('credit_card_type');
860 $this->select('credit_card_type', 'label=Visa');
861 $this->type('credit_card_number', '4807731747657838');
862 $this->type('cvv2', '123');
863 $this->select('credit_card_exp_date[M]', 'label=Feb');
864 $this->select('credit_card_exp_date[Y]', 'label=2019');
865 }
866
867 /**
868 * @param null $firstName
869 * @param null $middleName
870 * @param null $lastName
871 *
872 * @return array
873 */
874 public function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
875 if (!$firstName) {
876 $firstName = 'John';
877 }
878
879 if (!$middleName) {
880 $middleName = 'Apple';
881 }
882
883 if (!$lastName) {
884 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
885 }
886
887 $this->type('billing_first_name', $firstName);
888 $this->type('billing_middle_name', $middleName);
889 $this->type('billing_last_name', $lastName);
890
891 $this->type('billing_street_address-5', '234 Lincoln Ave');
892 $this->type('billing_city-5', 'San Bernadino');
893 $this->select2('billing_country_id-5', 'United States');
894 $this->select2('billing_state_province_id-5', 'California');
895 $this->type('billing_postal_code-5', '93245');
896
897 return array($firstName, $middleName, $lastName);
898 }
899
900 /**
901 * @param $fieldLocator
902 * @param null $filePath
903 *
904 * @return null|string
905 */
906 public function webtestAttachFile($fieldLocator, $filePath = NULL) {
907 if (!$filePath) {
908 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
909 $fp = @fopen($filePath, 'w');
910 fputs($fp, 'Test file created by selenium test.');
911 @fclose($fp);
912 }
913
914 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
915
916 $this->attachFile($fieldLocator, "file://{$filePath}");
917
918 return $filePath;
919 }
920
921 /**
922 * @param $headers
923 * @param $rows
924 * @param null $filePath
925 *
926 * @return null|string
927 */
928 public function webtestCreateCSV($headers, $rows, $filePath = NULL) {
929 if (!$filePath) {
930 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
931 }
932
933 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
934
935 foreach ($rows as $row) {
936 $temp = array();
937 foreach ($headers as $field => $header) {
938 $temp[$field] = isset($row[$field]) ? '"' . $row[$field] . '"' : '""';
939 }
940 $data .= implode(', ', $temp) . "\r\n";
941 }
942
943 $fp = @fopen($filePath, 'w');
944 @fwrite($fp, $data);
945 @fclose($fp);
946
947 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
948
949 return $filePath;
950 }
951
952 /**
953 * Create new relationship type w/ user specified params or default.
954 *
955 * @param $params
956 * Array of required params.
957 *
958 * @return an array of saved params values.
959 */
960 public function webtestAddRelationshipType($params = array()) {
961 $this->openCiviPage("admin/reltype", "reset=1&action=add");
962
963 //build the params if not passed.
964 if (!is_array($params) || empty($params)) {
965 $params = array(
966 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
967 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
968 'contact_types_a' => 'Individual',
969 'contact_types_b' => 'Individual',
970 'description' => 'Test Relationship Type Description',
971 );
972 }
973 //make sure we have minimum required params.
974 if (!isset($params['label_a_b']) || empty($params['label_a_b'])) {
975 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
976 }
977
978 //start the form fill.
979 $this->type('label_a_b', $params['label_a_b']);
980 $this->type('label_b_a', $params['label_b_a']);
981 $this->select('contact_types_a', "value={$params['contact_type_a']}");
982 $this->select('contact_types_b', "value={$params['contact_type_b']}");
983 $this->type('description', $params['description']);
984
985 //save the data.
986 $this->click('_qf_RelationshipType_next-bottom');
987 $this->waitForPageToLoad($this->getTimeoutMsec());
988
989 //does data saved.
990 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
991 "Status message didn't show up after saving!"
992 );
993
994 $this->openCiviPage("admin/reltype", "reset=1");
995
996 //validate data on selector.
997 $data = $params;
998 if (isset($data['description'])) {
999 unset($data['description']);
1000 }
1001 $this->assertStringsPresent($data);
1002
1003 return $params;
1004 }
1005
1006 /**
1007 * Create new online contribution page w/ user specified params or defaults.
1008 * FIXME: this function take an absurd number of params - very unwieldy :(
1009 *
1010 * @param null $hash
1011 * @param null $rand
1012 * @param null $pageTitle
1013 * @param array $processor
1014 * @param bool $amountSection
1015 * @param bool $payLater
1016 * @param bool $onBehalf
1017 * @param bool $pledges
1018 * @param bool $recurring
1019 * @param bool $membershipTypes
1020 * @param int $memPriceSetId
1021 * @param bool $friend
1022 * @param int $profilePreId
1023 * @param int $profilePostId
1024 * @param bool $premiums
1025 * @param bool $widget
1026 * @param bool $pcp
1027 * @param bool $isAddPaymentProcessor
1028 * @param bool $isPcpApprovalNeeded
1029 * @param bool $isSeparatePayment
1030 * @param bool $honoreeSection
1031 * @param bool $allowOtherAmount
1032 * @param bool $isConfirmEnabled
1033 * @param string $financialType
1034 * @param bool $fixedAmount
1035 * @param bool $membershipsRequired
1036 * @internal param \can $User define pageTitle, hash and rand values for later data verification
1037 *
1038 * @return null $pageId of newly created online contribution page.
1039 */
1040 function webtestAddContributionPage($hash = NULL,
1041 $rand = NULL,
1042 $pageTitle = NULL,
1043 $processor = array('Test Processor' => 'Dummy'),
1044 $amountSection = TRUE,
1045 $payLater = TRUE,
1046 $onBehalf = TRUE,
1047 $pledges = TRUE,
1048 $recurring = FALSE,
1049 $membershipTypes = TRUE,
1050 $memPriceSetId = NULL,
1051 $friend = TRUE,
1052 $profilePreId = 1,
1053 $profilePostId = 7,
1054 $premiums = TRUE,
1055 $widget = TRUE,
1056 $pcp = TRUE,
1057 $isAddPaymentProcessor = TRUE,
1058 $isPcpApprovalNeeded = FALSE,
1059 $isSeparatePayment = FALSE,
1060 $honoreeSection = TRUE,
1061 $allowOtherAmount = TRUE,
1062 $isConfirmEnabled = TRUE,
1063 $financialType = 'Donation',
1064 $fixedAmount = TRUE,
1065 $membershipsRequired = TRUE
1066 ) {
1067 if (!$hash) {
1068 $hash = substr(sha1(rand()), 0, 7);
1069 }
1070 if (!$pageTitle) {
1071 $pageTitle = 'Donate Online ' . $hash;
1072 }
1073
1074 if (!$rand) {
1075 $rand = 2 * rand(2, 50);
1076 }
1077
1078 // Create a new payment processor if requested
1079 if ($isAddPaymentProcessor) {
1080 while (list($processorName, $processorType) = each($processor)) {
1081 $this->webtestAddPaymentProcessor($processorName, $processorType);
1082 }
1083 }
1084
1085 // go to the New Contribution Page page
1086 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
1087
1088 // fill in step 1 (Title and Settings)
1089 $this->type('title', $pageTitle);
1090
1091 //to select financial type
1092 $this->select('financial_type_id', "label={$financialType}");
1093
1094 if ($onBehalf) {
1095 $this->click('is_organization');
1096 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
1097 $this->type('for_organization', "On behalf $hash");
1098
1099 if ($onBehalf == 'required') {
1100 $this->click('CIVICRM_QFID_2_4');
1101 }
1102 elseif ($onBehalf == 'optional') {
1103 $this->click('CIVICRM_QFID_1_2');
1104 }
1105 }
1106
1107 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1108 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1109
1110 $this->type('goal_amount', 10 * $rand);
1111
1112 // FIXME: handle Start/End Date/Time
1113 if ($honoreeSection) {
1114 $this->click('honor_block_is_active');
1115 $this->type('honor_block_title', "Honoree Section Title $hash");
1116 $this->type('honor_block_text', "Honoree Introductory Message $hash");
1117 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1118 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1119 $this->waitForElementPresent("//*[@class='select2-result-label']");
1120 $this->clickAt("//*[@class='select2-results']/li[1]");
1121 }
1122
1123 // is confirm enabled? it starts out enabled, so uncheck it if false
1124 if (!$isConfirmEnabled) {
1125 $this->click("id=is_confirm_enabled");
1126 }
1127
1128 // Submit form
1129 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1130
1131 // Get contribution page id
1132 $pageId = $this->urlArg('id');
1133
1134 // fill in step 2 (Processor, Pay Later, Amounts)
1135 if (!empty($processor)) {
1136 reset($processor);
1137 while (list($processorName) = each($processor)) {
1138 // select newly created processor
1139 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1140 $this->assertTrue($this->isTextPresent($processorName));
1141 $this->check($xpath);
1142 }
1143 }
1144
1145 if ($amountSection && !$memPriceSetId) {
1146 if ($payLater) {
1147 $this->click('is_pay_later');
1148 $this->type('pay_later_text', "Pay later label $hash");
1149 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1150 }
1151
1152 if ($pledges) {
1153 $this->click('is_pledge_active');
1154 $this->click('pledge_frequency_unit[week]');
1155 $this->click('is_pledge_interval');
1156 $this->type('initial_reminder_day', 3);
1157 $this->type('max_reminders', 2);
1158 $this->type('additional_reminder_day', 1);
1159 }
1160 elseif ($recurring) {
1161 $this->click('is_recur');
1162 $this->click("is_recur_interval");
1163 $this->click("is_recur_installments");
1164 }
1165 if ($allowOtherAmount) {
1166
1167 $this->click('is_allow_other_amount');
1168
1169 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1170 //$this->type('min_amount', $rand / 2);
1171 //$this->type('max_amount', $rand * 10);
1172 }
1173 if ($fixedAmount || !$allowOtherAmount) {
1174 $this->type('label_1', "Label $hash");
1175 $this->type('value_1', "$rand");
1176 }
1177 $this->click('CIVICRM_QFID_1_4');
1178 }
1179 else {
1180 $this->click('amount_block_is_active');
1181 }
1182
1183 $this->click('_qf_Amount_next');
1184 $this->waitForElementPresent('_qf_Amount_next-bottom');
1185 $this->waitForPageToLoad($this->getTimeoutMsec());
1186 $text = "'Amount' information has been saved.";
1187 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1188
1189 if ($memPriceSetId || (($membershipTypes === TRUE) || (is_array($membershipTypes) && !empty($membershipTypes)))) {
1190 // go to step 3 (memberships)
1191 $this->click('link=Memberships');
1192 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1193
1194 // fill in step 3 (Memberships)
1195 $this->click('member_is_active');
1196 $this->waitForElementPresent('displayFee');
1197 $this->type('new_title', "Title - New Membership $hash");
1198 $this->type('renewal_title', "Title - Renewals $hash");
1199
1200 if ($memPriceSetId) {
1201 $this->click('member_price_set_id');
1202 $this->select('member_price_set_id', "value={$memPriceSetId}");
1203 }
1204 else {
1205 if ($membershipTypes === TRUE) {
1206 $membershipTypes = array(array('id' => 2));
1207 }
1208
1209 // FIXME: handle Introductory Message - New Memberships/Renewals
1210 foreach ($membershipTypes as $mType) {
1211 $this->click("membership_type_{$mType['id']}");
1212 if (array_key_exists('default', $mType)) {
1213 // FIXME:
1214 }
1215 if (array_key_exists('auto_renew', $mType)) {
1216 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1217 }
1218 }
1219 if ($membershipsRequired) {
1220 $this->click('is_required');
1221 }
1222 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1223 $this->click('CIVICRM_QFID_2_4');
1224 if ($isSeparatePayment) {
1225 $this->click('is_separate_payment');
1226 }
1227 }
1228 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1229 $text = "'MembershipBlock' information has been saved.";
1230 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1231 }
1232
1233 // go to step 4 (thank-you and receipting)
1234 $this->click('link=Receipt');
1235 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1236
1237 // fill in step 4
1238 $this->type('thankyou_title', "Thank-you Page Title $hash");
1239 // FIXME: handle Thank-you Message/Page Footer
1240 $this->type('receipt_from_name', "Receipt From Name $hash");
1241 $this->type('receipt_from_email', "$hash@example.org");
1242 $this->type('receipt_text', "Receipt Message $hash");
1243 $this->type('cc_receipt', "$hash@example.net");
1244 $this->type('bcc_receipt', "$hash@example.com");
1245
1246 $this->click('_qf_ThankYou_next');
1247 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1248 $this->waitForPageToLoad($this->getTimeoutMsec());
1249 $text = "'ThankYou' information has been saved.";
1250 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1251
1252 if ($friend) {
1253 // fill in step 5 (Tell a Friend)
1254 $this->click('link=Tell a Friend');
1255 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1256 $this->click('tf_is_active');
1257 $this->type('tf_title', "TaF Title $hash");
1258 $this->type('intro', "TaF Introduction $hash");
1259 $this->type('suggested_message', "TaF Suggested Message $hash");
1260 $this->type('general_link', "TaF Info Page Link $hash");
1261 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1262 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1263
1264 //$this->click('_qf_Contribute_next');
1265 $this->click('_qf_Contribute_next-bottom');
1266 $this->waitForPageToLoad($this->getTimeoutMsec());
1267 $text = "'Friend' information has been saved.";
1268 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1269 }
1270
1271 if ($profilePreId || $profilePostId) {
1272 // fill in step 6 (Include Profiles)
1273 $this->click('css=li#tab_custom a');
1274 $this->waitForElementPresent('_qf_Custom_next-bottom');
1275
1276 if ($profilePreId) {
1277 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1278 }
1279
1280 if ($profilePostId) {
1281 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1282 }
1283
1284 $this->click('_qf_Custom_next-bottom');
1285 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1286
1287 $this->waitForPageToLoad($this->getTimeoutMsec());
1288 $text = "'Custom' information has been saved.";
1289 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1290 }
1291
1292 if ($premiums) {
1293 // fill in step 7 (Premiums)
1294 $this->click('link=Premiums');
1295 $this->waitForElementPresent('_qf_Premium_next-bottom');
1296 $this->click('premiums_active');
1297 $this->type('premiums_intro_title', "Prem Title $hash");
1298 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1299 $this->type('premiums_contact_email', "$hash@example.info");
1300 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1301 $this->click('premiums_display_min_contribution');
1302 $this->type('premiums_nothankyou_label', 'No thank-you');
1303 $this->click('_qf_Premium_next');
1304 $this->waitForElementPresent('_qf_Premium_next-bottom');
1305
1306 $this->waitForPageToLoad($this->getTimeoutMsec());
1307 $text = "'Premium' information has been saved.";
1308 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1309 }
1310
1311 if ($widget) {
1312 // fill in step 8 (Widget Settings)
1313 $this->click('link=Widgets');
1314 $this->waitForElementPresent('_qf_Widget_next-bottom');
1315
1316 $this->click('is_active');
1317 $this->type('url_logo', "URL to Logo Image $hash");
1318 $this->type('button_title', "Button Title $hash");
1319 // Type About text in ckEditor (fieldname, text to type, editor)
1320 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1321
1322 $this->click('_qf_Widget_next');
1323 $this->waitForElementPresent('_qf_Widget_next-bottom');
1324
1325 $this->waitForPageToLoad($this->getTimeoutMsec());
1326 $text = "'Widget' information has been saved.";
1327 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1328 }
1329
1330 if ($pcp) {
1331 // fill in step 9 (Enable Personal Campaign Pages)
1332 $this->click('link=Personal Campaigns');
1333 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1334 $this->click('pcp_active');
1335 if (!$isPcpApprovalNeeded) {
1336 $this->click('is_approval_needed');
1337 }
1338 $this->type('notify_email', "$hash@example.name");
1339 $this->select('supporter_profile_id', 'value=2');
1340 $this->type('tellfriend_limit', 7);
1341 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1342
1343 $this->click('_qf_Contribute_next-bottom');
1344 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1345 $this->waitForPageToLoad($this->getTimeoutMsec());
1346 $text = "'Pcp' information has been saved.";
1347 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1348 }
1349
1350 return $pageId;
1351 }
1352
1353 /**
1354 * Update default strict rule.
1355 *
1356 * @param string $contactType
1357 * @param array $fields
1358 * Fields to be set for strict rule.
1359 * @param int $threshold
1360 * Rule's threshold value.
1361 */
1362 public function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1363 // set default strict rule.
1364 $strictRuleId = 4;
1365 if ($contactType == 'Organization') {
1366 $strictRuleId = 5;
1367 }
1368 elseif ($contactType == 'Household') {
1369 $strictRuleId = 6;
1370 }
1371
1372 // Default dedupe fields for each Contact type.
1373 if (empty($fields)) {
1374 $fields = array('civicrm_email.email' => 10);
1375 if ($contactType == 'Organization') {
1376 $fields = array(
1377 'civicrm_contact.organization_name' => 10,
1378 'civicrm_email.email' => 10,
1379 );
1380 }
1381 elseif ($contactType == 'Household') {
1382 $fields = array(
1383 'civicrm_contact.household_name' => 10,
1384 'civicrm_email.email' => 10,
1385 );
1386 }
1387 }
1388
1389 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1390
1391 $count = 0;
1392 foreach ($fields as $field => $weight) {
1393 $this->select("where_{$count}", "value={$field}");
1394 $this->type("length_{$count}", '');
1395 $this->type("weight_{$count}", $weight);
1396 $count++;
1397 }
1398
1399 if ($count > 4) {
1400 $this->type('threshold', $threshold);
1401 // click save
1402 $this->click('_qf_DedupeRules_next-bottom');
1403 $this->waitForPageToLoad($this->getTimeoutMsec());
1404 return;
1405 }
1406
1407 for ($i = $count; $i <= 4; $i++) {
1408 $this->select("where_{$i}", 'label=- none -');
1409 $this->type("length_{$i}", '');
1410 $this->type("weight_{$i}", '');
1411 }
1412
1413 $this->type('threshold', $threshold);
1414
1415 // click save
1416 $this->click('_qf_DedupeRules_next-bottom');
1417 $this->waitForPageToLoad($this->getTimeoutMsec());
1418 }
1419
1420 /**
1421 * @param string $period_type
1422 * @param int $duration_interval
1423 * @param string $duration_unit
1424 * @param string $auto_renew
1425 *
1426 * @return array
1427 */
1428 public function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1429 $membershipTitle = substr(sha1(rand()), 0, 7);
1430 $membershipOrg = $membershipTitle . ' memorg';
1431 $this->webtestAddOrganization($membershipOrg, TRUE);
1432
1433 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1434 $memTypeParams = array(
1435 'membership_type' => $title,
1436 'member_of_contact' => $membershipOrg,
1437 'financial_type' => 2,
1438 'period_type' => $period_type,
1439 );
1440
1441 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1442
1443 $this->type('name', $memTypeParams['membership_type']);
1444
1445 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1446 // select the radio first since the element id changes after membership org search results are loaded
1447 switch ($auto_renew) {
1448 case 'optional':
1449 $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')]");
1450 break;
1451
1452 case 'required':
1453 $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')]");
1454 break;
1455
1456 default:
1457 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1458 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')]")) {
1459 $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')]");
1460 }
1461 break;
1462 }
1463
1464 $this->select2('member_of_contact_id',$membershipTitle);
1465
1466 $this->type('minimum_fee', '100');
1467 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1468
1469 $this->type('duration_interval', $duration_interval);
1470 $this->select('duration_unit', "label={$duration_unit}");
1471
1472 $this->select('period_type', "value={$period_type}");
1473
1474 $this->click('_qf_MembershipType_upload-bottom');
1475 $this->waitForElementPresent('link=Add Membership Type');
1476 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1477
1478 return $memTypeParams;
1479 }
1480
1481 /**
1482 * @param null $groupName
1483 * @param null $parentGroupName
1484 *
1485 * @return null|string
1486 */
1487 public function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1488 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1489
1490 // fill group name
1491 if (!$groupName) {
1492 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1493 }
1494 $this->type('title', $groupName);
1495
1496 // fill description
1497 $this->type('description', 'Adding new group.');
1498
1499 // check Access Control
1500 $this->click('group_type[1]');
1501
1502 // check Mailing List
1503 $this->click('group_type[2]');
1504
1505 // select Visibility as Public Pages
1506 $this->select('visibility', 'value=Public Pages');
1507
1508 // select parent group
1509 if ($parentGroupName) {
1510 $this->select('parents', "*$parentGroupName");
1511 }
1512
1513 // Clicking save.
1514 $this->clickLink('_qf_Edit_upload-bottom');
1515
1516 // Is status message correct?
1517 $this->waitForText('crm-notification-container', "$groupName");
1518 return $groupName;
1519 }
1520
1521 /**
1522 * @param string $activityType
1523 *
1524 * @return null
1525 */
1526 public function WebtestAddActivity($activityType = "Meeting") {
1527 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1528 // We're using Quick Add block on the main page for this.
1529 $firstName1 = substr(sha1(rand()), 0, 7);
1530 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1531 $firstName2 = substr(sha1(rand()), 0, 7);
1532 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1533
1534 $this->click("css=li#tab_activity a");
1535
1536 // waiting for the activity dropdown to show up
1537 $this->waitForElementPresent("other_activity");
1538
1539 // Select the activity type from the activity dropdown
1540 $this->select("other_activity", "label=Meeting");
1541
1542 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1543 $this->waitForElementPresent("s2id_target_contact_id");
1544
1545 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__);
1546
1547 // Typing contact's name into the field (using typeKeys(), not type()!)...
1548 $this->select2("assignee_contact_id", $firstName1, TRUE);
1549
1550 // ...and verifying if the page contains properly formatted display name for chosen contact.
1551 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__);
1552
1553 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1554 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1555 // For simple input fields we can use field id as selector
1556 $this->type("subject", $subject);
1557 $this->type("location", "Some location needs to be put in this field.");
1558
1559 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1560
1561 // Setting duration.
1562 $this->type("duration", "30");
1563
1564 // Putting in details.
1565 $this->type("details", "Really brief details information.");
1566
1567 // Making sure that status is set to Scheduled (using value, not label).
1568 $this->select("status_id", "value=1");
1569
1570 // Setting priority.
1571 $this->select("priority_id", "value=1");
1572
1573 // Scheduling follow-up.
1574 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1575 $this->select("followup_activity_type_id", "value=1");
1576 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1577 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1578
1579 // Clicking save.
1580 $this->click("_qf_Activity_upload-bottom");
1581 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1582
1583 // Is status message correct?
1584 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1585
1586 $this->waitForElementPresent("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1587
1588 // click through to the Activity view screen
1589 $this->clickLinkSuppressPopup("xpath=//div[@class='dataTables_wrapper no-footer']//table/tbody/tr[2]/td[8]/span/a[text()='View']", '_qf_Activity_cancel-bottom');
1590
1591 // parse URL to grab the activity id
1592 // pass id back to any other tests that call this class
1593 return $this->urlArg('id');
1594 }
1595
1596 /**
1597 * @return bool
1598 */
1599 static
1600 public function checkDoLocalDBTest() {
1601 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1602 CIVICRM_WEBTEST_LOCAL_DB
1603 ) {
1604 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1605 return TRUE;
1606 }
1607 return FALSE;
1608 }
1609
1610 /**
1611 * Generic function to compare expected values after an api call to retrieved
1612 * DB values.
1613 *
1614 * @daoName string DAO Name of object we're evaluating.
1615 * @id int Id of object
1616 * @match array Associative array of field name => expected value. Empty if asserting
1617 * that a DELETE occurred
1618 * @delete boolean True if we're checking that a DELETE action occurred.
1619 */
1620 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
1621 if (!self::checkDoLocalDBTest()) {
1622 return;
1623 }
1624
1625 return CiviDBAssert::assertDBState($this, $daoName, $id, $match, $delete);
1626 }
1627
1628 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1629 /**
1630 * @param string $daoName
1631 * @param $searchValue
1632 * @param $returnColumn
1633 * @param $searchColumn
1634 * @param $message
1635 *
1636 * @return null|string
1637 */
1638 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1639 if (!self::checkDoLocalDBTest()) {
1640 return;
1641 }
1642
1643 return CiviDBAssert::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1644 }
1645
1646 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1647 /**
1648 * @param string $daoName
1649 * @param $searchValue
1650 * @param $returnColumn
1651 * @param $searchColumn
1652 * @param $message
1653 */
1654 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1655 if (!self::checkDoLocalDBTest()) {
1656 return;
1657 }
1658
1659 return CiviDBAssert::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1660 }
1661
1662 // Request a record from the DB by id. Success if row not found.
1663 /**
1664 * @param string $daoName
1665 * @param int $id
1666 * @param $message
1667 */
1668 public function assertDBRowNotExist($daoName, $id, $message) {
1669 if (!self::checkDoLocalDBTest()) {
1670 return;
1671 }
1672
1673 return CiviDBAssert::assertDBRowNotExist($this, $daoName, $id, $message);
1674 }
1675
1676 // Compare a single column value in a retrieved DB record to an expected value
1677 /**
1678 * @param string $daoName
1679 * @param $searchValue
1680 * @param $returnColumn
1681 * @param $searchColumn
1682 * @param $expectedValue
1683 * @param string $message
1684 */
1685 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1686 $expectedValue, $message
1687 ) {
1688 if (!self::checkDoLocalDBTest()) {
1689 return;
1690 }
1691
1692 return CiviDBAssert::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1693 $expectedValue, $message
1694 );
1695 }
1696
1697 // Compare all values in a single retrieved DB record to an array of expected values
1698 /**
1699 * @param string $daoName
1700 * @param array $searchParams
1701 * @param $expectedValues
1702 */
1703 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1704 if (!self::checkDoLocalDBTest()) {
1705 return;
1706 }
1707
1708 return CiviDBAssert::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1709 }
1710
1711 /**
1712 * @param $expectedValues
1713 * @param $actualValues
1714 */
1715 public function assertAttributesEquals(&$expectedValues, &$actualValues) {
1716 if (!self::checkDoLocalDBTest()) {
1717 return;
1718 }
1719
1720 return CiviDBAssert::assertAttributesEquals($expectedValues, $actualValues);
1721 }
1722
1723 /**
1724 * @param $expected
1725 * @param $actual
1726 * @param string $message
1727 */
1728 public function assertType($expected, $actual, $message = '') {
1729 return $this->assertInternalType($expected, $actual, $message);
1730 }
1731
1732 /**
1733 * Add new Financial Account
1734 */
1735 function _testAddFinancialAccount($financialAccountTitle,
1736 $financialAccountDescription = FALSE,
1737 $accountingCode = FALSE,
1738 $firstName = FALSE,
1739 $financialAccountType = FALSE,
1740 $taxDeductible = FALSE,
1741 $isActive = FALSE,
1742 $isTax = FALSE,
1743 $taxRate = FALSE,
1744 $isDefault = FALSE
1745 ) {
1746
1747 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1748
1749 $this->click("link=Add Financial Account");
1750 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1751
1752 // Financial Account Name
1753 $this->type('name', $financialAccountTitle);
1754
1755 // Financial Description
1756 if ($financialAccountDescription) {
1757 $this->type('description', $financialAccountDescription);
1758 }
1759
1760 //Accounting Code
1761 if ($accountingCode) {
1762 $this->type('accounting_code', $accountingCode);
1763 }
1764
1765 // Autofill Organization
1766 if ($firstName) {
1767 $this->webtestOrganisationAutocomplete($firstName);
1768 }
1769
1770 // Financial Account Type
1771 if ($financialAccountType) {
1772 $this->select('financial_account_type_id', "label={$financialAccountType}");
1773 }
1774
1775 // Is Tax Deductible
1776 if ($taxDeductible) {
1777 $this->check('is_deductible');
1778 }
1779 else {
1780 $this->uncheck('is_deductible');
1781 }
1782 // Is Active
1783 if (!$isActive) {
1784 $this->check('is_active');
1785 }
1786 else {
1787 $this->uncheck('is_active');
1788 }
1789 // Is Tax
1790 if ($isTax) {
1791 $this->check('is_tax');
1792 }
1793 else {
1794 $this->uncheck('is_tax');
1795 }
1796 // Tax Rate
1797 if ($taxRate) {
1798 $this->type('tax_rate', $taxRate);
1799 }
1800
1801 // Set Default
1802 if ($isDefault) {
1803 $this->check('is_default');
1804 }
1805 else {
1806 $this->uncheck('is_default');
1807 }
1808 $this->click('_qf_FinancialAccount_next-botttom');
1809 }
1810
1811 /**
1812 * Edit Financial Account
1813 */
1814 function _testEditFinancialAccount($editfinancialAccount,
1815 $financialAccountTitle = FALSE,
1816 $financialAccountDescription = FALSE,
1817 $accountingCode = FALSE,
1818 $firstName = FALSE,
1819 $financialAccountType = FALSE,
1820 $taxDeductible = FALSE,
1821 $isActive = TRUE,
1822 $isTax = FALSE,
1823 $taxRate = FALSE,
1824 $isDefault = FALSE
1825 ) {
1826 if ($firstName) {
1827 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1828 }
1829
1830 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
1831 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1832
1833 // Change Financial Account Name
1834 if ($financialAccountTitle) {
1835 $this->type('name', $financialAccountTitle);
1836 }
1837
1838 // Financial Description
1839 if ($financialAccountDescription) {
1840 $this->type('description', $financialAccountDescription);
1841 }
1842
1843 //Accounting Code
1844 if ($accountingCode) {
1845 $this->type('accounting_code', $accountingCode);
1846 }
1847
1848 // Autofill Edit Organization
1849 if ($firstName) {
1850 $this->webtestOrganisationAutocomplete($firstName);
1851 }
1852
1853 // Financial Account Type
1854 if ($financialAccountType) {
1855 $this->select('financial_account_type_id', "label={$financialAccountType}");
1856 }
1857
1858 // Is Tax Deductible
1859 if ($taxDeductible) {
1860 $this->check('is_deductible');
1861 }
1862 else {
1863 $this->uncheck('is_deductible');
1864 }
1865
1866 // Is Tax
1867 if ($isTax) {
1868 $this->check('is_tax');
1869 }
1870 else {
1871 $this->uncheck('is_tax');
1872 }
1873
1874 // Tax Rate
1875 if ($taxRate) {
1876 $this->type('tax_rate', $taxRate);
1877 }
1878
1879 // Set Default
1880 if ($isDefault) {
1881 $this->check('is_default');
1882 }
1883 else {
1884 $this->uncheck('is_default');
1885 }
1886
1887 // Is Active
1888 if ($isActive) {
1889 $this->check('is_active');
1890 }
1891 else {
1892 $this->uncheck('is_active');
1893 }
1894 $this->click('_qf_FinancialAccount_next-botttom');
1895 $this->waitForElementPresent('link=Add Financial Account');
1896 }
1897
1898 /**
1899 * Delete Financial Account
1900 */
1901 public function _testDeleteFinancialAccount($financialAccountTitle) {
1902 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1903 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1904 $this->click('_qf_FinancialAccount_next-botttom');
1905 $this->waitForElementPresent('link=Add Financial Account');
1906 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1907 }
1908
1909 /**
1910 * Verify data after ADD and EDIT
1911 */
1912 public function _assertFinancialAccount($verifyData) {
1913 foreach ($verifyData as $key => $expectedValue) {
1914 $actualValue = $this->getValue($key);
1915 if ($key == 'parent_financial_account') {
1916 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1917 }
1918 else {
1919 $this->assertEquals($expectedValue, $actualValue);
1920 }
1921 }
1922 }
1923
1924 /**
1925 * @param $verifySelectFieldData
1926 */
1927 public function _assertSelectVerify($verifySelectFieldData) {
1928 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1929 $actualvalue = $this->getSelectedLabel($key);
1930 $this->assertEquals($expectedvalue, $actualvalue);
1931 }
1932 }
1933
1934 /**
1935 * @param $financialType
1936 * @param string $option
1937 */
1938 public function addeditFinancialType($financialType, $option = 'new') {
1939 $this->openCiviPage("admin/financial/financialType", "reset=1");
1940
1941 if ($option == 'Delete') {
1942 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1943 $this->waitForElementPresent("css=span.btn-slide-active");
1944 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1945 $this->waitForElementPresent("_qf_FinancialType_next");
1946 $this->click("_qf_FinancialType_next");
1947 $this->waitForElementPresent("newFinancialType");
1948 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1949 return;
1950 }
1951 if ($option == 'new') {
1952 $this->click("link=Add Financial Type");
1953 }
1954 else {
1955 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1956 }
1957 $this->waitForElementPresent("name");
1958 $this->type('name', $financialType['name']);
1959 if ($option == 'new') {
1960 $this->type('description', $financialType['name'] . ' description');
1961 }
1962
1963 if ($financialType['is_reserved']) {
1964 $this->check('is_reserved');
1965 }
1966 else {
1967 $this->uncheck('is_reserved');
1968 }
1969
1970 if ($financialType['is_deductible']) {
1971 $this->check('is_deductible');
1972 }
1973 else {
1974 $this->uncheck('is_deductible');
1975 }
1976
1977 $this->click('_qf_FinancialType_next');
1978 if ($option == 'new') {
1979 $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.";
1980 }
1981 else {
1982 $text = "The financial type \"{$financialType['name']}\" has been updated.";
1983 }
1984 $this->checkCRMAlert($text);
1985 }
1986
1987 /**
1988 * Give the specified permissions
1989 * Note: this function logs in as 'admin' (logging out if necessary)
1990 */
1991 public function changePermissions($permission) {
1992 $this->webtestLogin('admin');
1993 $this->open("{$this->sboxPath}admin/people/permissions");
1994 $this->waitForElementPresent('edit-submit');
1995 foreach ((array) $permission as $perm) {
1996 $this->check($perm);
1997 }
1998 $this->click('edit-submit');
1999 $this->waitForPageToLoad($this->getTimeoutMsec());
2000 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
2001 }
2002
2003 /**
2004 * @param $profileTitle
2005 * @param $profileFields
2006 */
2007 public function addProfile($profileTitle, $profileFields) {
2008 $this->openCiviPage('admin/uf/group', "reset=1");
2009
2010 $this->clickLink('link=Add Profile', '_qf_Group_cancel-bottom');
2011 $this->type('title', $profileTitle);
2012 $this->clickLink('_qf_Group_next-bottom');
2013
2014 $this->waitForText('crm-notification-container', "Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now.");
2015
2016 foreach ($profileFields as $field) {
2017 $this->waitForElementPresent('field_name_0');
2018 $this->click("id=field_name_0");
2019 $this->select("id=field_name_0", "label=" . $field['type']);
2020 $this->waitForElementPresent('field_name_1');
2021 $this->click("id=field_name_1");
2022 $this->select("id=field_name_1", "label=" . $field['name']);
2023 $this->waitForElementPresent('label');
2024 $this->type("id=label", $field['label']);
2025 $this->click("id=_qf_Field_next_new-top");
2026 $this->waitForElementPresent("xpath=//select[@id='field_name_1'][@style='display: none;']");
2027 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
2028 }
2029 }
2030
2031 /**
2032 * @param string $name
2033 * @param $sku
2034 * @param $amount
2035 * @param $price
2036 * @param $cost
2037 * @param $financialType
2038 */
2039 public function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
2040 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
2041 $this->type("name", $name);
2042 $this->type("sku", $sku);
2043 $this->click("CIVICRM_QFID_noImage_16");
2044 $this->type("min_contribution", $amount);
2045 $this->type("price", $price);
2046 $this->type("cost", $cost);
2047 if ($financialType) {
2048 $this->select("financial_type_id", "label={$financialType}");
2049 }
2050 $this->click("_qf_ManagePremiums_upload-bottom");
2051 $this->waitForPageToLoad($this->getTimeoutMsec());
2052 }
2053
2054 /**
2055 * @param $label
2056 * @param $financialAccount
2057 */
2058 public function addPaymentInstrument($label, $financialAccount) {
2059 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
2060 $this->type("label", $label);
2061 $this->select("financial_account_id", "value=$financialAccount");
2062 $this->click("_qf_Options_next-bottom");
2063 $this->waitForPageToLoad($this->getTimeoutMsec());
2064 }
2065
2066 /**
2067 * Ensure we have a default mailbox set up for CiviMail
2068 */
2069 public function setupDefaultMailbox() {
2070 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
2071 // Check if it hasn't already been set up
2072 if (!$this->getSelectedValue('protocol')) {
2073 $this->type('name', 'Test Domain');
2074 $this->select('protocol', "IMAP");
2075 $this->type('server', 'localhost');
2076 $this->type('domain', 'example.com');
2077 $this->clickLink('_qf_MailSettings_next-top');
2078 }
2079 }
2080
2081 /**
2082 * Determine the default time-out in milliseconds.
2083 *
2084 * @return string, timeout expressed in milliseconds
2085 */
2086 public function getTimeoutMsec() {
2087 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
2088 $timeout = ($this->settings && @$this->settings->timeout) ? ($this->settings->timeout * 1000) : 30000;
2089 return (string) $timeout; // don't know why, but all our old code used a string
2090 }
2091
2092 /**
2093 * CRM-12378
2094 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
2095 *
2096 *
2097 * @param array $customSets
2098 * Custom sets i.e entity wise sets want to be created and checked.
2099 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
2100 'triggerElement' => $triggerElement))
2101 array $triggerElement: the element which is responsible for custom group to load
2102
2103 which uses the entity info as its selection value
2104 * @param array $pageUrl
2105 * The url which on which the ajax custom group load takes place.
2106 * @param callable|boolean $beforeTriggering fn to execute before actual element triggering
2107 * @return void
2108 */
2109 public function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
2110 // FIXME: Testing a theory that these failures have something to do with permissions
2111 $this->webtestLogin('admin');
2112
2113 //add the custom set
2114 $return = $this->addCustomGroupField($customSets);
2115
2116 // FIXME: Hack to ensure caches are properly cleared
2117 if (TRUE) {
2118 $userName = $this->loggedInAs;
2119 $this->webtestLogout();
2120 $this->webtestLogin($userName);
2121 }
2122
2123 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
2124
2125 // FIXME: Try to find out what the heck is going on with these tests
2126 $this->waitForAjaxContent();
2127 $this->checkForErrorsOnPage();
2128
2129 foreach($return as $values) {
2130 foreach ($values as $entityType => $customData) {
2131 //initiate necessary variables
2132 list($entity, $entityData) = explode('_', $entityType);
2133 $elementType = CRM_Utils_Array::value('type', $customData['triggerElement'], 'select');
2134 $elementName = CRM_Utils_Array::value('name', $customData['triggerElement']);
2135 if (is_callable($beforeTriggering)) {
2136 call_user_func($beforeTriggering);
2137 }
2138 if ($elementType == 'select') {
2139 //reset the select box, so triggering of ajax only happens
2140 //WRT input of value in this function
2141 $this->select($elementName, "index=0");
2142 }
2143 if (!empty($entityData)) {
2144 if ($elementType == 'select') {
2145 $this->select($elementName, "label=regexp:{$entityData}");
2146 }
2147 elseif ($elementType == 'checkbox') {
2148 $val = explode(',', $entityData);
2149 foreach($val as $v) {
2150 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2151 $this->check($checkId);
2152 }
2153 }
2154 elseif ($elementType == 'select2') {
2155 $this->select2($elementName, $entityData);
2156 }
2157 }
2158 // FIXME: Try to find out what the heck is going on with these tests
2159 $this->waitForAjaxContent();
2160 $this->checkForErrorsOnPage();
2161
2162 //checking for proper custom data which is loading through ajax
2163 $this->waitForElementPresent("css=.custom-group-{$customData['cgtitle']}");
2164 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2165 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2166 }
2167 }
2168 }
2169
2170 /**
2171 * @param $customSets
2172 *
2173 * @return array
2174 */
2175 public function addCustomGroupField($customSets) {
2176 $return = array();
2177 foreach ($customSets as $customSet) {
2178 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2179
2180 //fill custom group title
2181 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2182 $this->click("title");
2183 $this->type("title", $customGroupTitle);
2184
2185 //custom group extends
2186 $this->click("extends_0");
2187 $this->select("extends_0", "value={$customSet['entity']}");
2188 if (!empty($customSet['subEntity'])) {
2189 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2190 }
2191
2192 // Don't collapse
2193 $this->uncheck('collapse_display');
2194
2195 // Save
2196 $this->click('_qf_Group_next-bottom');
2197
2198 //Is custom group created?
2199 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2200
2201 $gid = $this->urlArg('gid');
2202 $this->waitForTextPresent("{$customGroupTitle} - New Field");
2203
2204 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2205 $this->waitForElementPresent('label');
2206 $this->type('label', $fieldLabel);
2207 $this->click('_qf_Field_done-bottom');
2208
2209 $this->waitForText('crm-notification-container', $fieldLabel);
2210 $this->waitForAjaxContent();
2211
2212 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2213 $return[] = array(
2214 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
2215
2216 // Go home for a sec to give time for caches to clear
2217 $this->openCiviPage('');
2218 }
2219 return $return;
2220 }
2221
2222 /**
2223 * Type and select first occurance of autocomplete
2224 */
2225 public function select2($fieldName,$label, $multiple = FALSE, $xpath=FALSE) {
2226 // In the case of chainSelect, wait for options to load
2227 $this->waitForElementNotPresent('css=select.loading');
2228 if ($multiple) {
2229 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2230 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2231 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2232 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2233 $this->waitForElementPresent("//*[@class='select2-result-label']");
2234 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2235 }
2236 else {
2237 if ($xpath) {
2238 $this->clickAt($fieldName);
2239 }
2240 else {
2241 $this->clickAt("//*[@id='$fieldName']/../div/a");
2242 }
2243 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2244 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2245 $this->type("//*[@id='select2-drop']/div/input", $label);
2246 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
2247 $this->waitForElementPresent("//*[@class='select2-result-label']");
2248 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2249 }
2250 // Wait a sec for select2 to update the original element
2251 sleep(1);
2252 }
2253
2254 /**
2255 * Select multiple options
2256 */
2257 public function multiselect2($fieldid, $params) {
2258 // In the case of chainSelect, wait for options to load
2259 $this->waitForElementNotPresent('css=select.loading');
2260 foreach($params as $value) {
2261 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2262 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2263 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2264 $this->assertElementContainsText("xpath=//*[@id='$fieldid']/preceding-sibling::div[1]/", $value);
2265 }
2266 // Wait a sec for select2 to update the original element
2267 sleep(1);
2268 }
2269
2270 /**
2271 * Check for unobtrusive status message as set by CRM.status
2272 */
2273 public function checkCRMStatus($text=NULL) {
2274 $this->waitForElementPresent("css=.crm-status-box-outer.status-success");
2275 if ($text) {
2276 $this->assertElementContainsText("css=.crm-status-box-outer.status-success", $text);
2277 }
2278 }
2279
2280 /**
2281 * Check for obtrusive status message as set by CRM.alert
2282 */
2283 public function checkCRMAlert($text, $type='success') {
2284 $this->waitForElementPresent("css=div.ui-notify-message.$type");
2285 $this->waitForText("css=div.ui-notify-message.$type", $text);
2286 // We got the message, now let's close it so the webtest doesn't get confused by lots of open alerts
2287 $this->click('css=.ui-notify-cross');
2288 }
2289
2290 /**
2291 * Enable or disable Pop-ups via Display Preferences
2292 */
2293 public function enableDisablePopups($enabled = TRUE) {
2294 $this->openCiviPage('admin/setting/preferences/display', 'reset=1');
2295 $isChecked = $this->isChecked('ajaxPopupsEnabled');
2296 if (($isChecked && !$enabled) || (!$isChecked && $enabled)) {
2297 $this->click('ajaxPopupsEnabled');
2298 }
2299 if ($enabled) {
2300 $this->assertChecked('ajaxPopupsEnabled');
2301 }
2302 else {
2303 $this->assertNotChecked('ajaxPopupsEnabled');
2304 }
2305 $this->clickLink("_qf_Display_next-bottom");
2306 }
2307
2308 /**
2309 * Attempt to get information about what went wrong if we encounter an error when loading a page
2310 */
2311 public function checkForErrorsOnPage() {
2312 foreach (array('Access denied', 'Page not found') as $err) {
2313 if ($this->isElementPresent("xpath=//h1[contains(., '$err')]")) {
2314 $this->fail("'$err' encountered at " . $this->getLocation() . "\nwhile logged in as '{$this->loggedInAs}'");
2315 }
2316 }
2317 if ($this->isElementPresent("xpath=//span[text()='Sorry but we are not able to provide this at the moment.']")) {
2318 $msg = '"Fatal Error" encountered at ' . $this->getLocation();
2319 if ($this->isElementPresent('css=div.crm-section.crm-error-message')) {
2320 $msg .= "\nError Message: " . $this->getText('css=div.crm-section.crm-error-message');
2321 }
2322 $this->fail($msg);
2323 }
2324 }
2325 }