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