[TASK] Unify use of getter for $GLOBALS['TYPO3_DB']
[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 * Array of folders that should be created inside the test instance document root.
141 *
142 * This property will stay empty in this abstract, so it is possible
143 * to just overwrite it in extending classes. Path noted here will
144 * be linked for every test of a test case and it is not possible to change
145 * the list of folders between single tests of a test case.
146 *
147 * Per default the following folder are created
148 * /fileadmin
149 * /typo3temp
150 * /typo3conf
151 * /typo3conf/ext
152 * /uploads
153 *
154 * To create additional folders add the paths to this array. Given paths are expected to be
155 * relative to the test instance root and have to begin with a slash. Example:
156 *
157 * array(
158 * 'fileadmin/user_upload'
159 * );
160 *
161 * @var array
162 */
163 protected $additionalFoldersToCreate = array();
164
165 /**
166 * Private utility class used in setUp() and tearDown(). Do NOT use in test cases!
167 *
168 * @var \TYPO3\CMS\Core\Tests\FunctionalTestCaseBootstrapUtility
169 */
170 private $bootstrapUtility = NULL;
171
172 /**
173 * Path to TYPO3 CMS test installation for this test case
174 *
175 * @var string
176 */
177 private $instancePath;
178
179 /**
180 * Set up creates a test instance and database.
181 *
182 * This method should be called with parent::setUp() in your test cases!
183 *
184 * @return void
185 */
186 public function setUp() {
187 if (!defined('ORIGINAL_ROOT')) {
188 $this->markTestSkipped('Functional tests must be called through phpunit on CLI');
189 }
190 $this->bootstrapUtility = new FunctionalTestCaseBootstrapUtility();
191 $this->instancePath = $this->bootstrapUtility->setUp(
192 get_class($this),
193 $this->coreExtensionsToLoad,
194 $this->testExtensionsToLoad,
195 $this->pathsToLinkInTestInstance,
196 $this->configurationToUseInTestInstance,
197 $this->additionalFoldersToCreate
198 );
199 }
200
201 /**
202 * Tear down destroys the instance and database.
203 *
204 * This method should be called with parent::tearDown() in your test cases!
205 *
206 * @throws Exception
207 * @return void
208 */
209 public function tearDown() {
210 if (!($this->bootstrapUtility instanceof FunctionalTestCaseBootstrapUtility)) {
211 throw new Exception(
212 'Bootstrap utility not set. Is parent::setUp() called in setUp()?',
213 1376826527
214 );
215 }
216 $this->bootstrapUtility->tearDown();
217 }
218
219 /**
220 * Get DatabaseConnection instance - $GLOBALS['TYPO3_DB']
221 *
222 * This method should be used instead of direct access to
223 * $GLOBALS['TYPO3_DB'] for easy IDE auto completion.
224 *
225 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
226 */
227 protected function getDatabaseConnection() {
228 return $GLOBALS['TYPO3_DB'];
229 }
230
231 /**
232 * Initialize backend user
233 *
234 * @param int $userUid uid of the user we want to initialize. This user must exist in the fixture file
235 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
236 * @throws Exception
237 */
238 protected function setUpBackendUserFromFixture($userUid) {
239 $this->importDataSet(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Fixtures/be_users.xml');
240 $database = $this->getDatabaseConnection();
241 $userRow = $database->exec_SELECTgetSingleRow('*', 'be_users', 'uid = ' . $userUid);
242
243 /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
244 $backendUser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
245 $sessionId = $backendUser->createSessionId();
246 $_SERVER['HTTP_COOKIE'] = 'be_typo_user=' . $sessionId . '; path=/';
247 $backendUser->id = $sessionId;
248 $backendUser->sendNoCacheHeaders = FALSE;
249 $backendUser->dontSetCookie = TRUE;
250 $backendUser->createUserSession($userRow);
251
252 $GLOBALS['BE_USER'] = $backendUser;
253 $GLOBALS['BE_USER']->start();
254 if (!is_array($GLOBALS['BE_USER']->user) || !$GLOBALS['BE_USER']->user['uid']) {
255 throw new Exception(
256 'Can not initialize backend user',
257 1377095807
258 );
259 }
260 $GLOBALS['BE_USER']->backendCheckLogin();
261
262 return $backendUser;
263 }
264
265 /**
266 * Imports a data set represented as XML into the test database,
267 *
268 * @param string $path Absolute path to the XML file containing the data set to load
269 * @return void
270 * @throws Exception
271 */
272 protected function importDataSet($path) {
273 if (!is_file($path)) {
274 throw new Exception(
275 'Fixture file ' . $path . ' not found',
276 1376746261
277 );
278 }
279
280 $database = $this->getDatabaseConnection();
281
282 $xml = simplexml_load_file($path);
283 $foreignKeys = array();
284
285 /** @var $table \SimpleXMLElement */
286 foreach ($xml->children() as $table) {
287 $insertArray = array();
288
289 /** @var $column \SimpleXMLElement */
290 foreach ($table->children() as $column) {
291 $columnName = $column->getName();
292 $columnValue = NULL;
293
294 if (isset($column['ref'])) {
295 list($tableName, $elementId) = explode('#', $column['ref']);
296 $columnValue = $foreignKeys[$tableName][$elementId];
297 } elseif (isset($column['is-NULL']) && ($column['is-NULL'] === 'yes')) {
298 $columnValue = NULL;
299 } else {
300 $columnValue = (string) $table->$columnName;
301 }
302
303 $insertArray[$columnName] = $columnValue;
304 }
305
306 $tableName = $table->getName();
307 $result = $database->exec_INSERTquery($tableName, $insertArray);
308 if ($result === FALSE) {
309 throw new Exception(
310 'Error when processing fixture file: ' . $path . ' Can not insert data to table ' . $tableName,
311 1376746262
312 );
313 }
314 if (isset($table['id'])) {
315 $elementId = (string) $table['id'];
316 $foreignKeys[$tableName][$elementId] = $database->sql_insert_id();
317 }
318 }
319 }
320
321 /**
322 * @param int $pageId
323 * @param array $typoScriptFiles
324 */
325 protected function setUpFrontendRootPage($pageId, array $typoScriptFiles = array()) {
326 $pageId = (int)$pageId;
327 $page = $this->getDatabaseConnection()->exec_SELECTgetSingleRow('*', 'pages', 'uid=' . $pageId);
328
329 if (empty($page)) {
330 $this->fail('Cannot set up frontend root page "' . $pageId . '"');
331 }
332
333 $pagesFields = array(
334 'is_siteroot' => 1
335 );
336
337 $this->getDatabaseConnection()->exec_UPDATEquery('pages', 'uid=' . $pageId, $pagesFields);
338
339 $templateFields = array(
340 'pid' => $pageId,
341 'title' => '',
342 'config' => '',
343 'clear' => 3,
344 'root' => 1,
345 );
346
347 foreach ($typoScriptFiles as $typoScriptFile) {
348 $templateFields['config'] .= '<INCLUDE_TYPOSCRIPT: source="FILE:' . $typoScriptFile . '">' . LF;
349 }
350
351 $this->getDatabaseConnection()->exec_INSERTquery('sys_template', $templateFields);
352 }
353
354 /**
355 * @param int $pageId
356 * @param int $languageId
357 * @param int $backendUserId
358 * @param int $workspaceId
359 * @param bool $failOnFailure
360 * @return Response
361 */
362 protected function getFrontendResponse($pageId, $languageId = 0, $backendUserId = 0, $workspaceId = 0, $failOnFailure = TRUE) {
363 $pageId = (int)$pageId;
364 $languageId = (int)$languageId;
365
366 if (defined('PHP_BINARY')) {
367 $phpExecutable = PHP_BINARY;
368 } else {
369 $phpExecutable = rtrim(PHP_BINDIR, '/') . '/php';
370 }
371
372 $additionalParameter = '';
373
374 if (!empty($backendUserId)) {
375 $additionalParameter .= '&backendUserId=' . (int)$backendUserId;
376 }
377 if (!empty($workspaceId)) {
378 $additionalParameter .= '&workspaceId=' . (int)$workspaceId;
379 }
380
381 $arguments = array(
382 'documentRoot' => $this->instancePath,
383 'requestUrl' => 'http://localhost/?id=' . $pageId . '&L=' . $languageId . $additionalParameter,
384 );
385
386 $commandParts = array(
387 escapeshellcmd($phpExecutable),
388 escapeshellarg(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Framework/Scripts/Request.php'),
389 escapeshellarg(json_encode($arguments)),
390 );
391
392 $command = trim(implode(' ', $commandParts));
393 $response = shell_exec($command);
394 $result = json_decode($response, TRUE);
395
396 if ($result === FALSE) {
397 $this->fail('Frontend Response is empty');
398 }
399
400 if ($failOnFailure && $result['status'] === Response::STATUS_Failure) {
401 $this->fail('Frontend Response has failure:' . LF . $result['error']);
402 }
403
404 $response = new Response($result['status'], $result['content'], $result['error']);
405 return $response;
406 }
407
408 }