4.5 Webtests fixes
[civicrm-core.git] / tests / phpunit / CiviTest / CiviSeleniumTestCase.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
28 /**
29 * Include configuration
30 */
31 define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
32 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
33 define('CIVICRM_WEBTEST', 1);
34
35 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH;
37 }
38 require_once CIVICRM_SETTINGS_PATH;
39
40 /**
41 * Base class for CiviCRM Selenium tests
42 *
43 * Common functions for unit tests
44 * @package CiviCRM
45 */
46 class CiviSeleniumTestCase extends PHPUnit_Extensions_SeleniumTestCase {
47
48 // Current logged-in user
49 protected $loggedInAs = NULL;
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
62 * @param array $data
63 * @param string $dataName
64 * @param array $browser
65 */
66 function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
67 parent::__construct($name, $data, $dataName, $browser);
68 $this->loggedInAs = NULL;
69
70 require_once 'CiviSeleniumSettings.php';
71 $this->settings = new CiviSeleniumSettings();
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 }
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
89 // FIXME: not necessary for most tests, consider moving into functions that need this
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;
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 }
104 }
105
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
149 protected function tearDown() {
150 }
151
152 /**
153 * Authenticate as drupal user
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
156 */
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 }
166 $this->open("{$this->sboxPath}user");
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 }
173 // Make sure login form is available
174 $this->waitForElementPresent('edit-submit');
175 $this->type('edit-name', $username);
176 $this->type('edit-pass', $pass);
177 $this->click('edit-submit');
178 $this->waitForPageToLoad($this->getTimeoutMsec());
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;
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 */
201 function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
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");
217 $this->waitForPageToLoad($this->getTimeoutMsec());
218 if ($waitFor) {
219 $this->waitForElementPresent($waitFor);
220 }
221 }
222
223 /**
224 * Click on a link or button
225 * Wait for the page to load
226 * Wait for an element to be present
227 */
228 function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
229 $this->click($element);
230 // conditional wait for page load e.g for ajax form save
231 if ($waitForPageLoad) {
232 $this->waitForPageToLoad($this->getTimeoutMsec());
233 }
234 if ($waitFor) {
235 $this->waitForElementPresent($waitFor);
236 }
237 }
238
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
275 /**
276 * @param $option_group_name
277 *
278 * @return array|int
279 */
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
289 /**
290 * @return mixed
291 */
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
301 /**
302 * @param $entity
303 *
304 * @return mixed|null
305 */
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
316 /**
317 * @param $field
318 *
319 * @return mixed
320 */
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
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)) {
343 $this->addSelection("enableComponents-f", "label=$comp");
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());
352 $this->waitForText('crm-notification-container', "Saved");
353 }
354 }
355
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
362 * @param mixed $email contact’s email (when string) or random email (when true) or no email (when null)
363 *
364 * @param null $contactSubtype
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
389 /**
390 * @param string $householdName
391 * @param null $email
392 *
393 * @return null|string
394 */
395 function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
396
397 $this->openCiviPage("contact/add", "reset=1&ct=Household");
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
413 /**
414 * @param string $organizationName
415 * @param null $email
416 * @param null $contactSubtype
417 *
418 * @return null|string
419 */
420 function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
421
422 $url = $this->sboxPath . 'civicrm/contact/add?reset=1&ct=Organization';
423 if ($contactSubtype) {
424 $url = $url . "&cst={$contactSubtype}";
425 }
426 $this->open($url);
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 */
443 function webtestFillAutocomplete($sortName, $fieldName = 'contact_id') {
444 $this->select2($fieldName,$sortName);
445 //$this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
446 }
447
448 /**
449 */
450 function webtestOrganisationAutocomplete($sortName) {
451 $this->clickAt("//*[@id='contact_id']/../div/a");
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]");
458 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
459 }
460
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 */
473 /**
474 * @param $dateElement
475 * @param null $strToTimeArgs
476 */
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.
493 /**
494 * @param $dateElement
495 * @param null $strToTimeArgs
496 */
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) {
524 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td");
525 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
526 }
527 else {
528 $this->waitForElementPresent("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td");
529 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
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 */
543 function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor', $compressed = FALSE) {
544 // make sure cursor focuses on the field
545 $this->fireEvent($fieldName, 'focus');
546 if ($editor == 'CKEditor') {
547 if ($compressed) {
548 $this->click("{$fieldName}-plain");
549 }
550 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
551 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
552 }
553 elseif ($editor == 'TinyMCE') {
554 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
555 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
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'];
577 if (!empty($oValue['membership_type_id'])) {
578 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
579 }
580 if (!empty($oValue['financial_type_id'])) {
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 */
591 function webtestNewDialogContact($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
592 $type = 4, $selectId = 's2id_contact_id', $row = 1, $prefix = '') {
593 // 4 - Individual profile
594 // 5 - Organization profile
595 // 6 - Household profile
596 $profile = array('4' => 'New Individual', '5' => 'New Organization', '6' => 'New Household');
597 $this->clickAt("xpath=//div[@id='$selectId']/a");
598 $this->click("xpath=//li[@class='select2-no-results']//a[contains(text(),' $profile[$type]')]");
599
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) {
622 $this->waitForText("xpath=//div[@id='$selectId']","$lname, $fname");
623 }
624 else {
625 $this->waitForText("xpath=//div[@id='$selectId']","$fname");
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 *
634 * @param $strings
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 *
648 * @param null $url
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
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
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
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.)
680 * @param array $processorSettings Array of fieldname => value for required settings for the processor
681 *
682 * @param string $financialAccount
683 * @throws PHPUnit_Framework_AssertionFailedError
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
745 $paymentProcessorId = explode('&id=', $this->getAttribute("xpath=//table[@class='selector row-highlight']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href"));
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
759 /**
760 * @param null $firstName
761 * @param null $middleName
762 * @param null $lastName
763 *
764 * @return array
765 */
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');
785 $this->select('billing_country_id-5', 'value=1228');
786 $this->click('billing_state_province_id-5');
787 $this->select('billing_state_province_id-5', 'label=California');
788 $this->type('billing_postal_code-5', '93245');
789
790 return array($firstName, $middleName, $lastName);
791 }
792
793 /**
794 * @param $fieldLocator
795 * @param null $filePath
796 *
797 * @return null|string
798 */
799 function webtestAttachFile($fieldLocator, $filePath = NULL) {
800 if (!$filePath) {
801 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
802 $fp = @fopen($filePath, 'w');
803 fputs($fp, 'Test file created by selenium test.');
804 @fclose($fp);
805 }
806
807 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
808
809 $this->attachFile($fieldLocator, "file://{$filePath}");
810
811 return $filePath;
812 }
813
814 /**
815 * @param $headers
816 * @param $rows
817 * @param null $filePath
818 *
819 * @return null|string
820 */
821 function webtestCreateCSV($headers, $rows, $filePath = NULL) {
822 if (!$filePath) {
823 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
824 }
825
826 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
827
828 foreach ($rows as $row) {
829 $temp = array();
830 foreach ($headers as $field => $header) {
831 $temp[$field] = isset($row[$field]) ? '"' . $row[$field] . '"' : '""';
832 }
833 $data .= implode(', ', $temp) . "\r\n";
834 }
835
836 $fp = @fopen($filePath, 'w');
837 @fwrite($fp, $data);
838 @fclose($fp);
839
840 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
841
842 return $filePath;
843 }
844
845 /**
846 * Create new relationship type w/ user specified params or default.
847 *
848 * @param $params array of required params.
849 *
850 * @return an array of saved params values.
851 */
852 function webtestAddRelationshipType($params = array()) {
853 $this->openCiviPage("admin/reltype", "reset=1&action=add");
854
855 //build the params if not passed.
856 if (!is_array($params) || empty($params)) {
857 $params = array(
858 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
859 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
860 'contact_types_a' => 'Individual',
861 'contact_types_b' => 'Individual',
862 'description' => 'Test Relationship Type Description',
863 );
864 }
865 //make sure we have minimum required params.
866 if (!isset($params['label_a_b']) || empty($params['label_a_b'])) {
867 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
868 }
869
870 //start the form fill.
871 $this->type('label_a_b', $params['label_a_b']);
872 $this->type('label_b_a', $params['label_b_a']);
873 $this->select('contact_types_a', "value={$params['contact_type_a']}");
874 $this->select('contact_types_b', "value={$params['contact_type_b']}");
875 $this->type('description', $params['description']);
876
877 //save the data.
878 $this->click('_qf_RelationshipType_next-bottom');
879 $this->waitForPageToLoad($this->getTimeoutMsec());
880
881 //does data saved.
882 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
883 "Status message didn't show up after saving!"
884 );
885
886 $this->openCiviPage("admin/reltype", "reset=1");
887
888 //validate data on selector.
889 $data = $params;
890 if (isset($data['description'])) {
891 unset($data['description']);
892 }
893 $this->assertStringsPresent($data);
894
895 return $params;
896 }
897
898 /**
899 * Create new online contribution page w/ user specified params or defaults.
900 * FIXME: this function take an absurd number of params - very unwieldy :(
901 *
902 * @param null $hash
903 * @param null $rand
904 * @param null $pageTitle
905 * @param array $processor
906 * @param bool $amountSection
907 * @param bool $payLater
908 * @param bool $onBehalf
909 * @param bool $pledges
910 * @param bool $recurring
911 * @param bool $membershipTypes
912 * @param null $memPriceSetId
913 * @param bool $friend
914 * @param int $profilePreId
915 * @param int $profilePostId
916 * @param bool $premiums
917 * @param bool $widget
918 * @param bool $pcp
919 * @param bool $isAddPaymentProcessor
920 * @param bool $isPcpApprovalNeeded
921 * @param bool $isSeparatePayment
922 * @param bool $honoreeSection
923 * @param bool $allowOtherAmount
924 * @param bool $isConfirmEnabled
925 * @param string $financialType
926 * @param bool $fixedAmount
927 * @param bool $membershipsRequired
928 * @internal param \can $User define pageTitle, hash and rand values for later data verification
929 *
930 * @return null $pageId of newly created online contribution page.
931 */
932 function webtestAddContributionPage($hash = NULL,
933 $rand = NULL,
934 $pageTitle = NULL,
935 $processor = array('Dummy Processor' => 'Dummy'),
936 $amountSection = TRUE,
937 $payLater = TRUE,
938 $onBehalf = TRUE,
939 $pledges = TRUE,
940 $recurring = FALSE,
941 $membershipTypes = TRUE,
942 $memPriceSetId = NULL,
943 $friend = TRUE,
944 $profilePreId = 1,
945 $profilePostId = 7,
946 $premiums = TRUE,
947 $widget = TRUE,
948 $pcp = TRUE,
949 $isAddPaymentProcessor = TRUE,
950 $isPcpApprovalNeeded = FALSE,
951 $isSeparatePayment = FALSE,
952 $honoreeSection = TRUE,
953 $allowOtherAmount = TRUE,
954 $isConfirmEnabled = TRUE,
955 $financialType = 'Donation',
956 $fixedAmount = TRUE,
957 $membershipsRequired = TRUE
958 ) {
959 if (!$hash) {
960 $hash = substr(sha1(rand()), 0, 7);
961 }
962 if (!$pageTitle) {
963 $pageTitle = 'Donate Online ' . $hash;
964 }
965
966 if (!$rand) {
967 $rand = 2 * rand(2, 50);
968 }
969
970 // Create a new payment processor if requested
971 if ($isAddPaymentProcessor) {
972 while (list($processorName, $processorType) = each($processor)) {
973 $this->webtestAddPaymentProcessor($processorName, $processorType);
974 }
975 }
976
977 // go to the New Contribution Page page
978 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
979
980 // fill in step 1 (Title and Settings)
981 $this->type('title', $pageTitle);
982
983 //to select financial type
984 $this->select('financial_type_id', "label={$financialType}");
985
986 if ($onBehalf) {
987 $this->click('is_organization');
988 $this->select("xpath=//*[@class='crm-contribution-onbehalf_profile_id']//span[@class='crm-profile-selector-select']//select", 'label=On Behalf Of Organization');
989 $this->type('for_organization', "On behalf $hash");
990
991 if ($onBehalf == 'required') {
992 $this->click('CIVICRM_QFID_2_4');
993 }
994 elseif ($onBehalf == 'optional') {
995 $this->click('CIVICRM_QFID_1_2');
996 }
997 }
998
999 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
1000 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
1001
1002 $this->type('goal_amount', 10 * $rand);
1003
1004 // FIXME: handle Start/End Date/Time
1005 if ($honoreeSection) {
1006 $this->click('honor_block_is_active');
1007 $this->type('honor_block_title', "Honoree Section Title $hash");
1008 $this->type('honor_block_text', "Honoree Introductory Message $hash");
1009 $this->click("//*[@id='s2id_soft_credit_types']/ul");
1010 $this->waitForElementPresent("//*[@id='select2-drop']/ul");
1011 $this->waitForElementPresent("//*[@class='select2-result-label']");
1012 $this->clickAt("//*[@class='select2-results']/li[1]");
1013 }
1014
1015 // is confirm enabled? it starts out enabled, so uncheck it if false
1016 if (!$isConfirmEnabled) {
1017 $this->click("id=is_confirm_enabled");
1018 }
1019
1020 // Submit form
1021 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
1022
1023 // Get contribution page id
1024 $pageId = $this->urlArg('id');
1025
1026 // fill in step 2 (Processor, Pay Later, Amounts)
1027 if (!empty($processor)) {
1028 reset($processor);
1029 while (list($processorName) = each($processor)) {
1030 // select newly created processor
1031 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
1032 $this->assertTrue($this->isTextPresent($processorName));
1033 $this->check($xpath);
1034 }
1035 }
1036
1037 if ($amountSection && !$memPriceSetId) {
1038 if ($payLater) {
1039 $this->click('is_pay_later');
1040 $this->type('pay_later_text', "Pay later label $hash");
1041 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
1042 }
1043
1044 if ($pledges) {
1045 $this->click('is_pledge_active');
1046 $this->click('pledge_frequency_unit[week]');
1047 $this->click('is_pledge_interval');
1048 $this->type('initial_reminder_day', 3);
1049 $this->type('max_reminders', 2);
1050 $this->type('additional_reminder_day', 1);
1051 }
1052 elseif ($recurring) {
1053 $this->click('is_recur');
1054 $this->click("is_recur_interval");
1055 $this->click("is_recur_installments");
1056 }
1057 if ($allowOtherAmount) {
1058
1059 $this->click('is_allow_other_amount');
1060
1061 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
1062 //$this->type('min_amount', $rand / 2);
1063 //$this->type('max_amount', $rand * 10);
1064 }
1065 if ($fixedAmount || !$allowOtherAmount) {
1066 $this->type('label_1', "Label $hash");
1067 $this->type('value_1', "$rand");
1068 }
1069 $this->click('CIVICRM_QFID_1_4');
1070 }
1071 else {
1072 $this->click('amount_block_is_active');
1073 }
1074
1075 $this->click('_qf_Amount_next');
1076 $this->waitForElementPresent('_qf_Amount_next-bottom');
1077 $this->waitForPageToLoad($this->getTimeoutMsec());
1078 $text = "'Amount' information has been saved.";
1079 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1080
1081 if ($memPriceSetId || (($membershipTypes === TRUE) || (is_array($membershipTypes) && !empty($membershipTypes)))) {
1082 // go to step 3 (memberships)
1083 $this->click('link=Memberships');
1084 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
1085
1086 // fill in step 3 (Memberships)
1087 $this->click('member_is_active');
1088 $this->waitForElementPresent('displayFee');
1089 $this->type('new_title', "Title - New Membership $hash");
1090 $this->type('renewal_title', "Title - Renewals $hash");
1091
1092 if ($memPriceSetId) {
1093 $this->click('member_price_set_id');
1094 $this->select('member_price_set_id', "value={$memPriceSetId}");
1095 }
1096 else {
1097 if ($membershipTypes === TRUE) {
1098 $membershipTypes = array(array('id' => 2));
1099 }
1100
1101 // FIXME: handle Introductory Message - New Memberships/Renewals
1102 foreach ($membershipTypes as $mType) {
1103 $this->click("membership_type_{$mType['id']}");
1104 if (array_key_exists('default', $mType)) {
1105 // FIXME:
1106 }
1107 if (array_key_exists('auto_renew', $mType)) {
1108 $this->select("auto_renew_{$mType['id']}", "label=Give option");
1109 }
1110 }
1111 if ($membershipsRequired) {
1112 $this->click('is_required');
1113 }
1114 $this->waitForElementPresent('CIVICRM_QFID_2_4');
1115 $this->click('CIVICRM_QFID_2_4');
1116 if ($isSeparatePayment) {
1117 $this->click('is_separate_payment');
1118 }
1119 }
1120 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
1121 $text = "'MembershipBlock' information has been saved.";
1122 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1123 }
1124
1125 // go to step 4 (thank-you and receipting)
1126 $this->click('link=Receipt');
1127 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1128
1129 // fill in step 4
1130 $this->type('thankyou_title', "Thank-you Page Title $hash");
1131 // FIXME: handle Thank-you Message/Page Footer
1132 $this->type('receipt_from_name', "Receipt From Name $hash");
1133 $this->type('receipt_from_email', "$hash@example.org");
1134 $this->type('receipt_text', "Receipt Message $hash");
1135 $this->type('cc_receipt', "$hash@example.net");
1136 $this->type('bcc_receipt', "$hash@example.com");
1137
1138 $this->click('_qf_ThankYou_next');
1139 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1140 $this->waitForPageToLoad($this->getTimeoutMsec());
1141 $text = "'ThankYou' information has been saved.";
1142 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1143
1144 if ($friend) {
1145 // fill in step 5 (Tell a Friend)
1146 $this->click('link=Tell a Friend');
1147 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1148 $this->click('tf_is_active');
1149 $this->type('tf_title', "TaF Title $hash");
1150 $this->type('intro', "TaF Introduction $hash");
1151 $this->type('suggested_message', "TaF Suggested Message $hash");
1152 $this->type('general_link', "TaF Info Page Link $hash");
1153 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1154 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1155
1156 //$this->click('_qf_Contribute_next');
1157 $this->click('_qf_Contribute_next-bottom');
1158 $this->waitForPageToLoad($this->getTimeoutMsec());
1159 $text = "'Friend' information has been saved.";
1160 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1161 }
1162
1163 if ($profilePreId || $profilePostId) {
1164 // fill in step 6 (Include Profiles)
1165 $this->click('css=li#tab_custom a');
1166 $this->waitForElementPresent('_qf_Custom_next-bottom');
1167
1168 if ($profilePreId) {
1169 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_pre_id span.crm-profile-selector-select select', "value={$profilePreId}");
1170 }
1171
1172 if ($profilePostId) {
1173 $this->select('css=tr.crm-contribution-contributionpage-custom-form-block-custom_post_id span.crm-profile-selector-select select', "value={$profilePostId}");
1174 }
1175
1176 $this->click('_qf_Custom_next-bottom');
1177 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1178
1179 $this->waitForPageToLoad($this->getTimeoutMsec());
1180 $text = "'Custom' information has been saved.";
1181 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1182 }
1183
1184 if ($premiums) {
1185 // fill in step 7 (Premiums)
1186 $this->click('link=Premiums');
1187 $this->waitForElementPresent('_qf_Premium_next-bottom');
1188 $this->click('premiums_active');
1189 $this->type('premiums_intro_title', "Prem Title $hash");
1190 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1191 $this->type('premiums_contact_email', "$hash@example.info");
1192 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1193 $this->click('premiums_display_min_contribution');
1194 $this->type('premiums_nothankyou_label', 'No thank-you');
1195 $this->click('_qf_Premium_next');
1196 $this->waitForElementPresent('_qf_Premium_next-bottom');
1197
1198 $this->waitForPageToLoad($this->getTimeoutMsec());
1199 $text = "'Premium' information has been saved.";
1200 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1201 }
1202
1203 if ($widget) {
1204 // fill in step 8 (Widget Settings)
1205 $this->click('link=Widgets');
1206 $this->waitForElementPresent('_qf_Widget_next-bottom');
1207
1208 $this->click('is_active');
1209 $this->type('url_logo', "URL to Logo Image $hash");
1210 $this->type('button_title', "Button Title $hash");
1211 // Type About text in ckEditor (fieldname, text to type, editor)
1212 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1213
1214 $this->click('_qf_Widget_next');
1215 $this->waitForElementPresent('_qf_Widget_next-bottom');
1216
1217 $this->waitForPageToLoad($this->getTimeoutMsec());
1218 $text = "'Widget' information has been saved.";
1219 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1220 }
1221
1222 if ($pcp) {
1223 // fill in step 9 (Enable Personal Campaign Pages)
1224 $this->click('link=Personal Campaigns');
1225 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1226 $this->click('pcp_active');
1227 if (!$isPcpApprovalNeeded) {
1228 $this->click('is_approval_needed');
1229 }
1230 $this->type('notify_email', "$hash@example.name");
1231 $this->select('supporter_profile_id', 'value=2');
1232 $this->type('tellfriend_limit', 7);
1233 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1234
1235 $this->click('_qf_Contribute_next-bottom');
1236 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1237 $this->waitForPageToLoad($this->getTimeoutMsec());
1238 $text = "'Pcp' information has been saved.";
1239 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1240 }
1241
1242 return $pageId;
1243 }
1244
1245 /**
1246 * Function to update default strict rule.
1247 *
1248 * @params string $contactType Contact type
1249 * @param string $contactType
1250 * @param array $fields Fields to be set for strict rule
1251 * @param Integer $threshold Rule's threshold value
1252 */
1253 function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1254 // set default strict rule.
1255 $strictRuleId = 4;
1256 if ($contactType == 'Organization') {
1257 $strictRuleId = 5;
1258 }
1259 elseif ($contactType == 'Household') {
1260 $strictRuleId = 6;
1261 }
1262
1263 // Default dedupe fields for each Contact type.
1264 if (empty($fields)) {
1265 $fields = array('civicrm_email.email' => 10);
1266 if ($contactType == 'Organization') {
1267 $fields = array(
1268 'civicrm_contact.organization_name' => 10,
1269 'civicrm_email.email' => 10,
1270 );
1271 }
1272 elseif ($contactType == 'Household') {
1273 $fields = array(
1274 'civicrm_contact.household_name' => 10,
1275 'civicrm_email.email' => 10,
1276 );
1277 }
1278 }
1279
1280 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1281
1282 $count = 0;
1283 foreach ($fields as $field => $weight) {
1284 $this->select("where_{$count}", "value={$field}");
1285 $this->type("length_{$count}", '');
1286 $this->type("weight_{$count}", $weight);
1287 $count++;
1288 }
1289
1290 if ($count > 4) {
1291 $this->type('threshold', $threshold);
1292 // click save
1293 $this->click('_qf_DedupeRules_next-bottom');
1294 $this->waitForPageToLoad($this->getTimeoutMsec());
1295 return;
1296 }
1297
1298 for ($i = $count; $i <= 4; $i++) {
1299 $this->select("where_{$i}", 'label=- none -');
1300 $this->type("length_{$i}", '');
1301 $this->type("weight_{$i}", '');
1302 }
1303
1304 $this->type('threshold', $threshold);
1305
1306 // click save
1307 $this->click('_qf_DedupeRules_next-bottom');
1308 $this->waitForPageToLoad($this->getTimeoutMsec());
1309 }
1310
1311 /**
1312 * @param string $period_type
1313 * @param int $duration_interval
1314 * @param string $duration_unit
1315 * @param string $auto_renew
1316 *
1317 * @return array
1318 */
1319 function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1320 $membershipTitle = substr(sha1(rand()), 0, 7);
1321 $membershipOrg = $membershipTitle . ' memorg';
1322 $this->webtestAddOrganization($membershipOrg, TRUE);
1323
1324 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1325 $memTypeParams = array(
1326 'membership_type' => $title,
1327 'member_of_contact' => $membershipOrg,
1328 'financial_type' => 2,
1329 'period_type' => $period_type,
1330 );
1331
1332 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1333
1334 $this->type('name', $memTypeParams['membership_type']);
1335
1336 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1337 // select the radio first since the element id changes after membership org search results are loaded
1338 switch ($auto_renew) {
1339 case 'optional':
1340 $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')]");
1341 break;
1342
1343 case 'required':
1344 $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')]");
1345 break;
1346
1347 default:
1348 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1349 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')]")) {
1350 $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')]");
1351 }
1352 break;
1353 }
1354
1355 $this->select2('member_of_contact_id',$membershipTitle);
1356
1357 $this->type('minimum_fee', '100');
1358 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1359
1360 $this->type('duration_interval', $duration_interval);
1361 $this->select('duration_unit', "label={$duration_unit}");
1362
1363 $this->select('period_type', "value={$period_type}");
1364
1365 $this->click('_qf_MembershipType_upload-bottom');
1366 $this->waitForElementPresent('link=Add Membership Type');
1367 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1368
1369 return $memTypeParams;
1370 }
1371
1372 /**
1373 * @param null $groupName
1374 * @param null $parentGroupName
1375 *
1376 * @return null|string
1377 */
1378 function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1379 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1380
1381 // fill group name
1382 if (!$groupName) {
1383 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1384 }
1385 $this->type('title', $groupName);
1386
1387 // fill description
1388 $this->type('description', 'Adding new group.');
1389
1390 // check Access Control
1391 $this->click('group_type[1]');
1392
1393 // check Mailing List
1394 $this->click('group_type[2]');
1395
1396 // select Visibility as Public Pages
1397 $this->select('visibility', 'value=Public Pages');
1398
1399 // select parent group
1400 if ($parentGroupName) {
1401 $this->select('parents', "*$parentGroupName");
1402 }
1403
1404 // Clicking save.
1405 $this->clickLink('_qf_Edit_upload-bottom');
1406
1407 // Is status message correct?
1408 $this->waitForText('crm-notification-container', "$groupName");
1409 return $groupName;
1410 }
1411
1412 /**
1413 * @param string $activityType
1414 *
1415 * @return null
1416 */
1417 function WebtestAddActivity($activityType = "Meeting") {
1418 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1419 // We're using Quick Add block on the main page for this.
1420 $firstName1 = substr(sha1(rand()), 0, 7);
1421 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1422 $firstName2 = substr(sha1(rand()), 0, 7);
1423 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1424
1425 $this->click("css=li#tab_activity a");
1426
1427 // waiting for the activity dropdown to show up
1428 $this->waitForElementPresent("other_activity");
1429
1430 // Select the activity type from the activity dropdown
1431 $this->select("other_activity", "label=Meeting");
1432
1433 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1434 $this->waitForElementPresent("s2id_target_contact_id");
1435
1436 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__);
1437
1438 // Typing contact's name into the field (using typeKeys(), not type()!)...
1439 $this->select2("assignee_contact_id", $firstName1, TRUE);
1440
1441 // ...and verifying if the page contains properly formatted display name for chosen contact.
1442 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__);
1443
1444 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1445 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1446 // For simple input fields we can use field id as selector
1447 $this->type("subject", $subject);
1448 $this->type("location", "Some location needs to be put in this field.");
1449
1450 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1451
1452 // Setting duration.
1453 $this->type("duration", "30");
1454
1455 // Putting in details.
1456 $this->type("details", "Really brief details information.");
1457
1458 // Making sure that status is set to Scheduled (using value, not label).
1459 $this->select("status_id", "value=1");
1460
1461 // Setting priority.
1462 $this->select("priority_id", "value=1");
1463
1464 // Scheduling follow-up.
1465 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1466 $this->select("followup_activity_type_id", "value=1");
1467 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1468 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1469
1470 // Clicking save.
1471 $this->click("_qf_Activity_upload-bottom");
1472 $this->waitForElementPresent("xpath=//div[@id='crm-notification-container']");
1473
1474 // Is status message correct?
1475 $this->waitForText('crm-notification-container', "Activity '$subject' has been saved.");
1476
1477 $this->waitForElementPresent("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1478
1479 // click through to the Activity view screen
1480 $this->click("xpath=//div[@id='contact-activity-selector-activity_wrapper']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1481 $this->waitForElementPresent('_qf_Activity_cancel-bottom');
1482
1483 // parse URL to grab the activity id
1484 // pass id back to any other tests that call this class
1485 return $this->urlArg('id');
1486 }
1487
1488 /**
1489 * @return bool
1490 */
1491 static
1492 function checkDoLocalDBTest() {
1493 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1494 CIVICRM_WEBTEST_LOCAL_DB
1495 ) {
1496 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1497 return TRUE;
1498 }
1499 return FALSE;
1500 }
1501
1502 /**
1503 * Generic function to compare expected values after an api call to retrieved
1504 * DB values.
1505 *
1506 * @daoName string DAO Name of object we're evaluating.
1507 * @id int Id of object
1508 * @match array Associative array of field name => expected value. Empty if asserting
1509 * that a DELETE occurred
1510 * @delete boolean True if we're checking that a DELETE action occurred.
1511 */
1512 function assertDBState($daoName, $id, $match, $delete = FALSE) {
1513 if (!self::checkDoLocalDBTest()) {
1514 return;
1515 }
1516
1517 return CiviDBAssert::assertDBState($this, $daoName, $id, $match, $delete);
1518 }
1519
1520 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1521 /**
1522 * @param $daoName
1523 * @param $searchValue
1524 * @param $returnColumn
1525 * @param $searchColumn
1526 * @param $message
1527 *
1528 * @return null|string
1529 */
1530 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1531 if (!self::checkDoLocalDBTest()) {
1532 return;
1533 }
1534
1535 return CiviDBAssert::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1536 }
1537
1538 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1539 /**
1540 * @param $daoName
1541 * @param $searchValue
1542 * @param $returnColumn
1543 * @param $searchColumn
1544 * @param $message
1545 */
1546 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1547 if (!self::checkDoLocalDBTest()) {
1548 return;
1549 }
1550
1551 return CiviDBAssert::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1552 }
1553
1554 // Request a record from the DB by id. Success if row not found.
1555 /**
1556 * @param $daoName
1557 * @param $id
1558 * @param $message
1559 */
1560 function assertDBRowNotExist($daoName, $id, $message) {
1561 if (!self::checkDoLocalDBTest()) {
1562 return;
1563 }
1564
1565 return CiviDBAssert::assertDBRowNotExist($this, $daoName, $id, $message);
1566 }
1567
1568 // Compare a single column value in a retrieved DB record to an expected value
1569 /**
1570 * @param $daoName
1571 * @param $searchValue
1572 * @param $returnColumn
1573 * @param $searchColumn
1574 * @param $expectedValue
1575 * @param string $message
1576 */
1577 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1578 $expectedValue, $message
1579 ) {
1580 if (!self::checkDoLocalDBTest()) {
1581 return;
1582 }
1583
1584 return CiviDBAssert::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1585 $expectedValue, $message
1586 );
1587 }
1588
1589 // Compare all values in a single retrieved DB record to an array of expected values
1590 /**
1591 * @param $daoName
1592 * @param $searchParams
1593 * @param $expectedValues
1594 */
1595 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1596 if (!self::checkDoLocalDBTest()) {
1597 return;
1598 }
1599
1600 return CiviDBAssert::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1601 }
1602
1603 /**
1604 * @param $expectedValues
1605 * @param $actualValues
1606 */
1607 function assertAttributesEquals(&$expectedValues, &$actualValues) {
1608 if (!self::checkDoLocalDBTest()) {
1609 return;
1610 }
1611
1612 return CiviDBAssert::assertAttributesEquals($expectedValues, $actualValues);
1613 }
1614
1615 /**
1616 * @param $expected
1617 * @param $actual
1618 * @param string $message
1619 */
1620 function assertType($expected, $actual, $message = '') {
1621 return $this->assertInternalType($expected, $actual, $message);
1622 }
1623
1624 /**
1625 * Add new Financial Account
1626 */
1627 function _testAddFinancialAccount($financialAccountTitle,
1628 $financialAccountDescription = FALSE,
1629 $accountingCode = FALSE,
1630 $firstName = FALSE,
1631 $financialAccountType = FALSE,
1632 $taxDeductible = FALSE,
1633 $isActive = FALSE,
1634 $isTax = FALSE,
1635 $taxRate = FALSE,
1636 $isDefault = FALSE
1637 ) {
1638
1639 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1640
1641 $this->click("link=Add Financial Account");
1642 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1643
1644 // Financial Account Name
1645 $this->type('name', $financialAccountTitle);
1646
1647 // Financial Description
1648 if ($financialAccountDescription) {
1649 $this->type('description', $financialAccountDescription);
1650 }
1651
1652 //Accounting Code
1653 if ($accountingCode) {
1654 $this->type('accounting_code', $accountingCode);
1655 }
1656
1657 // Autofill Organization
1658 if ($firstName) {
1659 $this->webtestOrganisationAutocomplete($firstName);
1660 }
1661
1662 // Financial Account Type
1663 if ($financialAccountType) {
1664 $this->select('financial_account_type_id', "label={$financialAccountType}");
1665 }
1666
1667 // Is Tax Deductible
1668 if ($taxDeductible) {
1669 $this->check('is_deductible');
1670 }
1671 else {
1672 $this->uncheck('is_deductible');
1673 }
1674 // Is Active
1675 if (!$isActive) {
1676 $this->check('is_active');
1677 }
1678 else {
1679 $this->uncheck('is_active');
1680 }
1681 // Is Tax
1682 if ($isTax) {
1683 $this->check('is_tax');
1684 }
1685 else {
1686 $this->uncheck('is_tax');
1687 }
1688 // Tax Rate
1689 if ($taxRate) {
1690 $this->type('tax_rate', $taxRate);
1691 }
1692
1693 // Set Default
1694 if ($isDefault) {
1695 $this->check('is_default');
1696 }
1697 else {
1698 $this->uncheck('is_default');
1699 }
1700 $this->click('_qf_FinancialAccount_next-botttom');
1701 }
1702
1703 /**
1704 * Edit Financial Account
1705 */
1706 function _testEditFinancialAccount($editfinancialAccount,
1707 $financialAccountTitle = FALSE,
1708 $financialAccountDescription = FALSE,
1709 $accountingCode = FALSE,
1710 $firstName = FALSE,
1711 $financialAccountType = FALSE,
1712 $taxDeductible = FALSE,
1713 $isActive = TRUE,
1714 $isTax = FALSE,
1715 $taxRate = FALSE,
1716 $isDefault = FALSE
1717 ) {
1718 if ($firstName) {
1719 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1720 }
1721
1722 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
1723 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom', FALSE);
1724
1725 // Change Financial Account Name
1726 if ($financialAccountTitle) {
1727 $this->type('name', $financialAccountTitle);
1728 }
1729
1730 // Financial Description
1731 if ($financialAccountDescription) {
1732 $this->type('description', $financialAccountDescription);
1733 }
1734
1735 //Accounting Code
1736 if ($accountingCode) {
1737 $this->type('accounting_code', $accountingCode);
1738 }
1739
1740 // Autofill Edit Organization
1741 if ($firstName) {
1742 $this->webtestOrganisationAutocomplete($firstName);
1743 }
1744
1745 // Financial Account Type
1746 if ($financialAccountType) {
1747 $this->select('financial_account_type_id', "label={$financialAccountType}");
1748 }
1749
1750 // Is Tax Deductible
1751 if ($taxDeductible) {
1752 $this->check('is_deductible');
1753 }
1754 else {
1755 $this->uncheck('is_deductible');
1756 }
1757
1758 // Is Tax
1759 if ($isTax) {
1760 $this->check('is_tax');
1761 }
1762 else {
1763 $this->uncheck('is_tax');
1764 }
1765
1766 // Tax Rate
1767 if ($taxRate) {
1768 $this->type('tax_rate', $taxRate);
1769 }
1770
1771 // Set Default
1772 if ($isDefault) {
1773 $this->check('is_default');
1774 }
1775 else {
1776 $this->uncheck('is_default');
1777 }
1778
1779 // Is Active
1780 if ($isActive) {
1781 $this->check('is_active');
1782 }
1783 else {
1784 $this->uncheck('is_active');
1785 }
1786 $this->click('_qf_FinancialAccount_next-botttom');
1787 $this->waitForElementPresent('link=Add Financial Account');
1788 }
1789
1790 /**
1791 * Delete Financial Account
1792 */
1793 function _testDeleteFinancialAccount($financialAccountTitle) {
1794 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1795 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1796 $this->click('_qf_FinancialAccount_next-botttom');
1797 $this->waitForElementPresent('link=Add Financial Account');
1798 $this->waitForText('crm-notification-container', "Selected Financial Account has been deleted.");
1799 }
1800
1801 /**
1802 * Verify data after ADD and EDIT
1803 */
1804 function _assertFinancialAccount($verifyData) {
1805 foreach ($verifyData as $key => $expectedValue) {
1806 $actualValue = $this->getValue($key);
1807 if ($key == 'parent_financial_account') {
1808 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1809 }
1810 else {
1811 $this->assertEquals($expectedValue, $actualValue);
1812 }
1813 }
1814 }
1815
1816 /**
1817 * @param $verifySelectFieldData
1818 */
1819 function _assertSelectVerify($verifySelectFieldData) {
1820 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1821 $actualvalue = $this->getSelectedLabel($key);
1822 $this->assertEquals($expectedvalue, $actualvalue);
1823 }
1824 }
1825
1826 /**
1827 * @param $financialType
1828 * @param string $option
1829 */
1830 function addeditFinancialType($financialType, $option = 'new') {
1831 $this->openCiviPage("admin/financial/financialType", "reset=1");
1832
1833 if ($option == 'Delete') {
1834 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1835 $this->waitForElementPresent("css=span.btn-slide-active");
1836 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1837 $this->waitForElementPresent("_qf_FinancialType_next");
1838 $this->click("_qf_FinancialType_next");
1839 $this->waitForElementPresent("newFinancialType");
1840 $this->waitForText('crm-notification-container', 'Selected financial type has been deleted.');
1841 return;
1842 }
1843 if ($option == 'new') {
1844 $this->click("link=Add Financial Type");
1845 }
1846 else {
1847 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1848 }
1849 $this->waitForElementPresent("name");
1850 $this->type('name', $financialType['name']);
1851 if ($option == 'new') {
1852 $this->type('description', $financialType['name'] . ' description');
1853 }
1854
1855 if ($financialType['is_reserved']) {
1856 $this->check('is_reserved');
1857 }
1858 else {
1859 $this->uncheck('is_reserved');
1860 }
1861
1862 if ($financialType['is_deductible']) {
1863 $this->check('is_deductible');
1864 }
1865 else {
1866 $this->uncheck('is_deductible');
1867 }
1868
1869 $this->click('_qf_FinancialType_next');
1870 if ($option == 'new') {
1871 $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.";
1872 }
1873 else {
1874 $text = "The financial type '{$financialType['name']}' has been saved.";
1875 }
1876 $this->waitForText('crm-notification-container', $text);
1877 }
1878
1879 /**
1880 * Give the specified permissions
1881 * Note: this function logs in as 'admin' (logging out if necessary)
1882 */
1883 function changePermissions($permission) {
1884 $this->webtestLogin('admin');
1885 $this->open("{$this->sboxPath}admin/people/permissions");
1886 $this->waitForElementPresent('edit-submit');
1887 foreach ((array) $permission as $perm) {
1888 $this->check($perm);
1889 }
1890 $this->click('edit-submit');
1891 $this->waitForPageToLoad($this->getTimeoutMsec());
1892 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
1893 }
1894
1895 /**
1896 * @param $profileTitle
1897 * @param $profileFields
1898 */
1899 function addProfile($profileTitle, $profileFields) {
1900 $this->openCiviPage('admin/uf/group', "reset=1");
1901
1902 $this->click('link=Add Profile');
1903
1904 // Add membership custom data field to profile
1905 $this->waitForElementPresent('_qf_Group_cancel-bottom');
1906 $this->type('title', $profileTitle);
1907 $this->click('_qf_Group_next-bottom');
1908
1909 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1910 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now."));
1911
1912 foreach ($profileFields as $field) {
1913 $this->waitForElementPresent('field_name_0');
1914 // $this->waitForPageToLoad($this->getTimeoutMsec());
1915 $this->click("id=field_name_0");
1916 $this->select("id=field_name_0", "label=" . $field['type']);
1917 $this->waitForElementPresent('field_name_1');
1918 $this->click("id=field_name_1");
1919 $this->select("id=field_name_1", "label=" . $field['name']);
1920 $this->waitForElementPresent('label');
1921 $this->type("id=label", $field['label']);
1922 $this->click("id=_qf_Field_next_new-top");
1923 $this->waitForPageToLoad($this->getTimeoutMsec());
1924 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
1925 }
1926 }
1927
1928 /**
1929 * @param $name
1930 * @param $sku
1931 * @param $amount
1932 * @param $price
1933 * @param $cost
1934 * @param $financialType
1935 */
1936 function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
1937 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
1938 $this->type("name", $name);
1939 $this->type("sku", $sku);
1940 $this->click("CIVICRM_QFID_noImage_16");
1941 $this->type("min_contribution", $amount);
1942 $this->type("price", $price);
1943 $this->type("cost", $cost);
1944 if ($financialType) {
1945 $this->select("financial_type_id", "label={$financialType}");
1946 }
1947 $this->click("_qf_ManagePremiums_upload-bottom");
1948 $this->waitForPageToLoad($this->getTimeoutMsec());
1949 }
1950
1951 /**
1952 * @param $label
1953 * @param $financialAccount
1954 */
1955 function addPaymentInstrument($label, $financialAccount) {
1956 $this->openCiviPage('admin/options/payment_instrument', 'action=add&reset=1', "_qf_Options_next-bottom");
1957 $this->type("label", $label);
1958 $this->select("financial_account_id", "value=$financialAccount");
1959 $this->click("_qf_Options_next-bottom");
1960 $this->waitForPageToLoad($this->getTimeoutMsec());
1961 }
1962
1963 /**
1964 * Ensure we have a default mailbox set up for CiviMail
1965 */
1966 function setupDefaultMailbox() {
1967 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
1968 // Check if it hasn't already been set up
1969 if (!$this->getSelectedValue('protocol')) {
1970 $this->type('name', 'Test Domain');
1971 $this->select('protocol', "IMAP");
1972 $this->type('server', 'localhost');
1973 $this->type('domain', 'example.com');
1974 $this->click('_qf_MailSettings_next-top');
1975 $this->waitForPageToLoad($this->getTimeoutMsec());
1976 }
1977 }
1978
1979 /**
1980 * Determine the default time-out in milliseconds.
1981 *
1982 * @return string, timeout expressed in milliseconds
1983 */
1984 function getTimeoutMsec() {
1985 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
1986 $timeout = ($this->settings && @$this->settings->timeout) ? ($this->settings->timeout * 1000) : 30000;
1987 return (string) $timeout; // don't know why, but all our old code used a string
1988 }
1989
1990 /**
1991 * CRM-12378
1992 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
1993 *
1994 *
1995 * @param array $customSets custom sets i.e entity wise sets want to be created and checked
1996 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
1997 'triggerElement' => $triggerElement))
1998 array $triggerElement: the element which is responsible for custom group to load
1999
2000 which uses the entity info as its selection value
2001 * @param array $pageUrl the url which on which the ajax custom group load takes place
2002 * @param $beforeTriggering code to execute before actual element triggering
2003 * @return void
2004 */
2005 function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
2006 //add the custom set
2007 $return = $this->addCustomGroupField($customSets);
2008
2009 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
2010 foreach($return as $values) {
2011 foreach ($values as $entityType => $customData) {
2012 //initiate necessary variables
2013 list($entity, $entityData) = explode('_', $entityType);
2014 $elementType = CRM_Utils_Array::value('type', $customData['triggerElement'], 'select');
2015 $elementName = CRM_Utils_Array::value('name', $customData['triggerElement']);
2016 if ($beforeTriggering) {
2017 call_user_func($beforeTriggering);
2018 }
2019 if ($elementType == 'select') {
2020 //reset the select box, so triggering of ajax only happens
2021 //WRT input of value in this function
2022 $this->select($elementName, "index=0");
2023 }
2024 if (!empty($entityData)) {
2025 if ($elementType == 'select') {
2026 $this->select($elementName, "label=regexp:{$entityData}");
2027 }
2028 elseif ($elementType == 'checkbox') {
2029 $val = explode(',', $entityData);
2030 foreach($val as $v) {
2031 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
2032 $this->check($checkId);
2033 }
2034 }
2035 elseif ($elementType == 'select2') {
2036 $this->select2($elementName, $entityData);
2037 }
2038 }
2039 //checking for proper custom data which is loading through ajax
2040 $this->waitForElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]",
2041 "The on the fly custom group has not been rendered for entity : {$entity} => {$entityData}");
2042 $this->assertElementPresent("xpath=//div[contains(@class, 'custom-group-{$customData['cgtitle']}')]/div[contains(@class, 'crm-accordion-body')]/table/tbody/tr/td[2]/input",
2043 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
2044 }
2045 }
2046 }
2047
2048 /**
2049 * @param $customSets
2050 *
2051 * @return array
2052 */
2053 function addCustomGroupField($customSets) {
2054 foreach ($customSets as $customSet) {
2055 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
2056
2057 //fill custom group title
2058 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
2059 $this->click("title");
2060 $this->type("title", $customGroupTitle);
2061
2062 //custom group extends
2063 $this->click("extends_0");
2064 $this->select("extends_0", "value={$customSet['entity']}");
2065 if (!empty($customSet['subEntity'])) {
2066 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
2067 }
2068
2069 // Don't collapse
2070 $this->uncheck('collapse_display');
2071
2072 // Save
2073 $this->click('_qf_Group_next-bottom');
2074
2075 //Is custom group created?
2076 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
2077 $this->click('css=a#newCustomField');
2078
2079 $gid = $this->urlArg('gid');
2080 $this->waitForTextPresent("{$customGroupTitle} - New Field");
2081
2082 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
2083 $this->type('label', $fieldLabel);
2084 $this->click('_qf_Field_next_new-bottom');
2085 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
2086
2087 $return[] = array(
2088 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
2089 }
2090 return $return;
2091 }
2092
2093 /**
2094 * function to type and select first occurance of autocomplete
2095 */
2096 function select2($fieldName,$label, $multiple = FALSE, $xpath=FALSE) {
2097 if ($multiple) {
2098 $this->clickAt("//*[@id='$fieldName']/../div/ul/li");
2099 $this->keyDown("//*[@id='$fieldName']/../div/ul/li//input", " ");
2100 $this->type("//*[@id='$fieldName']/../div/ul/li//input", $label);
2101 $this->typeKeys("//*[@id='$fieldName']/../div/ul/li//input", $label);
2102 $this->waitForElementPresent("//*[@class='select2-result-label']");
2103 $this->clickAt("//*[@class='select2-results']/li[1]/div");
2104 }
2105 else {
2106 if ($xpath) {
2107 $this->clickAt($fieldName);
2108 }
2109 else {
2110 $this->clickAt("//*[@id='$fieldName']/../div/a");
2111 }
2112 $this->waitForElementPresent("//*[@id='select2-drop']/div/input");
2113 $this->keyDown("//*[@id='select2-drop']/div/input", " ");
2114 $this->type("//*[@id='select2-drop']/div/input", $label);
2115 $this->typeKeys("//*[@id='select2-drop']/div/input", $label);
2116 $this->waitForElementPresent("//*[@class='select2-result-label']");
2117 $this->clickAt("//*[contains(@class,'select2-result-selectable')]/div[contains(@class, 'select2-result-label')]");
2118 }
2119 }
2120
2121 /**
2122 * function to select multiple options
2123 */
2124 function multiselect2($fieldid, $params) {
2125 foreach($params as $value) {
2126 $this->clickAt("xpath=//*[@id='$fieldid']/../div/ul//li/input");
2127 $this->waitForElementPresent("xpath=//ul[@class='select2-results']");
2128 $this->clickAt("xpath=//ul[@class='select2-results']//li/div[text()='$value']");
2129 $this->assertElementContainsText("xpath=//*[@id='$fieldid']/preceding-sibling::div[1]/", $value);
2130 }
2131 }
2132 }