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