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