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