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