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