Merge pull request #3623 from monishdeb/CRM-14758-44-fixes
[civicrm-core.git] / tests / phpunit / CiviTest / CiviSeleniumTestCase.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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
6a488035
TO
28require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
29
30/**
31 * Include configuration
32 */
33define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
34define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
aa2733c0 35define('CIVICRM_WEBTEST', 1);
6a488035
TO
36
37if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
38 require_once CIVICRM_SETTINGS_LOCAL_PATH;
39}
40require_once CIVICRM_SETTINGS_PATH;
41
42/**
43 * Base class for CiviCRM Selenium tests
44 *
45 * Common functions for unit tests
46 * @package CiviCRM
47 */
48class CiviSeleniumTestCase extends PHPUnit_Extensions_SeleniumTestCase {
49
42daf119
CW
50 // Current logged-in user
51 protected $loggedInAs = NULL;
6a488035
TO
52
53 /**
54 * Constructor
55 *
56 * Because we are overriding the parent class constructor, we
57 * need to show the same arguments as exist in the constructor of
58 * PHPUnit_Framework_TestCase, since
59 * PHPUnit_Framework_TestSuite::createTest() creates a
60 * ReflectionClass of the Test class and checks the constructor
61 * of that class to decide how to set up the test.
62 *
63 * @param string $name
64 * @param array $data
65 * @param string $dataName
66 */
67 function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
68 parent::__construct($name, $data, $dataName, $browser);
42daf119 69 $this->loggedInAs = NULL;
6a488035
TO
70
71 require_once 'CiviSeleniumSettings.php';
72 $this->settings = new CiviSeleniumSettings();
b5c0ad9a
TO
73 if (property_exists($this->settings, 'serverStartupTimeOut') && $this->settings->serverStartupTimeOut) {
74 global $CiviSeleniumTestCase_polled;
75 if (!$CiviSeleniumTestCase_polled) {
76 $CiviSeleniumTestCase_polled = TRUE;
77 CRM_Utils_Network::waitForServiceStartup(
78 $this->drivers[0]->getHost(),
79 $this->drivers[0]->getPort(),
80 $this->settings->serverStartupTimeOut
81 );
82 }
83 }
6a488035
TO
84
85 // autoload
86 require_once 'CRM/Core/ClassLoader.php';
87 CRM_Core_ClassLoader::singleton()->register();
88
89 // also initialize a connection to the db
42daf119 90 // FIXME: not necessary for most tests, consider moving into functions that need this
6a488035
TO
91 $config = CRM_Core_Config::singleton();
92 }
93
94 protected function setUp() {
95 $this->setBrowser($this->settings->browser);
96 // Make sure that below strings have path separator at the end
97 $this->setBrowserUrl($this->settings->sandboxURL);
98 $this->sboxPath = $this->settings->sandboxPATH;
b5c0ad9a
TO
99 if (property_exists($this->settings, 'rcHost') && $this->settings->rcHost) {
100 $this->setHost($this->settings->rcHost);
101 }
102 if (property_exists($this->settings, 'rcPort') && $this->settings->rcPort) {
103 $this->setPort($this->settings->rcPort);
104 }
6a488035
TO
105 }
106
107 protected function tearDown() {
6a488035
TO
108 }
109
110 /**
111 * Authenticate as drupal user
42daf119
CW
112 * @param $user: (str) the key 'user' or 'admin', or a literal username
113 * @param $pass: (str) if $user is a literal username and not 'user' or 'admin', supply the password
6a488035 114 */
42daf119
CW
115 function webtestLogin($user = 'user', $pass = NULL) {
116 // If already logged in as correct user, do nothing
117 if ($this->loggedInAs === $user) {
118 return;
119 }
120 // If we are logged in as a different user, log out first
121 if ($this->loggedInAs) {
122 $this->webtestLogout();
123 }
6a488035 124 $this->open("{$this->sboxPath}user");
42daf119
CW
125 // Lookup username & password if not supplied
126 $username = $user;
127 if ($pass === NULL) {
128 $pass = $user == 'admin' ? $this->settings->adminPassword : $this->settings->password;
129 $username = $user == 'admin' ? $this->settings->adminUsername : $this->settings->username;
130 }
6a488035
TO
131 // Make sure login form is available
132 $this->waitForElementPresent('edit-submit');
133 $this->type('edit-name', $username);
42daf119 134 $this->type('edit-pass', $pass);
6a488035
TO
135 $this->click('edit-submit');
136 $this->waitForPageToLoad($this->getTimeoutMsec());
42daf119
CW
137 $this->loggedInAs = $user;
138 }
139
140 function webtestLogout() {
141 if ($this->loggedInAs) {
142 $this->open($this->sboxPath . "user/logout");
143 $this->waitForPageToLoad($this->getTimeoutMsec());
144 }
145 $this->loggedInAs = NULL;
6a488035
TO
146 }
147
148 /**
149 * Open an internal path beginning with 'civicrm/'
150 *
151 * @param $url (str) omit the 'civicrm/' it will be added for you
152 * @param $args (str|array) optional url arguments
153 * @param $waitFor - page element to wait for - using this is recommended to ensure the document is fully loaded
154 *
155 * Although it doesn't seem to do much now, using this function is recommended for
156 * opening all civi pages, and using the $args param is also strongly encouraged
157 * This will make it much easier to run webtests in other CMSs in the future
158 */
0bd37c06 159 function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
6a488035
TO
160 // Construct full url with args
161 // This could be extended in future to work with other CMS style urls
162 if ($args) {
163 if (is_array($args)) {
164 $sep = '?';
165 foreach ($args as $key => $val) {
166 $url .= $sep . $key . '=' . $val;
167 $sep = '&';
168 }
169 }
170 else {
171 $url .= "?$args";
172 }
173 }
174 $this->open("{$this->sboxPath}civicrm/$url");
42daf119 175 $this->waitForPageToLoad($this->getTimeoutMsec());
6a488035
TO
176 if ($waitFor) {
177 $this->waitForElementPresent($waitFor);
178 }
179 }
180
b45c587e
CW
181 /**
182 * Click on a link or button
183 * Wait for the page to load
184 * Wait for an element to be present
185 */
28154ee7 186 function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
b45c587e 187 $this->click($element);
28154ee7
PJ
188 // conditional wait for page load e.g for ajax form save
189 if ($waitForPageLoad) {
190 $this->waitForPageToLoad($this->getTimeoutMsec());
191 }
b45c587e
CW
192 if ($waitFor) {
193 $this->waitForElementPresent($waitFor);
194 }
195 }
196
6a488035
TO
197 /**
198 * Call the API on the local server
199 * (kind of defeats the point of a webtest - see CRM-11889)
200 */
201 function webtest_civicrm_api($entity, $action, $params) {
202 if (!isset($params['version'])) {
203 $params['version'] = 3;
204 }
205
206 $result = civicrm_api($entity, $action, $params);
207 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
208 return $result;
209 }
210
211 /**
212 * Call the API on the remote server
213 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
214 * @see CRM-11889
215 */
216 function rest_civicrm_api($entity, $action, $params = array()) {
217 $params += array(
218 'version' => 3,
219 );
220 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
221 $request = array(
222 'http' => array(
223 'method' => 'POST',
224 // Naughty sidestep of civi's security checks
225 'header' => "X-Requested-With: XMLHttpRequest",
226 ),
227 );
228 $ctx = stream_context_create($request);
229 $result = file_get_contents($url, FALSE, $ctx);
230 return json_decode($result, TRUE);
231 }
232
233 function webtestGetFirstValueForOptionGroup($option_group_name) {
234 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
235 'option_group_name' => $option_group_name,
236 'option.limit' => 1,
237 'return' => 'value'
238 ));
239 return $result;
240 }
241
242 function webtestGetValidCountryID() {
243 static $_country_id;
244 if (is_null($_country_id)) {
245 $config_backend = $this->webtestGetConfig('countryLimit');
246 $_country_id = current($config_backend);
247 }
248 return $_country_id;
249 }
250
251 function webtestGetValidEntityID($entity) {
252 // michaelmcandrew: would like to use getvalue but there is a bug
253 // for e.g. group where option.limit not working at the moment CRM-9110
254 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
255 if (!empty($result['values'])) {
256 return current(array_keys($result['values']));
257 }
258 return NULL;
259 }
260
261 function webtestGetConfig($field) {
262 static $_config_backend;
263 if (is_null($_config_backend)) {
264 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
265 'current_domain' => 1,
266 'option.limit' => 1,
267 'return' => 'config_backend'
268 ));
269 $_config_backend = unserialize($result);
270 }
271 return $_config_backend[$field];
272 }
273
1fbd57f8
CW
274 /**
275 * Ensures the required CiviCRM components are enabled
276 */
277 function enableComponents($components) {
278 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
279 $enabledComponents = $this->getSelectOptions("enableComponents-t");
280 $added = FALSE;
281 foreach ((array) $components as $comp) {
282 if (!in_array($comp, $enabledComponents)) {
0bd37c06 283 $this->addSelection("enableComponents-f", "label=$comp");
1fbd57f8
CW
284 $this->click("//option[@value='$comp']");
285 $this->click("add");
286 $added = TRUE;
287 }
288 }
289 if ($added) {
290 $this->click("_qf_Component_next-bottom");
291 $this->waitForPageToLoad($this->getTimeoutMsec());
6c5f7368 292 $this->waitForText('crm-notification-container', "Saved");
1fbd57f8
CW
293 }
294 }
295
6a488035
TO
296 /**
297 * Add a contact with the given first and last names and either a given email
298 * (when specified), a random email (when true) or no email (when unspecified or null).
299 *
300 * @param string $fname contact’s first name
301 * @param string $lname contact’s last name
302 * @param mixed $email contact’s email (when string) or random email (when true) or no email (when null)
303 *
304 * @return mixed either a string with the (either generated or provided) email or null (if no email)
305 */
306 function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
307 $url = $this->sboxPath . 'civicrm/contact/add?reset=1&ct=Individual';
308 if ($contactSubtype) {
309 $url = $url . "&cst={$contactSubtype}";
310 }
311 $this->open($url);
312 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
313 $this->type('first_name', $fname);
314 $this->type('last_name', $lname);
315 if ($email === TRUE) {
316 $email = substr(sha1(rand()), 0, 7) . '@example.org';
317 }
318 if ($email) {
319 $this->type('email_1_email', $email);
320 }
321 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
322 $this->click('_qf_Contact_upload_view-bottom');
323 $this->waitForPageToLoad($this->getTimeoutMsec());
324 return $email;
325 }
326
327 function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
328
b45c587e 329 $this->openCiviPage("contact/add", "reset=1&ct=Household");
6a488035
TO
330 $this->click('household_name');
331 $this->type('household_name', $householdName);
332
333 if ($email === TRUE) {
334 $email = substr(sha1(rand()), 0, 7) . '@example.org';
335 }
336 if ($email) {
337 $this->type('email_1_email', $email);
338 }
339
340 $this->click('_qf_Contact_upload_view');
341 $this->waitForPageToLoad($this->getTimeoutMsec());
342 return $email;
343 }
344
69164898 345 function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
6a488035 346
69164898
N
347 $url = $this->sboxPath . 'civicrm/contact/add?reset=1&ct=Organization';
348 if ($contactSubtype) {
349 $url = $url . "&cst={$contactSubtype}";
350 }
351 $this->open($url);
6a488035
TO
352 $this->click('organization_name');
353 $this->type('organization_name', $organizationName);
354
355 if ($email === TRUE) {
356 $email = substr(sha1(rand()), 0, 7) . '@example.org';
357 }
358 if ($email) {
359 $this->type('email_1_email', $email);
360 }
361 $this->click('_qf_Contact_upload_view');
362 $this->waitForPageToLoad($this->getTimeoutMsec());
363 return $email;
364 }
365
366 /**
367 */
038dc0e3 368 function webtestFillAutocomplete($sortName, $fieldName = 'contact_1') {
369 $this->click($fieldName);
370 $this->type($fieldName, $sortName);
371 $this->typeKeys($fieldName, $sortName);
6a488035
TO
372 $this->waitForElementPresent("css=div.ac_results-inner li");
373 $this->click("css=div.ac_results-inner li");
038dc0e3 374 $this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
6a488035
TO
375 }
376
377 /**
378 */
379 function webtestOrganisationAutocomplete($sortName) {
380 $this->type('contact_name', $sortName);
381 $this->click('contact_name');
382 $this->waitForElementPresent("css=div.ac_results-inner li");
383 $this->click("css=div.ac_results-inner li");
384 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
385 }
386
6a488035
TO
387 /*
388 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
389 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
390 * 3. Examples of $strToTime arguments -
391 * webtestFillDate('start_date',"now")
392 * webtestFillDate('start_date',"10 September 2000")
393 * webtestFillDate('start_date',"+1 day")
394 * webtestFillDate('start_date',"+1 week")
395 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
396 * webtestFillDate('start_date',"next Thursday")
397 * webtestFillDate('start_date',"last Monday")
398 */
399 function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
400 $timeStamp = strtotime($strToTimeArgs ? $strToTimeArgs : '+1 month');
401
402 $year = date('Y', $timeStamp);
403 // -1 ensures month number is inline with calender widget's month
404 $mon = date('n', $timeStamp) - 1;
405 $day = date('j', $timeStamp);
406
407 $this->click("{$dateElement}_display");
408 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
409 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
410 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
411 $this->click("link=$day");
412 }
413
414 // 1. set both date and time.
415 function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
416 $this->webtestFillDate($dateElement, $strToTimeArgs);
417
418 $timeStamp = strtotime($strToTimeArgs ? $strToTimeArgs : '+1 month');
419 $hour = date('h', $timeStamp);
420 $min = date('i', $timeStamp);
421 $meri = date('A', $timeStamp);
422
423 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
424 }
425
426 /**
427 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
428 *
429 * @param array $expected Array of key/value pairs (like Status/Registered) to be checked
430 * @param string $xpathPrefix Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath
431 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
432 * @param string $tableId Pass in the id attribute of a table to be verified if you want to only check a specific table
433 * on the web page.
434 */
435 function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
436 $tableLocator = "";
437 if ($tableId) {
438 $tableLocator = "[@id='$tableId']";
439 }
440 foreach ($expected as $label => $value) {
441 if ($xpathPrefix) {
0054ead7 442 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
6a488035
TO
443 }
444 else {
0054ead7 445 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
6a488035
TO
446 }
447 }
448 }
449
450 /**
451 * Types text into a ckEditor rich text field in a form
452 *
453 * @param string $fieldName form field name (as assigned by PHP buildForm class)
454 * @param string $text text to type into the field
455 * @param string $editor which text editor (valid values are 'CKEditor', 'TinyMCE')
456 *
457 * @return void
458 */
459 function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor') {
460 // make sure cursor focuses on the field
461 $this->fireEvent($fieldName, 'focus');
462 if ($editor == 'CKEditor') {
463 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
464 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
465 }
466 elseif ($editor == 'TinyMCE') {
f97d29d1
RN
467 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
468 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
6a488035
TO
469 }
470 else {
471 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
472 }
473 $this->selectFrame('relative=top');
474 }
475
476 /**
477 * Types option label and name into a table of multiple choice options
478 * (for price set fields of type select, radio, or checkbox)
479 * TODO: extend for custom field multiple choice table input
480 *
481 * @param array $options form field name (as assigned by PHP buildForm class)
482 * @param array $validateStrings appends label and name strings to this array so they can be validated later
483 *
484 * @return void
485 */
486 function addMultipleChoiceOptions($options, &$validateStrings) {
487 foreach ($options as $oIndex => $oValue) {
488 $validateStrings[] = $oValue['label'];
489 $validateStrings[] = $oValue['amount'];
490 if (CRM_Utils_Array::value('membership_type_id', $oValue)) {
491 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
492 }
493 if (CRM_Utils_Array::value('financial_type_id', $oValue)) {
494 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
495 }
496 $this->type("option_label_{$oIndex}", $oValue['label']);
497 $this->type("option_amount_{$oIndex}", $oValue['amount']);
498 $this->click('link=another choice');
499 }
500 }
501
502 /**
503 */
648f9d79 504 function webtestNewDialogContact($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
505 $type = 4, $selectId = 'profiles_1', $row = 1, $prefix = '') {
6a488035
TO
506 // 4 - Individual profile
507 // 5 - Organization profile
508 // 6 - Household profile
509 $this->select($selectId, "value={$type}");
510
511 // create new contact using dialog
648f9d79 512 if (!$prefix) {
513 $this->waitForElementPresent("css=div#contact-dialog-{$row}");
514 }
515 else {
516 $this->waitForElementPresent("css=div#contact-dialog-{$prefix}_{$row}");
517 }
6a488035
TO
518 $this->waitForElementPresent('_qf_Edit_next');
519
520 switch ($type) {
521 case 4:
522 $this->type('first_name', $fname);
523 $this->type('last_name', $lname);
524 break;
525
526 case 5:
527 $this->type('organization_name', $fname);
528 break;
529
530 case 6:
531 $this->type('household_name', $fname);
532 break;
533 }
534
535 $this->type('email-Primary', $email);
536 $this->click('_qf_Edit_next');
537
538 // Is new contact created?
539 if ($lname) {
7c20a3bd 540 $this->assertTrue($this->isTextPresent("$fname $lname has been created."), "Status message didn't show up after saving!");
6a488035
TO
541 }
542 else {
543 $this->assertTrue($this->isTextPresent("$fname has been created."), "Status message didn't show up after saving!");
544 }
545 }
546
547 /**
548 * Generic function to check that strings are present in the page
549 *
550 * @strings array array of strings or a single string
551 *
552 * @return void
553 */
554 function assertStringsPresent($strings) {
555 foreach ((array) $strings as $string) {
556 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
557 }
558 }
559
560 /**
561 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
562 *
563 * @url string url to parse or retrieve current url if null
564 *
565 * @return array returns an associative array containing any of the various components
566 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
567 * http://php.net/manual/en/function.parse-url.php
568 *
569 */
570 function parseURL($url = NULL) {
571 if (!$url) {
572 $url = $this->getLocation();
573 }
574
575 $elements = parse_url($url);
576 if (!empty($elements['query'])) {
577 $elements['queryString'] = array();
578 parse_str($elements['query'], $elements['queryString']);
579 }
580 return $elements;
581 }
582
efb29358
CW
583 /**
584 * Returns a single argument from the url query
585 */
586 function urlArg($arg, $url = NULL) {
587 $elements = $this->parseURL($url);
588 return isset($elements['queryString'][$arg]) ? $elements['queryString'][$arg] : NULL;
589 }
590
6a488035
TO
591 /**
592 * Define a payment processor for use by a webtest. Default is to create Dummy processor
593 * which is useful for testing online public forms (online contribution pages and event registration)
594 *
595 * @param string $processorName Name assigned to new processor
596 * @param string $processorType Name for processor type (e.g. PayPal, Dummy, etc.)
597 * @param array $processorSettings Array of fieldname => value for required settings for the processor
598 *
599 * @return void
600 */
601
602 function webtestAddPaymentProcessor($processorName, $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
603 if (!$processorName) {
604 $this->fail("webTestAddPaymentProcessor requires $processorName.");
605 }
606 if ($processorType == 'Dummy') {
607 $processorSettings = array(
608 'user_name' => 'dummy',
609 'url_site' => 'http://dummy.com',
610 'test_user_name' => 'dummytest',
611 'test_url_site' => 'http://dummytest.com',
612 );
613 }
614 elseif ($processorType == 'AuthNet') {
615 // FIXME: we 'll need to make a new separate account for testing
616 $processorSettings = array(
617 'test_user_name' => '5ULu56ex',
618 'test_password' => '7ARxW575w736eF5p',
619 );
620 }
621 elseif ($processorType == 'Google_Checkout') {
622 // FIXME: we 'll need to make a new separate account for testing
623 $processorSettings = array(
624 'test_user_name' => '559999327053114',
625 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
626 );
627 }
628 elseif ($processorType == 'PayPal') {
629 $processorSettings = array(
630 'test_user_name' => '559999327053114',
631 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
632 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
633 );
634 }
635 elseif ($processorType == 'PayPal_Standard') {
636 $processorSettings = array(
637 'test_user_name' => 'V18ki@9r5Bf.org',
638 );
639 }
640 elseif (empty($processorSettings)) {
641 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
642 }
643 $pid = CRM_Core_DAO::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
644 if (empty($pid)) {
645 $this->fail("$processorType processortype not found.");
646 }
647 $this->open($this->sboxPath . 'civicrm/admin/paymentProcessor?action=add&reset=1&pp=' . $pid);
648 $this->waitForPageToLoad($this->getTimeoutMsec());
649 $this->type('name', $processorName);
650 $this->select('financial_account_id', "label={$financialAccount}");
651
652 foreach ($processorSettings AS $f => $v) {
653 $this->type($f, $v);
654 }
655 $this->click('_qf_PaymentProcessor_next-bottom');
656 $this->waitForPageToLoad($this->getTimeoutMsec());
657 // Is new processor created?
658 $this->assertTrue($this->isTextPresent($processorName), 'Processor name not found in selector after adding payment processor (webTestAddPaymentProcessor).');
659
660 $paymentProcessorId = explode('&id=', $this->getAttribute("xpath=//table[@class='selector']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href"));
661 $paymentProcessorId = explode('&', $paymentProcessorId[1]);
662 return $paymentProcessorId[0];
663 }
664
665 function webtestAddCreditCardDetails() {
666 $this->waitForElementPresent('credit_card_type');
667 $this->select('credit_card_type', 'label=Visa');
668 $this->type('credit_card_number', '4807731747657838');
669 $this->type('cvv2', '123');
670 $this->select('credit_card_exp_date[M]', 'label=Feb');
671 $this->select('credit_card_exp_date[Y]', 'label=2019');
672 }
673
674 function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
675 if (!$firstName) {
676 $firstName = 'John';
677 }
678
679 if (!$middleName) {
680 $middleName = 'Apple';
681 }
682
683 if (!$lastName) {
684 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
685 }
686
687 $this->type('billing_first_name', $firstName);
688 $this->type('billing_middle_name', $middleName);
689 $this->type('billing_last_name', $lastName);
690
691 $this->type('billing_street_address-5', '234 Lincoln Ave');
692 $this->type('billing_city-5', 'San Bernadino');
693 $this->click('billing_state_province_id-5');
694 $this->select('billing_state_province_id-5', 'label=California');
0e6f669d 695 $this->select('billing_country_id-5', 'value=1228');
6a488035
TO
696 $this->type('billing_postal_code-5', '93245');
697
698 return array($firstName, $middleName, $lastName);
699 }
700
701 function webtestAttachFile($fieldLocator, $filePath = NULL) {
702 if (!$filePath) {
703 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
704 $fp = @fopen($filePath, 'w');
705 fputs($fp, 'Test file created by selenium test.');
706 @fclose($fp);
707 }
708
709 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
710
711 $this->attachFile($fieldLocator, "file://{$filePath}");
712
713 return $filePath;
714 }
715
716 function webtestCreateCSV($headers, $rows, $filePath = NULL) {
717 if (!$filePath) {
718 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
719 }
720
721 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
722
723 foreach ($rows as $row) {
724 $temp = array();
725 foreach ($headers as $field => $header) {
726 $temp[$field] = isset($row[$field]) ? '"' . $row[$field] . '"' : '""';
727 }
728 $data .= implode(', ', $temp) . "\r\n";
729 }
730
731 $fp = @fopen($filePath, 'w');
732 @fwrite($fp, $data);
733 @fclose($fp);
734
735 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
736
737 return $filePath;
738 }
739
740 /**
741 * Create new relationship type w/ user specified params or default.
742 *
743 * @param $params array of required params.
744 *
745 * @return an array of saved params values.
746 */
747 function webtestAddRelationshipType($params = array()) {
b45c587e 748 $this->openCiviPage("admin/reltype", "reset=1&action=add");
6a488035
TO
749
750 //build the params if not passed.
751 if (!is_array($params) || empty($params)) {
752 $params = array(
753 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
754 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
755 'contact_types_a' => 'Individual',
756 'contact_types_b' => 'Individual',
757 'description' => 'Test Relationship Type Description',
758 );
759 }
760 //make sure we have minimum required params.
761 if (!isset($params['label_a_b']) || empty($params['label_a_b'])) {
762 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
763 }
764
765 //start the form fill.
766 $this->type('label_a_b', $params['label_a_b']);
767 $this->type('label_b_a', $params['label_b_a']);
768 $this->select('contact_types_a', "value={$params['contact_type_a']}");
769 $this->select('contact_types_b', "value={$params['contact_type_b']}");
770 $this->type('description', $params['description']);
771
772 //save the data.
773 $this->click('_qf_RelationshipType_next-bottom');
774 $this->waitForPageToLoad($this->getTimeoutMsec());
775
776 //does data saved.
777 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
778 "Status message didn't show up after saving!"
779 );
780
b45c587e 781 $this->openCiviPage("admin/reltype", "reset=1");
6a488035
TO
782
783 //validate data on selector.
784 $data = $params;
785 if (isset($data['description'])) {
786 unset($data['description']);
787 }
788 $this->assertStringsPresent($data);
789
790 return $params;
791 }
792
793 /**
794 * Create new online contribution page w/ user specified params or defaults.
b45c587e 795 * FIXME: this function take an absurd number of params - very unwieldy :(
6a488035
TO
796 *
797 * @param User can define pageTitle, hash and rand values for later data verification
798 *
799 * @return $pageId of newly created online contribution page.
800 */
801 function webtestAddContributionPage($hash = NULL,
802 $rand = NULL,
803 $pageTitle = NULL,
804 $processor = array('Dummy Processor' => 'Dummy'),
805 $amountSection = TRUE,
806 $payLater = TRUE,
807 $onBehalf = TRUE,
808 $pledges = TRUE,
809 $recurring = FALSE,
810 $membershipTypes = TRUE,
811 $memPriceSetId = NULL,
812 $friend = TRUE,
813 $profilePreId = 1,
814 $profilePostId = 7,
815 $premiums = TRUE,
816 $widget = TRUE,
817 $pcp = TRUE,
818 $isAddPaymentProcessor = TRUE,
819 $isPcpApprovalNeeded = FALSE,
820 $isSeparatePayment = FALSE,
821 $honoreeSection = TRUE,
822 $allowOtherAmmount = TRUE,
823 $isConfirmEnabled = TRUE,
1019390e
PN
824 $financialType = 'Donation',
825 $fixedAmount = TRUE,
826 $membershipsRequired = TRUE
6a488035
TO
827 ) {
828 if (!$hash) {
829 $hash = substr(sha1(rand()), 0, 7);
830 }
831 if (!$pageTitle) {
832 $pageTitle = 'Donate Online ' . $hash;
833 }
834
835 if (!$rand) {
836 $rand = 2 * rand(2, 50);
837 }
838
839 // Create a new payment processor if requested
840 if ($isAddPaymentProcessor) {
841 while (list($processorName, $processorType) = each($processor)) {
842 $this->webtestAddPaymentProcessor($processorName, $processorType);
843 }
844 }
845
846 // go to the New Contribution Page page
b45c587e 847 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
6a488035
TO
848
849 // fill in step 1 (Title and Settings)
850 $this->type('title', $pageTitle);
851
852 //to select financial type
853 $this->select('financial_type_id', "label={$financialType}");
854
855 if ($onBehalf) {
856 $this->click('is_organization');
857 $this->select('onbehalf_profile_id', 'label=On Behalf Of Organization');
858 $this->type('for_organization', "On behalf $hash");
859
860 if ($onBehalf == 'required') {
861 $this->click('CIVICRM_QFID_2_4');
862 }
863 elseif ($onBehalf == 'optional') {
864 $this->click('CIVICRM_QFID_1_2');
865 }
866 }
867
868 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
869 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
870
871 $this->type('goal_amount', 10 * $rand);
872
873 // FIXME: handle Start/End Date/Time
874 if ($honoreeSection) {
875 $this->click('honor_block_is_active');
876 $this->type('honor_block_title', "Honoree Section Title $hash");
877 $this->type('honor_block_text', "Honoree Introductory Message $hash");
878 }
879
880 // is confirm enabled? it starts out enabled, so uncheck it if false
881 if (!$isConfirmEnabled) {
882 $this->click("id=is_confirm_enabled");
883 }
884
b45c587e
CW
885 // Submit form
886 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
887
888 // Get contribution page id
889 $pageId = $this->urlArg('id');
6a488035
TO
890
891 // fill in step 2 (Processor, Pay Later, Amounts)
892 if (!empty($processor)) {
893 reset($processor);
894 while (list($processorName) = each($processor)) {
895 // select newly created processor
896 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
897 $this->assertTrue($this->isTextPresent($processorName));
898 $this->check($xpath);
899 }
900 }
901
902 if ($amountSection && !$memPriceSetId) {
903 if ($payLater) {
904 $this->click('is_pay_later');
905 $this->type('pay_later_text', "Pay later label $hash");
3c001b0e 906 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
6a488035
TO
907 }
908
909 if ($pledges) {
910 $this->click('is_pledge_active');
911 $this->click('pledge_frequency_unit[week]');
912 $this->click('is_pledge_interval');
913 $this->type('initial_reminder_day', 3);
914 $this->type('max_reminders', 2);
915 $this->type('additional_reminder_day', 1);
916 }
917 elseif ($recurring) {
918 $this->click('is_recur');
919 $this->click("is_recur_interval");
920 $this->click("is_recur_installments");
921 }
922 if ($allowOtherAmmount) {
923
924 $this->click('is_allow_other_amount');
925
926 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
927 //$this->type('min_amount', $rand / 2);
928 //$this->type('max_amount', $rand * 10);
929 }
1019390e
PN
930 if ($fixedAmount || !$allowOtherAmmount) {
931 $this->type('label_1', "Label $hash");
932 $this->type('value_1', "$rand");
933 }
6a488035
TO
934 $this->click('CIVICRM_QFID_1_2');
935 }
936 else {
937 $this->click('amount_block_is_active');
938 }
939
940 $this->click('_qf_Amount_next');
941 $this->waitForElementPresent('_qf_Amount_next-bottom');
942 $this->waitForPageToLoad($this->getTimeoutMsec());
943 $text = "'Amount' information has been saved.";
944 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
945
946 if ($memPriceSetId || (($membershipTypes === TRUE) || (is_array($membershipTypes) && !empty($membershipTypes)))) {
947 // go to step 3 (memberships)
948 $this->click('link=Memberships');
949 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
950
951 // fill in step 3 (Memberships)
952 $this->click('member_is_active');
953 $this->waitForElementPresent('displayFee');
954 $this->type('new_title', "Title - New Membership $hash");
955 $this->type('renewal_title', "Title - Renewals $hash");
956
957 if ($memPriceSetId) {
958 $this->click('member_price_set_id');
959 $this->select('member_price_set_id', "value={$memPriceSetId}");
960 }
961 else {
962 if ($membershipTypes === TRUE) {
963 $membershipTypes = array(array('id' => 2));
964 }
965
966 // FIXME: handle Introductory Message - New Memberships/Renewals
967 foreach ($membershipTypes as $mType) {
968 $this->click("membership_type_{$mType['id']}");
969 if (array_key_exists('default', $mType)) {
970 // FIXME:
971 }
972 if (array_key_exists('auto_renew', $mType)) {
973 $this->select("auto_renew_{$mType['id']}", "label=Give option");
974 }
975 }
1019390e
PN
976 if ($membershipsRequired) {
977 $this->click('is_required');
978 }
6a488035
TO
979 $this->waitForElementPresent('CIVICRM_QFID_2_4');
980 $this->click('CIVICRM_QFID_2_4');
981 if ($isSeparatePayment) {
982 $this->click('is_separate_payment');
983 }
984 }
225a8648 985 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
6a488035
TO
986 $text = "'MembershipBlock' information has been saved.";
987 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
988 }
989
990 // go to step 4 (thank-you and receipting)
991 $this->click('link=Receipt');
992 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
993
994 // fill in step 4
995 $this->type('thankyou_title', "Thank-you Page Title $hash");
996 // FIXME: handle Thank-you Message/Page Footer
997 $this->type('receipt_from_name', "Receipt From Name $hash");
998 $this->type('receipt_from_email', "$hash@example.org");
999 $this->type('receipt_text', "Receipt Message $hash");
1000 $this->type('cc_receipt', "$hash@example.net");
1001 $this->type('bcc_receipt', "$hash@example.com");
1002
1003 $this->click('_qf_ThankYou_next');
1004 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1005 $this->waitForPageToLoad($this->getTimeoutMsec());
1006 $text = "'ThankYou' information has been saved.";
1007 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1008
1009 if ($friend) {
1010 // fill in step 5 (Tell a Friend)
1011 $this->click('link=Tell a Friend');
1012 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1013 $this->click('tf_is_active');
1014 $this->type('tf_title', "TaF Title $hash");
1015 $this->type('intro', "TaF Introduction $hash");
1016 $this->type('suggested_message', "TaF Suggested Message $hash");
1017 $this->type('general_link', "TaF Info Page Link $hash");
1018 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1019 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1020
1021 //$this->click('_qf_Contribute_next');
1022 $this->click('_qf_Contribute_next-bottom');
1023 $this->waitForPageToLoad($this->getTimeoutMsec());
1024 $text = "'Friend' information has been saved.";
1025 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1026 }
1027
1028 if ($profilePreId || $profilePostId) {
1029 // fill in step 6 (Include Profiles)
1030 $this->click('css=li#tab_custom a');
1031 $this->waitForElementPresent('_qf_Custom_next-bottom');
1032
1033 if ($profilePreId) {
1034 $this->select('custom_pre_id', "value={$profilePreId}");
1035 }
1036
1037 if ($profilePostId) {
1038 $this->select('custom_post_id', "value={$profilePostId}");
1039 }
1040
1041 $this->click('_qf_Custom_next-bottom');
1042 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1043
1044 $this->waitForPageToLoad($this->getTimeoutMsec());
1045 $text = "'Custom' information has been saved.";
1046 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1047 }
1048
1049 if ($premiums) {
1050 // fill in step 7 (Premiums)
1051 $this->click('link=Premiums');
1052 $this->waitForElementPresent('_qf_Premium_next-bottom');
1053 $this->click('premiums_active');
1054 $this->type('premiums_intro_title', "Prem Title $hash");
1055 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1056 $this->type('premiums_contact_email', "$hash@example.info");
1057 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1058 $this->click('premiums_display_min_contribution');
1059 $this->type('premiums_nothankyou_label', 'No thank-you');
1060 $this->click('_qf_Premium_next');
1061 $this->waitForElementPresent('_qf_Premium_next-bottom');
1062
1063 $this->waitForPageToLoad($this->getTimeoutMsec());
1064 $text = "'Premium' information has been saved.";
1065 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1066 }
1067
6a488035
TO
1068 if ($widget) {
1069 // fill in step 8 (Widget Settings)
1070 $this->click('link=Widgets');
1071 $this->waitForElementPresent('_qf_Widget_next-bottom');
1072
1073 $this->click('is_active');
1074 $this->type('url_logo', "URL to Logo Image $hash");
1075 $this->type('button_title', "Button Title $hash");
1076 // Type About text in ckEditor (fieldname, text to type, editor)
1077 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1078
1079 $this->click('_qf_Widget_next');
1080 $this->waitForElementPresent('_qf_Widget_next-bottom');
1081
1082 $this->waitForPageToLoad($this->getTimeoutMsec());
1083 $text = "'Widget' information has been saved.";
1084 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1085 }
1086
1087 if ($pcp) {
1088 // fill in step 9 (Enable Personal Campaign Pages)
1089 $this->click('link=Personal Campaigns');
1090 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1091 $this->click('pcp_active');
1092 if (!$isPcpApprovalNeeded) {
1093 $this->click('is_approval_needed');
1094 }
1095 $this->type('notify_email', "$hash@example.name");
1096 $this->select('supporter_profile_id', 'value=2');
1097 $this->type('tellfriend_limit', 7);
1098 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1099
1100 $this->click('_qf_Contribute_next-bottom');
1101 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1102 $this->waitForPageToLoad($this->getTimeoutMsec());
1103 $text = "'Pcp' information has been saved.";
1104 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1105 }
1106
b45c587e 1107 return $pageId;
6a488035
TO
1108 }
1109
1110 /**
1111 * Function to update default strict rule.
1112 *
1113 * @params string $contactType Contact type
1114 * @param array $fields Fields to be set for strict rule
1115 * @param Integer $threshold Rule's threshold value
1116 */
1117 function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1118 // set default strict rule.
1119 $strictRuleId = 4;
1120 if ($contactType == 'Organization') {
1121 $strictRuleId = 5;
1122 }
1123 elseif ($contactType == 'Household') {
1124 $strictRuleId = 6;
1125 }
1126
1127 // Default dedupe fields for each Contact type.
1128 if (empty($fields)) {
1129 $fields = array('civicrm_email.email' => 10);
1130 if ($contactType == 'Organization') {
1131 $fields = array(
1132 'civicrm_contact.organization_name' => 10,
1133 'civicrm_email.email' => 10,
1134 );
1135 }
1136 elseif ($contactType == 'Household') {
1137 $fields = array(
1138 'civicrm_contact.household_name' => 10,
1139 'civicrm_email.email' => 10,
1140 );
1141 }
1142 }
1143
b45c587e 1144 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
6a488035
TO
1145
1146 $count = 0;
1147 foreach ($fields as $field => $weight) {
1148 $this->select("where_{$count}", "value={$field}");
1149 $this->type("length_{$count}", '');
1150 $this->type("weight_{$count}", $weight);
1151 $count++;
1152 }
1153
1154 if ($count > 4) {
1155 $this->type('threshold', $threshold);
1156 // click save
1157 $this->click('_qf_DedupeRules_next-bottom');
1158 $this->waitForPageToLoad($this->getTimeoutMsec());
1159 return;
1160 }
1161
1162 for ($i = $count; $i <= 4; $i++) {
1163 $this->select("where_{$i}", 'label=- none -');
1164 $this->type("length_{$i}", '');
1165 $this->type("weight_{$i}", '');
1166 }
1167
1168 $this->type('threshold', $threshold);
1169
1170 // click save
1171 $this->click('_qf_DedupeRules_next-bottom');
1172 $this->waitForPageToLoad($this->getTimeoutMsec());
1173 }
1174
1175 function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1176 $membershipTitle = substr(sha1(rand()), 0, 7);
1177 $membershipOrg = $membershipTitle . ' memorg';
1178 $this->webtestAddOrganization($membershipOrg, TRUE);
1179
1180 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1181 $memTypeParams = array(
1182 'membership_type' => $title,
1183 'member_of_contact' => $membershipOrg,
1184 'financial_type' => 2,
1185 'period_type' => $period_type,
1186 );
1187
42daf119 1188 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
6a488035
TO
1189
1190 $this->type('name', $memTypeParams['membership_type']);
1191
1192 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1193 // select the radio first since the element id changes after membership org search results are loaded
1194 switch ($auto_renew) {
1195 case 'optional':
1196 $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')]");
1197 break;
1198
1199 case 'required':
1200 $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')]");
1201 break;
1202
1203 default:
1204 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1205 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')]")) {
1206 $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')]");
1207 }
1208 break;
1209 }
1210
1211 $this->type('member_of_contact', $membershipTitle);
1212 $this->click('member_of_contact');
1213 $this->waitForElementPresent("css=div.ac_results-inner li");
1214 $this->click("css=div.ac_results-inner li");
1215
1216 $this->type('minimum_fee', '100');
1217 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1218
1219 $this->type('duration_interval', $duration_interval);
1220 $this->select('duration_unit', "label={$duration_unit}");
1221
1222 $this->select('period_type', "label={$period_type}");
1223
1224 $this->click('_qf_MembershipType_upload-bottom');
1225 $this->waitForElementPresent('link=Add Membership Type');
1226 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1227
1228 return $memTypeParams;
1229 }
1230
1231 function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1232 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1233
1234 // fill group name
1235 if (!$groupName) {
1236 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1237 }
1238 $this->type('title', $groupName);
1239
1240 // fill description
1241 $this->type('description', 'Adding new group.');
1242
1243 // check Access Control
1244 $this->click('group_type[1]');
1245
1246 // check Mailing List
1247 $this->click('group_type[2]');
1248
1249 // select Visibility as Public Pages
1250 $this->select('visibility', 'value=Public Pages');
1251
1252 // select parent group
1253 if ($parentGroupName) {
1254 $this->select('parents', "*$parentGroupName");
1255 }
1256
1257 // Clicking save.
225a8648 1258 $this->clickLink('_qf_Edit_upload-bottom');
6a488035
TO
1259
1260 // Is status message correct?
6c5f7368 1261 $this->waitForText('crm-notification-container', "$groupName");
6a488035
TO
1262 return $groupName;
1263 }
1264
1265 function WebtestAddActivity($activityType = "Meeting") {
1266 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1267 // We're using Quick Add block on the main page for this.
1268 $firstName1 = substr(sha1(rand()), 0, 7);
1269 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1270 $firstName2 = substr(sha1(rand()), 0, 7);
1271 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1272
6a488035
TO
1273 $this->click("css=li#tab_activity a");
1274
1275 // waiting for the activity dropdown to show up
1276 $this->waitForElementPresent("other_activity");
1277
1278 // Select the activity type from the activity dropdown
1279 $this->select("other_activity", "label=Meeting");
1280
1281 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1282
1283 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__);
1284
1285 // Typing contact's name into the field (using typeKeys(), not type()!)...
1286 $this->click("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id");
1287 $this->type("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id", $firstName1);
1288 $this->typeKeys("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id", $firstName1);
1289
1290 // ...waiting for drop down with results to show up...
1291 $this->waitForElementPresent("css=div.token-input-dropdown-facebook");
1292 $this->waitForElementPresent("css=li.token-input-input-token-facebook");
1293
1294 //.need to use mouseDown on first result (which is a li element), click does not work
1295 // Note that if you are using firebug this appears at the bottom of the html source, before the closing </body> tag, not where the <li> referred to above is, which is a different <li>.
1296 $this->waitForElementPresent("css=div.token-input-dropdown-facebook li");
1297 $this->mouseDown("css=div.token-input-dropdown-facebook li");
1298
1299 // ...again, waiting for the box with contact name to show up...
1300 $this->waitForElementPresent("css=tr.crm-activity-form-block-assignee_contact_id td ul li span.token-input-delete-token-facebook");
1301
1302 // ...and verifying if the page contains properly formatted display name for chosen contact.
1303 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__);
1304
1305 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1306 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1307 // For simple input fields we can use field id as selector
1308 $this->type("subject", $subject);
1309 $this->type("location", "Some location needs to be put in this field.");
1310
1311 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1312
1313 // Setting duration.
1314 $this->type("duration", "30");
1315
1316 // Putting in details.
1317 $this->type("details", "Really brief details information.");
1318
1319 // Making sure that status is set to Scheduled (using value, not label).
1320 $this->select("status_id", "value=1");
1321
1322 // Setting priority.
1323 $this->select("priority_id", "value=1");
1324
1325 // Scheduling follow-up.
1326 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1327 $this->select("followup_activity_type_id", "value=1");
1328 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1329 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1330
1331 // Clicking save.
1332 $this->click("_qf_Activity_upload-bottom");
1333 $this->waitForPageToLoad($this->getTimeoutMsec());
1334
1335 // Is status message correct?
1336 $this->assertTrue($this->isTextPresent("Activity '$subject' has been saved."), "Status message didn't show up after saving!");
1337
da2fd2e8 1338 $this->waitForElementPresent("xpath=//div[@id='Activities']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
6a488035
TO
1339
1340 // click through to the Activity view screen
da2fd2e8 1341 $this->click("xpath=//div[@id='Activities']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
6a488035 1342 $this->waitForElementPresent('_qf_Activity_cancel-bottom');
76e86fd8 1343
efb29358
CW
1344 // parse URL to grab the activity id
1345 // pass id back to any other tests that call this class
1346 return $this->urlArg('id');
6a488035
TO
1347 }
1348
1349 static
1350 function checkDoLocalDBTest() {
1351 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1352 CIVICRM_WEBTEST_LOCAL_DB
1353 ) {
1354 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1355 return TRUE;
1356 }
1357 return FALSE;
1358 }
1359
1360 /**
1361 * Generic function to compare expected values after an api call to retrieved
1362 * DB values.
1363 *
1364 * @daoName string DAO Name of object we're evaluating.
1365 * @id int Id of object
1366 * @match array Associative array of field name => expected value. Empty if asserting
1367 * that a DELETE occurred
1368 * @delete boolean True if we're checking that a DELETE action occurred.
1369 */
1370 function assertDBState($daoName, $id, $match, $delete = FALSE) {
1371 if (!self::checkDoLocalDBTest()) {
1372 return;
1373 }
1374
1375 return CiviDBAssert::assertDBState($this, $daoName, $id, $match, $delete);
1376 }
1377
1378 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1379 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1380 if (!self::checkDoLocalDBTest()) {
1381 return;
1382 }
1383
1384 return CiviDBAssert::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1385 }
1386
1387 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1388 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1389 if (!self::checkDoLocalDBTest()) {
1390 return;
1391 }
1392
1393 return CiviDBAssert::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1394 }
1395
1396 // Request a record from the DB by id. Success if row not found.
1397 function assertDBRowNotExist($daoName, $id, $message) {
1398 if (!self::checkDoLocalDBTest()) {
1399 return;
1400 }
1401
1402 return CiviDBAssert::assertDBRowNotExist($this, $daoName, $id, $message);
1403 }
1404
1405 // Compare a single column value in a retrieved DB record to an expected value
1406 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1407 $expectedValue, $message
1408 ) {
1409 if (!self::checkDoLocalDBTest()) {
1410 return;
1411 }
1412
1413 return CiviDBAssert::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1414 $expectedValue, $message
1415 );
1416 }
1417
1418 // Compare all values in a single retrieved DB record to an array of expected values
1419 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1420 if (!self::checkDoLocalDBTest()) {
1421 return;
1422 }
1423
1424 return CiviDBAssert::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1425 }
1426
1427 function assertAttributesEquals(&$expectedValues, &$actualValues) {
1428 if (!self::checkDoLocalDBTest()) {
1429 return;
1430 }
1431
1432 return CiviDBAssert::assertAttributesEquals($expectedValues, $actualValues);
1433 }
1434
1435 function assertType($expected, $actual, $message = '') {
1436 return $this->assertInternalType($expected, $actual, $message);
1437 }
1438
6a488035
TO
1439 /**
1440 * Add new Financial Account
1441 */
6a488035
TO
1442 function _testAddFinancialAccount($financialAccountTitle,
1443 $financialAccountDescription = FALSE,
1444 $accountingCode = FALSE,
1445 $firstName = FALSE,
1446 $financialAccountType = FALSE,
1447 $taxDeductible = FALSE,
1448 $isActive = FALSE,
1449 $isTax = FALSE,
1450 $taxRate = FALSE,
1451 $isDefault = FALSE
1452 ) {
1453
b45c587e 1454 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
6a488035
TO
1455
1456 $this->click("link=Add Financial Account");
1457 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1458
1459 // Financial Account Name
1460 $this->type('name', $financialAccountTitle);
1461
1462 // Financial Description
1463 if ($financialAccountDescription) {
1464 $this->type('description', $financialAccountDescription);
1465 }
1466
1467 //Accounting Code
1468 if ($accountingCode) {
1469 $this->type('accounting_code', $accountingCode);
1470 }
1471
1472 // Autofill Organization
1473 if ($firstName) {
1474 $this->webtestOrganisationAutocomplete($firstName);
1475 }
1476
1477 // Financial Account Type
1478 if ($financialAccountType) {
1479 $this->select('financial_account_type_id', "label={$financialAccountType}");
1480 }
1481
1482 // Is Tax Deductible
1483 if ($taxDeductible) {
1484 $this->check('is_deductible');
1485 }
1486 else {
1487 $this->uncheck('is_deductible');
1488 }
1489 // Is Active
1490 if (!$isActive) {
1491 $this->check('is_active');
1492 }
1493 else {
1494 $this->uncheck('is_active');
1495 }
1496 // Is Tax
1497 if ($isTax) {
1498 $this->check('is_tax');
1499 }
1500 else {
1501 $this->uncheck('is_tax');
1502 }
1503 // Tax Rate
1504 if ($taxRate) {
1505 $this->type('tax_rate', $taxRate);
1506 }
1507
1508 // Set Default
1509 if ($isDefault) {
1510 $this->check('is_default');
1511 }
1512 else {
1513 $this->uncheck('is_default');
1514 }
1515 $this->click('_qf_FinancialAccount_next-botttom');
1516 $this->waitForPageToLoad($this->getTimeoutMsec());
1517 }
1518
6a488035
TO
1519 /**
1520 * Edit Financial Account
1521 */
1522 function _testEditFinancialAccount($editfinancialAccount,
1523 $financialAccountTitle = FALSE,
1524 $financialAccountDescription = FALSE,
1525 $accountingCode = FALSE,
1526 $firstName = FALSE,
1527 $financialAccountType = FALSE,
1528 $taxDeductible = FALSE,
1529 $isActive = TRUE,
1530 $isTax = FALSE,
1531 $taxRate = FALSE,
1532 $isDefault = FALSE
1533 ) {
1534 if ($firstName) {
b45c587e 1535 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
6a488035
TO
1536 }
1537
1538 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
225a8648 1539 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom');
6a488035
TO
1540
1541 // Change Financial Account Name
1542 if ($financialAccountTitle) {
1543 $this->type('name', $financialAccountTitle);
1544 }
1545
1546 // Financial Description
1547 if ($financialAccountDescription) {
1548 $this->type('description', $financialAccountDescription);
1549 }
1550
1551 //Accounting Code
1552 if ($accountingCode) {
1553 $this->type('accounting_code', $accountingCode);
1554 }
1555
6a488035
TO
1556 // Autofill Edit Organization
1557 if ($firstName) {
1558 $this->webtestOrganisationAutocomplete($firstName);
1559 }
1560
1561 // Financial Account Type
1562 if ($financialAccountType) {
1563 $this->select('financial_account_type_id', "label={$financialAccountType}");
1564 }
1565
1566 // Is Tax Deductible
1567 if ($taxDeductible) {
1568 $this->check('is_deductible');
1569 }
1570 else {
1571 $this->uncheck('is_deductible');
1572 }
1573
1574 // Is Tax
1575 if ($isTax) {
1576 $this->check('is_tax');
1577 }
1578 else {
1579 $this->uncheck('is_tax');
1580 }
1581
1582 // Tax Rate
1583 if ($taxRate) {
1584 $this->type('tax_rate', $taxRate);
1585 }
1586
1587 // Set Default
1588 if ($isDefault) {
1589 $this->check('is_default');
1590 }
1591 else {
1592 $this->uncheck('is_default');
1593 }
1594
1595 // Is Active
1596 if ($isActive) {
1597 $this->check('is_active');
1598 }
1599 else {
1600 $this->uncheck('is_active');
1601 }
1602 $this->click('_qf_FinancialAccount_next-botttom');
1603 $this->waitForPageToLoad($this->getTimeoutMsec());
1604 }
1605
6a488035
TO
1606 /**
1607 * Delete Financial Account
1608 */
1609 function _testDeleteFinancialAccount($financialAccountTitle) {
1610 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1611 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1612 $this->click('_qf_FinancialAccount_next-botttom');
1613 $this->waitForElementPresent('link=Add Financial Account');
1614 $this->assertTrue($this->isTextPresent("Selected Financial Account has been deleted."));
1615 }
1616
1617 /**
1618 * Verify data after ADD and EDIT
1619 */
1620 function _assertFinancialAccount($verifyData) {
1621 foreach ($verifyData as $key => $expectedValue) {
1622 $actualValue = $this->getValue($key);
1623 if ($key == 'parent_financial_account') {
1624 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1625 }
1626 else {
1627 $this->assertEquals($expectedValue, $actualValue);
1628 }
1629 }
1630 }
1631
1632 function _assertSelectVerify($verifySelectFieldData) {
1633 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1634 $actualvalue = $this->getSelectedLabel($key);
1635 $this->assertEquals($expectedvalue, $actualvalue);
1636 }
1637 }
1638
1639 function addeditFinancialType($financialType, $option = 'new') {
b45c587e 1640 $this->openCiviPage("admin/financial/financialType", "reset=1");
6a488035
TO
1641
1642 if ($option == 'Delete') {
1643 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1644 $this->waitForElementPresent("css=span.btn-slide-active");
1645 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1646 $this->waitForElementPresent("_qf_FinancialType_next");
1647 $this->click("_qf_FinancialType_next");
1648 $this->waitForPageToLoad($this->getTimeoutMsec());
1649 $this->assertTrue($this->isTextPresent('Selected financial type has been deleted.'), 'Missing text: ' . 'Selected financial type has been deleted.');
1650 return;
1651 }
1652 if ($option == 'new') {
1653 $this->click("link=Add Financial Type");
1654 }
1655 else {
1656 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1657 }
1658 $this->waitForPageToLoad($this->getTimeoutMsec());
1659 $this->type('name', $financialType['name']);
1660 if ($option == 'new') {
1661 $this->type('description', $financialType['name'] . ' description');
1662 }
1663
1664 if ($financialType['is_reserved']) {
1665 $this->check('is_reserved');
1666 }
1667 else {
1668 $this->uncheck('is_reserved');
1669 }
1670
1671 if ($financialType['is_deductible']) {
1672 $this->check('is_deductible');
1673 }
1674 else {
1675 $this->uncheck('is_deductible');
1676 }
1677
1678 $this->click('_qf_FinancialType_next');
1679 $this->waitForPageToLoad($this->getTimeoutMsec());
1680 if ($option == 'new') {
f17d75bb 1681 $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.";
6a488035
TO
1682 }
1683 else {
1684 $text = "The financial type '{$financialType['name']}' has been saved.";
1685 }
1686 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1687 }
1688
42daf119
CW
1689 /**
1690 * Give the specified permissions
b45c587e 1691 * Note: this function logs in as 'admin' (logging out if necessary)
42daf119 1692 */
6a488035 1693 function changePermissions($permission) {
42daf119
CW
1694 $this->webtestLogin('admin');
1695 $this->open("{$this->sboxPath}admin/people/permissions");
6a488035 1696 $this->waitForElementPresent('edit-submit');
42daf119
CW
1697 foreach ((array) $permission as $perm) {
1698 $this->check($perm);
6a488035
TO
1699 }
1700 $this->click('edit-submit');
1701 $this->waitForPageToLoad($this->getTimeoutMsec());
1702 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
6a488035
TO
1703 }
1704
1705 function addProfile($profileTitle, $profileFields) {
42daf119 1706 $this->openCiviPage('admin/uf/group', "reset=1");
6a488035 1707
6a488035
TO
1708 $this->click('link=Add Profile');
1709
1710 // Add membership custom data field to profile
1711 $this->waitForElementPresent('_qf_Group_cancel-bottom');
1712 $this->type('title', $profileTitle);
1713 $this->click('_qf_Group_next-bottom');
1714
1715 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1716 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now."));
1717
1718 foreach ($profileFields as $field) {
1719 $this->waitForElementPresent('field_name_0');
1720 // $this->waitForPageToLoad($this->getTimeoutMsec());
1721 $this->click("id=field_name_0");
1722 $this->select("id=field_name_0", "label=" . $field['type']);
1723 $this->waitForElementPresent('field_name_1');
1724 $this->click("id=field_name_1");
1725 $this->select("id=field_name_1", "label=" . $field['name']);
1726 $this->waitForElementPresent('label');
1727 $this->type("id=label", $field['label']);
1728 $this->click("id=_qf_Field_next_new-top");
1729 $this->waitForPageToLoad($this->getTimeoutMsec());
1730 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
1731 }
1732 }
1733
6a488035
TO
1734 function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
1735 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
1736 $this->type("name", $name);
1737 $this->type("sku", $sku);
1738 $this->click("CIVICRM_QFID_noImage_16");
1739 $this->type("min_contribution", $amount);
1740 $this->type("price", $price);
1741 $this->type("cost", $cost);
1742 if ($financialType) {
1743 $this->select("financial_type_id", "label={$financialType}");
1744 }
1745 $this->click("_qf_ManagePremiums_upload-bottom");
1746 $this->waitForPageToLoad($this->getTimeoutMsec());
1747 }
1748
1749 function addPaymentInstrument($label, $financialAccount) {
24afed26 1750 $this->openCiviPage('admin/options/payment_instrument', 'group=payment_instrument&action=add&reset=1', "_qf_Options_next-bottom");
6a488035
TO
1751 $this->type("label", $label);
1752 $this->select("financial_account_id", "value=$financialAccount");
1753 $this->click("_qf_Options_next-bottom");
1754 $this->waitForPageToLoad($this->getTimeoutMsec());
1755 }
1756
5ff68892
CW
1757 /**
1758 * Ensure we have a default mailbox set up for CiviMail
1759 */
1760 function setupDefaultMailbox() {
1761 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
1762 // Check if it hasn't already been set up
1763 if (!$this->getSelectedValue('protocol')) {
1764 $this->type('name', 'Test Domain');
1765 $this->select('protocol', "IMAP");
1766 $this->type('server', 'localhost');
1767 $this->type('domain', 'example.com');
1768 $this->click('_qf_MailSettings_next-top');
1769 $this->waitForPageToLoad($this->getTimeoutMsec());
1770 }
1771 }
1772
6a488035
TO
1773 /**
1774 * Determine the default time-out in milliseconds.
1775 *
1776 * @return string, timeout expressed in milliseconds
1777 */
1778 function getTimeoutMsec() {
1779 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
1780 $timeout = ($this->settings && @$this->settings->timeout) ? ($this->settings->timeout * 1000) : 30000;
1781 return (string) $timeout; // don't know why, but all our old code used a string
1782 }
6a488035 1783
c4e6d4e8
PJ
1784 /**
1785 * CRM-12378
1786 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
1787 *
1788 *
1789 * @param array $customSets custom sets i.e entity wise sets want to be created and checked
1790 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
1791 'triggerElement' => $triggerElement))
1792 array $triggerElement: the element which is responsible for custom group to load
1793
1794 which uses the entity info as its selection value
1795 * @param array $pageUrl the url which on which the ajax custom group load takes place
5b8ddc60 1796 * @param $beforeTriggering code to execute before actual element triggering
c4e6d4e8
PJ
1797 * @return void
1798 */
5b8ddc60 1799 function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
c4e6d4e8
PJ
1800 //add the custom set
1801 $return = $this->addCustomGroupField($customSets);
1802
1803 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
1804
1805 foreach($return as $values) {
1806 foreach ($values as $entityType => $customData) {
1807 //initiate necessary variables
1808 list($entity, $entityData) = explode('_', $entityType);
1809 $elementType = CRM_Utils_Array::value('type', $customData['triggerElement'], 'select');
1810 $elementName = CRM_Utils_Array::value('name', $customData['triggerElement']);
5b8ddc60
PJ
1811 if ($beforeTriggering) {
1812 call_user_func($beforeTriggering);
1813 }
c4e6d4e8
PJ
1814 if ($elementType == 'select') {
1815 //reset the select box, so triggering of ajax only happens
1816 //WRT input of value in this function
1817 $this->select($elementName, "index=0");
1818 }
1819 if (!empty($entityData)) {
1820 if ($elementType == 'select') {
1821 $this->select($elementName, "label=regexp:{$entityData}");
1822 }
1823 elseif ($elementType == 'checkbox') {
1824 $val = explode(',', $entityData);
1825 foreach($val as $v) {
1826 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
1827 $this->check($checkId);
1828 }
1829 }
1830 }
1831
1832 //sleep method is used as to wait for custom field div to load -
1833 //we cant use wait for the div element as we are asserting for the same,
1834 //so wait for some time till the div loads
1835 sleep(1);
1836
1837 //checking for proper custom data which is loading through ajax
1838 $this->assertElementPresent("xpath=//div[@id='{$customData['cgtitle']}'][@class='crm-accordion-body']",
1839 "The on the fly custom group has not been rendered for entity : {$entity} => {$entityData}");
1840 $this->assertElementPresent("xpath=//div[@id='{$customData['cgtitle']}'][@class='crm-accordion-body']/table/tbody/tr/td[2]/input",
1841 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
1842 }
1843 }
1844 }
1845
1846 function addCustomGroupField($customSets) {
1847 foreach ($customSets as $customSet) {
1848 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
1849
1850 //fill custom group title
1851 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
1852 $this->click("title");
1853 $this->type("title", $customGroupTitle);
1854
1855 //custom group extends
1856 $this->click("extends_0");
1857 $this->select("extends_0", "value={$customSet['entity']}");
1858 if (!empty($customSet['subEntity'])) {
1859 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
1860 }
1861
1862 // Don't collapse
1863 $this->uncheck('collapse_display');
1864
1865 // Save
1866 $this->click('_qf_Group_next-bottom');
1867 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1868
1869 //Is custom group created?
1870 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
1871 $gid = $this->urlArg('gid');
1872
1873 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
1874 $this->type('label', $fieldLabel);
1875 $this->click('_qf_Field_next-bottom');
1876 $this->waitForPageToLoad($this->getTimeoutMsec());
1877 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
1878
1879 $return[] = array(
1880 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
1881 }
1882 return $return;
1883 }
65c1908a 1884}