[TASK] Add additional configuration for functional tests
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Tests / FunctionalTestCase.php
1 <?php
2 namespace TYPO3\CMS\Core\Tests;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2013 Christian Kuhn <lolli@schwarzbu.ch>
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 *
19 * This script is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * This copyright notice MUST APPEAR in all copies of the script!
25 ***************************************************************/
26
27 use \TYPO3\CMS\Core\Tests\Functional\Framework\Frontend\Response;
28
29 /**
30 * Base test case class for functional tests, all TYPO3 CMS
31 * functional tests should extend from this class!
32 *
33 * If functional tests need additional setUp() and tearDown() code,
34 * they *must* call parent::setUp() and parent::tearDown() to properly
35 * set up and destroy the test system.
36 *
37 * The functional test system creates a full new TYPO3 CMS instance
38 * within typo3temp/ of the base system and the bootstraps this TYPO3 instance.
39 * This abstract class takes care of creating this instance with its
40 * folder structure and a LocalConfiguration, creates an own database
41 * for each test run and imports tables of loaded extensions.
42 *
43 * Functional tests must be run standalone (calling native phpunit
44 * directly) and can not be executed by eg. the ext:phpunit backend module.
45 * Additionally, the script must be called from the document root
46 * of the instance, otherwise path calculation is not successfully.
47 *
48 * Call whole functional test suite, example:
49 * - cd /var/www/t3master/foo # Document root of CMS instance, here is index.php of frontend
50 * - ./typo3conf/ext/phpunit/Composer/vendor/bin/phpunit -c typo3/sysext/core/Build/FunctionalTests.xml
51 *
52 * Call single test case, example:
53 * - cd /var/www/t3master/foo # Document root of CMS instance, here is index.php of frontend
54 * - ./typo3conf/ext/phpunit/Composer/vendor/bin/phpunit \
55 * --process-isolation \
56 * --bootstrap typo3/sysext/core/Build/FunctionalTestsBootstrap.php \
57 * typo3/sysext/core/Tests/Functional/DataHandling/DataHandlerTest.php
58 */
59 abstract class FunctionalTestCase extends BaseTestCase {
60 /**
61 * Core extensions to load.
62 *
63 * If the test case needs additional core extensions as requirement,
64 * they can be noted here and will be added to LocalConfiguration
65 * extension list and ext_tables.sql of those extensions will be applied.
66 *
67 * This property will stay empty in this abstract, so it is possible
68 * to just overwrite it in extending classes. Extensions noted here will
69 * be loaded for every test of a test case and it is not possible to change
70 * the list of loaded extensions between single tests of a test case.
71 *
72 * A default list of core extensions is always loaded.
73 *
74 * @see FunctionalTestCaseUtility $defaultActivatedCoreExtensions
75 * @var array
76 */
77 protected $coreExtensionsToLoad = array();
78
79 /**
80 * Array of test/fixture extensions paths that should be loaded for a test.
81 *
82 * This property will stay empty in this abstract, so it is possible
83 * to just overwrite it in extending classes. Extensions noted here will
84 * be loaded for every test of a test case and it is not possible to change
85 * the list of loaded extensions between single tests of a test case.
86 *
87 * Given path is expected to be relative to your document root, example:
88 *
89 * array(
90 * 'typo3conf/ext/some_extension/Tests/Functional/Fixtures/Extensions/test_extension',
91 * 'typo3conf/ext/base_extension',
92 * );
93 *
94 * Extensions in this array are linked to the test instance, loaded
95 * and their ext_tables.sql will be applied.
96 *
97 * @var array
98 */
99 protected $testExtensionsToLoad = array();
100
101 /**
102 * Array of test/fixture folder or file paths that should be linked for a test.
103 *
104 * This property will stay empty in this abstract, so it is possible
105 * to just overwrite it in extending classes. Path noted here will
106 * be linked for every test of a test case and it is not possible to change
107 * the list of folders between single tests of a test case.
108 *
109 * array(
110 * 'link-source' => 'link-destination'
111 * );
112 *
113 * Given paths are expected to be relative to the test instance root.
114 * The array keys are the source paths and the array values are the destination
115 * paths, example:
116 *
117 * array(
118 * 'typo3/sysext/impext/Tests/Functional/Fixtures/Folders/fileadmin/user_upload' =>
119 * 'fileadmin/user_upload',
120 * 'typo3conf/ext/my_own_ext/Tests/Functional/Fixtures/Folders/uploads/tx_myownext' =>
121 * 'uploads/tx_myownext'
122 * );
123 *
124 * To be able to link from my_own_ext the extension path needs also to be registered in
125 * property $testExtensionsToLoad
126 *
127 * @var array
128 */
129 protected $pathsToLinkInTestInstance = array();
130
131 /**
132 * This configuration array is merged with TYPO3_CONF_VARS
133 * that are set in default configuration and factory configuration
134 *
135 * @var array
136 */
137 protected $configurationToUseInTestInstance = array();
138
139 /**
140 * Private utility class used in setUp() and tearDown(). Do NOT use in test cases!
141 *
142 * @var \TYPO3\CMS\Core\Tests\FunctionalTestCaseBootstrapUtility
143 */
144 private $bootstrapUtility = NULL;
145
146 /**
147 * Path to TYPO3 CMS test installation for this test case
148 *
149 * @var string
150 */
151 private $instancePath;
152
153 /**
154 * Set up creates a test instance and database.
155 *
156 * This method should be called with parent::setUp() in your test cases!
157 *
158 * @return void
159 */
160 public function setUp() {
161 if (!defined('ORIGINAL_ROOT')) {
162 $this->markTestSkipped('Functional tests must be called through phpunit on CLI');
163 }
164 $this->bootstrapUtility = new FunctionalTestCaseBootstrapUtility();
165 $this->instancePath = $this->bootstrapUtility->setUp(
166 get_class($this),
167 $this->coreExtensionsToLoad,
168 $this->testExtensionsToLoad,
169 $this->pathsToLinkInTestInstance,
170 $this->configurationToUseInTestInstance
171 );
172 }
173
174 /**
175 * Tear down destroys the instance and database.
176 *
177 * This method should be called with parent::tearDown() in your test cases!
178 *
179 * @throws Exception
180 * @return void
181 */
182 public function tearDown() {
183 if (!($this->bootstrapUtility instanceof FunctionalTestCaseBootstrapUtility)) {
184 throw new Exception(
185 'Bootstrap utility not set. Is parent::setUp() called in setUp()?',
186 1376826527
187 );
188 }
189 $this->bootstrapUtility->tearDown();
190 }
191
192 /**
193 * Get DatabaseConnection instance - $GLOBALS['TYPO3_DB']
194 *
195 * This method should be used instead of direct access to
196 * $GLOBALS['TYPO3_DB'] for easy IDE auto completion.
197 *
198 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
199 */
200 protected function getDatabase() {
201 return $GLOBALS['TYPO3_DB'];
202 }
203
204 /**
205 * Initialize backend user
206 *
207 * @param int $userUid uid of the user we want to initialize. This user must exist in the fixture file
208 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
209 * @throws Exception
210 */
211 protected function setUpBackendUserFromFixture($userUid) {
212 $this->importDataSet(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Fixtures/be_users.xml');
213 $database = $this->getDatabase();
214 $userRow = $database->exec_SELECTgetSingleRow('*', 'be_users', 'uid = ' . $userUid);
215
216 /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
217 $backendUser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
218 $sessionId = $backendUser->createSessionId();
219 $_SERVER['HTTP_COOKIE'] = 'be_typo_user=' . $sessionId . '; path=/';
220 $backendUser->id = $sessionId;
221 $backendUser->sendNoCacheHeaders = FALSE;
222 $backendUser->dontSetCookie = TRUE;
223 $backendUser->createUserSession($userRow);
224
225 $GLOBALS['BE_USER'] = $backendUser;
226 $GLOBALS['BE_USER']->start();
227 if (!is_array($GLOBALS['BE_USER']->user) || !$GLOBALS['BE_USER']->user['uid']) {
228 throw new Exception(
229 'Can not initialize backend user',
230 1377095807
231 );
232 }
233 $GLOBALS['BE_USER']->backendCheckLogin();
234
235 return $backendUser;
236 }
237
238 /**
239 * Imports a data set represented as XML into the test database,
240 *
241 * @param string $path Absolute path to the XML file containing the data set to load
242 * @return void
243 * @throws Exception
244 */
245 protected function importDataSet($path) {
246 if (!is_file($path)) {
247 throw new Exception(
248 'Fixture file ' . $path . ' not found',
249 1376746261
250 );
251 }
252
253 $database = $this->getDatabase();
254
255 $xml = simplexml_load_file($path);
256 $foreignKeys = array();
257
258 /** @var $table \SimpleXMLElement */
259 foreach ($xml->children() as $table) {
260 $insertArray = array();
261
262 /** @var $column \SimpleXMLElement */
263 foreach ($table->children() as $column) {
264 $columnName = $column->getName();
265 $columnValue = NULL;
266
267 if (isset($column['ref'])) {
268 list($tableName, $elementId) = explode('#', $column['ref']);
269 $columnValue = $foreignKeys[$tableName][$elementId];
270 } elseif (isset($column['is-NULL']) && ($column['is-NULL'] === 'yes')) {
271 $columnValue = NULL;
272 } else {
273 $columnValue = (string) $table->$columnName;
274 }
275
276 $insertArray[$columnName] = $columnValue;
277 }
278
279 $tableName = $table->getName();
280 $result = $database->exec_INSERTquery($tableName, $insertArray);
281 if ($result === FALSE) {
282 throw new Exception(
283 'Error when processing fixture file: ' . $path . ' Can not insert data to table ' . $tableName,
284 1376746262
285 );
286 }
287 if (isset($table['id'])) {
288 $elementId = (string) $table['id'];
289 $foreignKeys[$tableName][$elementId] = $database->sql_insert_id();
290 }
291 }
292 }
293
294 /**
295 * @param int $pageId
296 * @param array $typoScriptFiles
297 */
298 protected function setUpFrontendRootPage($pageId, array $typoScriptFiles = array()) {
299 $pageId = (int)$pageId;
300 $page = $this->getDatabase()->exec_SELECTgetSingleRow('*', 'pages', 'uid=' . $pageId);
301
302 if (empty($page)) {
303 $this->fail('Cannot set up frontend root page "' . $pageId . '"');
304 }
305
306 $pagesFields = array(
307 'is_siteroot' => 1
308 );
309
310 $this->getDatabase()->exec_UPDATEquery('pages', 'uid=' . $pageId, $pagesFields);
311
312 $templateFields = array(
313 'pid' => $pageId,
314 'title' => '',
315 'config' => '',
316 'clear' => 3,
317 'root' => 1,
318 );
319
320 foreach ($typoScriptFiles as $typoScriptFile) {
321 $templateFields['config'] .= '<INCLUDE_TYPOSCRIPT: source="FILE:' . $typoScriptFile . '">' . LF;
322 }
323
324 $this->getDatabase()->exec_INSERTquery('sys_template', $templateFields);
325 }
326
327 /**
328 * @param int $pageId
329 * @param int $languageId
330 * @param int $backendUserId
331 * @param int $workspaceId
332 * @param bool $failOnFailure
333 * @return Response
334 */
335 protected function getFrontendResponse($pageId, $languageId = 0, $backendUserId = 0, $workspaceId = 0, $failOnFailure = TRUE) {
336 $pageId = (int)$pageId;
337 $languageId = (int)$languageId;
338
339 if (defined('PHP_BINARY')) {
340 $phpExecutable = PHP_BINARY;
341 } else {
342 $phpExecutable = rtrim(PHP_BINDIR, '/') . '/php';
343 }
344
345 $additionalParameter = '';
346
347 if (!empty($backendUserId)) {
348 $additionalParameter .= '&backendUserId=' . (int)$backendUserId;
349 }
350 if (!empty($workspaceId)) {
351 $additionalParameter .= '&workspaceId=' . (int)$workspaceId;
352 }
353
354 $arguments = array(
355 'documentRoot' => $this->instancePath,
356 'requestUrl' => 'http://localhost/?id=' . $pageId . '&L=' . $languageId . $additionalParameter,
357 );
358
359 $commandParts = array(
360 escapeshellcmd($phpExecutable),
361 escapeshellarg(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Framework/Scripts/Request.php'),
362 escapeshellarg(json_encode($arguments)),
363 );
364
365 $command = trim(implode(' ', $commandParts));
366 $response = shell_exec($command);
367 $result = json_decode($response, TRUE);
368
369 if ($result === FALSE) {
370 $this->fail('Frontend Response is empty');
371 }
372
373 if ($failOnFailure && $result['status'] === Response::STATUS_Failure) {
374 $this->fail('Frontend Response has failure:' . LF . $result['error']);
375 }
376
377 $response = new Response($result['status'], $result['content'], $result['error']);
378 return $response;
379 }
380
381 }