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