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