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