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