[TASK] Split DataHandler::copyRecord_procBasedOnFieldType
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Tests / FunctionalTestCase.php
index d11ff9a..34e8535 100644 (file)
 <?php
 namespace TYPO3\CMS\Core\Tests;
 
-/***************************************************************
- * Copyright notice
+/*
+ * This file is part of the TYPO3 CMS project.
  *
- * (c) 2005-2013 Robert Lemke (robert@typo3.org)
- * All rights reserved
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
  *
- * This script is part of the TYPO3 project. The TYPO3 project is
- * free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
  *
- * The GNU General Public License can be found at
- * http://www.gnu.org/copyleft/gpl.html.
- *
- * This script is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * This copyright notice MUST APPEAR in all copies of the script!
- ***************************************************************/
+ * The TYPO3 project - inspiring people to share!
+ */
 
-use TYPO3\CMS\Core\Utility\GeneralUtility;
+use TYPO3\CMS\Core\Tests\Functional\Framework\Frontend\Response;
 
 /**
- * Base test case for functional tests.
+ * Base test case class for functional tests, all TYPO3 CMS
+ * functional tests should extend from this class!
+ *
+ * If functional tests need additional setUp() and tearDown() code,
+ * they *must* call parent::setUp() and parent::tearDown() to properly
+ * set up and destroy the test system.
+ *
+ * The functional test system creates a full new TYPO3 CMS instance
+ * within typo3temp/ of the base system and the bootstraps this TYPO3 instance.
+ * This abstract class takes care of creating this instance with its
+ * folder structure and a LocalConfiguration, creates an own database
+ * for each test run and imports tables of loaded extensions.
  *
- * Functional tests should extend this class. It provides methods to create
- * a new database with base data and methods to fiddle with test data.
+ * Functional tests must be run standalone (calling native phpunit
+ * directly) and can not be executed by eg. the ext:phpunit backend module.
+ * Additionally, the script must be called from the document root
+ * of the instance, otherwise path calculation is not successfully.
+ *
+ * Call whole functional test suite, example:
+ * - cd /var/www/t3master/foo  # Document root of CMS instance, here is index.php of frontend
+ * - ./typo3conf/ext/phpunit/Composer/vendor/bin/phpunit -c typo3/sysext/core/Build/FunctionalTests.xml
+ *
+ * Call single test case, example:
+ * - cd /var/www/t3master/foo  # Document root of CMS instance, here is index.php of frontend
+ * - ./typo3conf/ext/phpunit/Composer/vendor/bin/phpunit \
+ *     --process-isolation \
+ *     --bootstrap typo3/sysext/core/Build/FunctionalTestsBootstrap.php \
+ *     typo3/sysext/core/Tests/Functional/DataHandling/DataHandlerTest.php
  */
 abstract class FunctionalTestCase extends BaseTestCase {
-
        /**
-        * @var string Name of test database - Private since test cases must not fiddle with this!
+        * Core extensions to load.
+        *
+        * If the test case needs additional core extensions as requirement,
+        * they can be noted here and will be added to LocalConfiguration
+        * extension list and ext_tables.sql of those extensions will be applied.
+        *
+        * This property will stay empty in this abstract, so it is possible
+        * to just overwrite it in extending classes. Extensions noted here will
+        * be loaded for every test of a test case and it is not possible to change
+        * the list of loaded extensions between single tests of a test case.
+        *
+        * A default list of core extensions is always loaded.
+        *
+        * @see FunctionalTestCaseUtility $defaultActivatedCoreExtensions
+        * @var array
         */
-       private $testDatabaseName;
+       protected $coreExtensionsToLoad = array();
 
        /**
-        * Array of core extension names this test depends on
+        * Array of test/fixture extensions paths that should be loaded for a test.
+        *
+        * This property will stay empty in this abstract, so it is possible
+        * to just overwrite it in extending classes. Extensions noted here will
+        * be loaded for every test of a test case and it is not possible to change
+        * the list of loaded extensions between single tests of a test case.
+        *
+        * Given path is expected to be relative to your document root, example:
+        *
+        * array(
+        *   'typo3conf/ext/some_extension/Tests/Functional/Fixtures/Extensions/test_extension',
+        *   'typo3conf/ext/base_extension',
+        * );
+        *
+        * Extensions in this array are linked to the test instance, loaded
+        * and their ext_tables.sql will be applied.
         *
         * @var array
         */
-       protected $requiredExtensions = array();
+       protected $testExtensionsToLoad = array();
 
        /**
-        * Array of test/fixture extension names this test depends on
+        * Array of test/fixture folder or file paths that should be linked for a test.
+        *
+        * This property will stay empty in this abstract, so it is possible
+        * to just overwrite it in extending classes. Path noted here will
+        * be linked for every test of a test case and it is not possible to change
+        * the list of folders between single tests of a test case.
+        *
+        * array(
+        *   'link-source' => 'link-destination'
+        * );
+        *
+        * Given paths are expected to be relative to the test instance root.
+        * The array keys are the source paths and the array values are the destination
+        * paths, example:
+        *
+        * array(
+        *   'typo3/sysext/impext/Tests/Functional/Fixtures/Folders/fileadmin/user_upload' =>
+        *   'fileadmin/user_upload',
+        *   'typo3conf/ext/my_own_ext/Tests/Functional/Fixtures/Folders/uploads/tx_myownext' =>
+        *   'uploads/tx_myownext'
+        * );
+        *
+        * To be able to link from my_own_ext the extension path needs also to be registered in
+        * property $testExtensionsToLoad
         *
         * @var array
         */
-       protected $requiredTestExtensions = array();
+       protected $pathsToLinkInTestInstance = array();
 
        /**
-        * Absolute path to the test installation root folder
+        * This configuration array is merged with TYPO3_CONF_VARS
+        * that are set in default configuration and factory configuration
         *
-        * @var string
+        * @var array
         */
-       private $testInstallationPath;
+       protected $configurationToUseInTestInstance = array();
 
        /**
-        * Set up creates a test database and fills with data.
+        * Array of folders that should be created inside the test instance document root.
         *
-        * This method should be called with parent::setUp() in your test cases!
+        * This property will stay empty in this abstract, so it is possible
+        * to just overwrite it in extending classes. Path noted here will
+        * be linked for every test of a test case and it is not possible to change
+        * the list of folders between single tests of a test case.
         *
-        * @return void
-        */
-       public function setUp() {
-               $this->calculateTestInstallationPath();
-               $this->setUpTestInstallationFolderStructure();
-               $this->copyMultipleTestExtensionsToExtFolder($this->requiredTestExtensions);
-               $this->setUpLocalConfiguration();
-               $this->setUpBasicTypo3Bootstrap();
-               $this->setUpTestDatabaseConnection();
-               $this->createDatabaseStructure();
-               \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadExtensionTables(TRUE);
-       }
-
-       /**
-        * Tear down.
+        * Per default the following folder are created
+        * /fileadmin
+        * /typo3temp
+        * /typo3conf
+        * /typo3conf/ext
+        * /uploads
         *
-        * This method should be called with parent::setUp() in your test cases!
+        * To create additional folders add the paths to this array. Given paths are expected to be
+        * relative to the test instance root and have to begin with a slash. Example:
         *
-        * @throws \TYPO3\CMS\Core\Tests\Exception
-        * @return void
+        * array(
+        *   'fileadmin/user_upload'
+        * );
+        *
+        * @var array
         */
-       public function tearDown() {
-               if (empty($this->testDatabaseName)) {
-                       throw new Exception(
-                               'Test database name not set. parent::setUp called?',
-                               1376579421
-                       );
-               }
-               $this->tearDownTestDatabase();
-               $this->tearDownTestInstallationFolder();
-       }
+       protected $additionalFoldersToCreate = array();
 
        /**
-        * Calculates path to the test TYPO3 installation
+        * Private utility class used in setUp() and tearDown(). Do NOT use in test cases!
         *
-        * @return void
+        * @var \TYPO3\CMS\Core\Tests\FunctionalTestCaseBootstrapUtility
         */
-       private function calculateTestInstallationPath() {
-               // @TODO: same id for filesystem & database name
-               $this->testInstallationPath = ORIGINAL_ROOT . '/typo3temp/'. uniqid('functional');
-       }
+       private $bootstrapUtility = NULL;
 
        /**
-        * Calculates test database name based on original database name
+        * Path to TYPO3 CMS test installation for this test case
         *
-        * @param string $originalDatabaseName Name of original database
-        * @return void
+        * @var string
         */
-       private function calculateTestDatabaseName($originalDatabaseName) {
-               // @TODO: same id for filesystem & database name
-               $this->testDatabaseName = uniqid(strtolower($originalDatabaseName . '_test_'));
-       }
+       private $instancePath;
 
        /**
-        * Creates folder structure of the test installation and link TYPO3 core
+        * Set up creates a test instance and database.
+        *
+        * This method should be called with parent::setUp() in your test cases!
         *
-        * @throws Exception
         * @return void
         */
-       private function setUpTestInstallationFolderStructure() {
-               $neededFolders = array(
-                       '',
-                       '/fileadmin',
-                       '/typo3temp',
-                       '/typo3conf',
-                       '/typo3conf/ext',
-                       '/uploads'
-               );
-               foreach ($neededFolders as $folder) {
-                       $success = mkdir($this->testInstallationPath . $folder);
-                       if (!$success) {
-                               throw new Exception('Can not create directory: ' . $this->testInstallationPath . $folder, 1376657189);
-                       }
+       protected function setUp() {
+               if (!defined('ORIGINAL_ROOT')) {
+                       $this->markTestSkipped('Functional tests must be called through phpunit on CLI');
                }
-
-               $neededLinks = array(
-                       '/typo3' => '/typo3',
-                       '/index.php' => '/index.php'
+               $this->bootstrapUtility = new FunctionalTestCaseBootstrapUtility();
+               $this->instancePath = $this->bootstrapUtility->setUp(
+                       get_class($this),
+                       $this->coreExtensionsToLoad,
+                       $this->testExtensionsToLoad,
+                       $this->pathsToLinkInTestInstance,
+                       $this->configurationToUseInTestInstance,
+                       $this->additionalFoldersToCreate
                );
-               foreach ($neededLinks as $from => $to) {
-                       $success = symlink(ORIGINAL_ROOT . $from, $this->testInstallationPath . $to);
-                       if (!$success) {
-                               throw new Exception('Can not link file : ' . ORIGINAL_ROOT . $from . ' to: ' . $this->testInstallationPath . $to, 1376657199);
-                       }
-               }
        }
 
        /**
-        * Create new $GLOBALS['TYPO3_DB'] on test database
+        * Get DatabaseConnection instance - $GLOBALS['TYPO3_DB']
         *
-        * @throws \TYPO3\CMS\Core\Tests\Exception
-        * @return void
+        * This method should be used instead of direct access to
+        * $GLOBALS['TYPO3_DB'] for easy IDE auto completion.
+        *
+        * @return \TYPO3\CMS\Core\Database\DatabaseConnection
         */
-       private function setUpTestDatabaseConnection() {
-               \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->initializeTypo3DbGlobal();
-               $GLOBALS['TYPO3_DB']->sql_pconnect();
-               $createDatabaseResult = $GLOBALS['TYPO3_DB']->admin_query('CREATE DATABASE `' . $this->testDatabaseName . '`');
-               if (!$createDatabaseResult) {
-                       throw new Exception(
-                               'Unable to create database with name ' . $this->testDatabaseName . ' permission problem?',
-                               1376579070
-                       );
-               }
-               $GLOBALS['TYPO3_DB']->setDatabaseName($this->testDatabaseName);
-               $GLOBALS['TYPO3_DB']->sql_select_db($this->testDatabaseName);
+       protected function getDatabaseConnection() {
+               return $GLOBALS['TYPO3_DB'];
        }
 
        /**
-        * Creates LocalConfiguration.php file in the test installation
+        * Initialize backend user
         *
-        * @return void
+        * @param int $userUid uid of the user we want to initialize. This user must exist in the fixture file
+        * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
+        * @throws Exception
         */
-       private function setUpLocalConfiguration() {
-               $localConfigurationFile = $this->testInstallationPath . '/typo3conf/LocalConfiguration.php';
-               $originalConfigurationArray = require ORIGINAL_ROOT . '/typo3conf/LocalConfiguration.php';
-               $localConfigurationArray = require ORIGINAL_ROOT .'/typo3/sysext/core/Configuration/FactoryConfiguration.php';
-
-
-               $additionalConfiguration = array('DB' => $originalConfigurationArray['DB']);
-               $this->calculateTestDatabaseName($additionalConfiguration['DB']['database']);
-               $additionalConfiguration['DB']['database'] = $this->testDatabaseName;
-               $localConfigurationArray['DB'] = $additionalConfiguration['DB'];
-
-               $extensions = array_merge($this->requiredExtensions, $this->requiredTestExtensions);
-               $localConfigurationArray['EXT']['extListArray'] = $extensions;
-
-               $result = $this->writeFile(
-                       $localConfigurationFile,
-                       '<?php' . chr(10) .
-                       'return ' .
-                       $this->arrayExport(
-                               $localConfigurationArray
-                       ) .
-                       ';' . chr(10) .
-                       '?>'
-               );
-               if (!$result) {
-                       throw new Exception('Can not write local configuration', 1376657277);
+       protected function setUpBackendUserFromFixture($userUid) {
+               $this->importDataSet(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Fixtures/be_users.xml');
+               $database = $this->getDatabaseConnection();
+               $userRow = $database->exec_SELECTgetSingleRow('*', 'be_users', 'uid = ' . (int)$userUid);
+
+               /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
+               $backendUser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class);
+               $sessionId = $backendUser->createSessionId();
+               $_COOKIE['be_typo_user'] = $sessionId;
+               $backendUser->id = $sessionId;
+               $backendUser->sendNoCacheHeaders = FALSE;
+               $backendUser->dontSetCookie = TRUE;
+               $backendUser->createUserSession($userRow);
+
+               $GLOBALS['BE_USER'] = $backendUser;
+               $GLOBALS['BE_USER']->start();
+               if (!is_array($GLOBALS['BE_USER']->user) || !$GLOBALS['BE_USER']->user['uid']) {
+                       throw new Exception(
+                               'Can not initialize backend user',
+                               1377095807
+                       );
                }
-       }
+               $GLOBALS['BE_USER']->backendCheckLogin();
 
-       /**
-        * Bootstrap basic TYPO3
-        *
-        * @return void
-        */
-       private function setUpBasicTypo3Bootstrap() {
-               $_SERVER['PWD'] = $this->testInstallationPath;
-               $_SERVER['argv'][0] = 'index.php';
-
-               define('TYPO3_MODE', 'BE');
-               define('TYPO3_cliMode', TRUE);
-
-               require $this->testInstallationPath . '/typo3/sysext/core/Classes/Core/CliBootstrap.php';
-               \TYPO3\CMS\Core\Core\CliBootstrap::checkEnvironmentOrDie();
-
-               require $this->testInstallationPath . '/typo3/sysext/core/Classes/Core/Bootstrap.php';
-               \TYPO3\CMS\Core\Core\Bootstrap::getInstance()
-                       ->baseSetup('')
-                       ->loadConfigurationAndInitialize(FALSE)
-                       ->loadTypo3LoadedExtAndExtLocalconf(FALSE)
-                       ->applyAdditionalConfigurationSettings();
+               return $backendUser;
        }
 
        /**
-        * Drop the test database.
+        * Imports a data set represented as XML into the test database,
         *
-        * @throws \TYPO3\CMS\Core\Tests\Exception
+        * @param string $path Absolute path to the XML file containing the data set to load
         * @return void
+        * @throws Exception
         */
-       private function tearDownTestDatabase() {
-               $result = $GLOBALS['TYPO3_DB']->admin_query('DROP DATABASE `' . $this->testDatabaseName . '`');
-               if (!$result) {
+       protected function importDataSet($path) {
+               if (!is_file($path)) {
                        throw new Exception(
-                               'Dropping test database ' . $this->testDatabaseName . ' failed',
-                               1376583188
+                               'Fixture file ' . $path . ' not found',
+                               1376746261
                        );
                }
-       }
 
-       /**
-        * Removes test installation folder
-        *
-        * @throws \TYPO3\CMS\Core\Tests\Exception
-        * @return void
-        */
-       private function tearDownTestInstallationFolder() {
-               $success = $this->rmdir($this->testInstallationPath, TRUE);
-               if (!$success) {
-                       throw new Exception('Can not remove folder: ' . $this->testInstallationPath, 1376657210);
-               }
-       }
+               $database = $this->getDatabaseConnection();
 
-       /**
-        * Create tables and import static rows
-        *
-        * @return void
-        */
-       private function createDatabaseStructure() {
-               /** @var \TYPO3\CMS\Install\Service\SqlSchemaMigrationService $schemaMigrationService */
-               $schemaMigrationService = GeneralUtility::makeInstance('TYPO3\\CMS\\Install\\Service\\SqlSchemaMigrationService');
-               /** @var \TYPO3\CMS\Install\Service\SqlExpectedSchemaService $expectedSchemaService */
-               $expectedSchemaService = GeneralUtility::makeInstance('TYPO3\\CMS\\Install\\Service\\SqlExpectedSchemaService');
-
-               // Raw concatenated ext_tables.sql and friends string
-               $expectedSchemaString = $expectedSchemaService->getTablesDefinitionString(TRUE);
-               $statements = $schemaMigrationService->getStatementArray($expectedSchemaString, TRUE);
-               list($_, $insertCount) = $schemaMigrationService->getCreateTables($statements, TRUE);
-
-               $fieldDefinitionsFile = $schemaMigrationService->getFieldDefinitions_fileContent($expectedSchemaString);
-               $fieldDefinitionsDatabase = $schemaMigrationService->getFieldDefinitions_database();
-               $difference = $schemaMigrationService->getDatabaseExtra($fieldDefinitionsFile, $fieldDefinitionsDatabase);
-               $updateStatements = $schemaMigrationService->getUpdateSuggestions($difference);
-
-               $schemaMigrationService->performUpdateQueries($updateStatements['add'], $updateStatements['add']);
-               $schemaMigrationService->performUpdateQueries($updateStatements['change'], $updateStatements['change']);
-               $schemaMigrationService->performUpdateQueries($updateStatements['create_table'], $updateStatements['create_table']);
-
-               foreach ($insertCount as $table => $count) {
-                       $insertStatements = $schemaMigrationService->getTableInsertStatements($statements, $table);
-                       foreach ($insertStatements as $insertQuery) {
-                               $insertQuery = rtrim($insertQuery, ';');
-                               $GLOBALS['TYPO3_DB']->admin_query($insertQuery);
-                       }
-               }
-       }
+               $xml = simplexml_load_file($path);
+               $foreignKeys = array();
 
-       /**
-        * Copy all needed test extensions to the typo3conf/ext folder of the test installation
-        *
-        * @param array $extensionNames array containing extension names (name should be the same as a folder name)
-        * @return void
-        */
-       private function copyMultipleTestExtensionsToExtFolder(array $extensionNames) {
-               foreach ($extensionNames as $extensionName) {
-                       $extensionPath = $this->getFixtureExtensionPath($extensionName);
-                       $this->copyTestExtensionToExtFolder($extensionPath);
-               }
-       }
+               /** @var $table \SimpleXMLElement */
+               foreach ($xml->children() as $table) {
+                       $insertArray = array();
 
-       /**
-        * Copy single single test extension to the typo3conf/ext folder of the test installation
-        *
-        * @param string $sourceFolderPath absolute path to extension
-        * @throws \TYPO3\CMS\Core\Tests\Exception
-        * @return void
-        */
-       private function copyTestExtensionToExtFolder($sourceFolderPath) {
-               if (!stristr(PHP_OS, 'darwin') && stristr(PHP_OS, 'win')) {
-                       // Windows
-                       $sourceFolderPath = rtrim($sourceFolderPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
-                       $files = GeneralUtility::getAllFilesAndFoldersInPath(array(), $sourceFolderPath, '', TRUE);
-                       $files = GeneralUtility::removePrefixPathFromList($files, $sourceFolderPath);
-
-                       foreach ($files as $fileName) {
-                               $destinationPath = $this->testInstallationPath . DIRECTORY_SEPARATOR . 'typo3conf' . DIRECTORY_SEPARATOR . 'ext'. DIRECTORY_SEPARATOR . $fileName;
-                               $success = copy($sourceFolderPath . $fileName, $destinationPath);
-                               if (!$success) {
-                                       throw new Exception('Can not copy file: ' . $fileName . ' to ' . $destinationPath, 1376657187);
+                       /** @var $column \SimpleXMLElement */
+                       foreach ($table->children() as $column) {
+                               $columnName = $column->getName();
+                               $columnValue = NULL;
+
+                               if (isset($column['ref'])) {
+                                       list($tableName, $elementId) = explode('#', $column['ref']);
+                                       $columnValue = $foreignKeys[$tableName][$elementId];
+                               } elseif (isset($column['is-NULL']) && ($column['is-NULL'] === 'yes')) {
+                                       $columnValue = NULL;
+                               } else {
+                                       $columnValue = (string)$table->$columnName;
                                }
+
+                               $insertArray[$columnName] = $columnValue;
                        }
-               } else {
-                       //linux
-                       $destinationPath = $this->testInstallationPath . DIRECTORY_SEPARATOR . 'typo3conf' . DIRECTORY_SEPARATOR . 'ext'. DIRECTORY_SEPARATOR. basename($sourceFolderPath);
-                       $success = symlink($sourceFolderPath, $destinationPath);
-                       if (!$success) {
-                               throw new Exception('Can not link folder: ' . $sourceFolderPath . ' to ' . $destinationPath, 1376657187);
+
+                       $tableName = $table->getName();
+                       $result = $database->exec_INSERTquery($tableName, $insertArray);
+                       if ($result === FALSE) {
+                               throw new Exception(
+                                       'Error when processing fixture file: ' . $path . ' Can not insert data to table ' . $tableName . ': ' . $database->sql_error(),
+                                       1376746262
+                               );
+                       }
+                       if (isset($table['id'])) {
+                               $elementId = (string)$table['id'];
+                               $foreignKeys[$tableName][$elementId] = $database->sql_insert_id();
                        }
                }
        }
 
        /**
-        * Returns absolute path to the fixture
-        * if called with empty $relativeFixturePath, returns path to the base folder for fixtures
-        *
-        * @param string $relativeFixturePath
-        * @return string absolute path with trailing slash
-        * @TODO: Figure out if this is useful
+        * @param int $pageId
+        * @param array $typoScriptFiles
         */
-       protected function getFixturePath($relativeFixturePath = '') {
-               $relativeFixturePath = !empty($relativeFixturePath) ? $relativeFixturePath . DIRECTORY_SEPARATOR : '';
-               $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR . $relativeFixturePath;
-               return $path;
-       }
+       protected function setUpFrontendRootPage($pageId, array $typoScriptFiles = array()) {
+               $pageId = (int)$pageId;
+               $page = $this->getDatabaseConnection()->exec_SELECTgetSingleRow('*', 'pages', 'uid=' . $pageId);
 
-       /**
-        * Returns absolute path to the fixture extension
-        * if called with empty name, returns path to the base folder for test extensions
-        *
-        * @param string $name
-        * @return string absolute path with trailing slash
-        * @TODO: Figure out if this is useful
-        */
-       protected function getFixtureExtensionPath($name = '') {
-               $name = !empty($name) ? $name . DIRECTORY_SEPARATOR : '';
-               $path = $this->getFixturePath() . 'extensions' . DIRECTORY_SEPARATOR . $name;
-               return $path;
-       }
+               if (empty($page)) {
+                       $this->fail('Cannot set up frontend root page "' . $pageId . '"');
+               }
 
-       /**
-        * METHODS COPIED FROM GeneralUtility
-        */
+               $pagesFields = array(
+                       'is_siteroot' => 1
+               );
 
-       /**
-        * COPIED FROM GeneralUtility
-        *
-        * Wrapper function for rmdir, allowing recursive deletion of folders and files
-        *
-        * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
-        * @param boolean $removeNonEmpty Allow deletion of non-empty directories
-        * @return boolean TRUE if @rmdir went well!
-        */
-       private function rmdir($path, $removeNonEmpty = FALSE) {
-               $OK = FALSE;
-               // Remove trailing slash
-               $path = preg_replace('|/$|', '', $path);
-               if (file_exists($path)) {
-                       $OK = TRUE;
-                       if (!is_link($path) && is_dir($path)) {
-                               if ($removeNonEmpty == TRUE && ($handle = opendir($path))) {
-                                       while ($OK && FALSE !== ($file = readdir($handle))) {
-                                               if ($file == '.' || $file == '..') {
-                                                       continue;
-                                               }
-                                               $OK = $this->rmdir($path . '/' . $file, $removeNonEmpty);
-                                       }
-                                       closedir($handle);
-                               }
-                               if ($OK) {
-                                       $OK = @rmdir($path);
-                               }
-                       } else {
-                               // If $path is a file, simply remove it
-                               $OK = unlink($path);
-                       }
-                       clearstatcache();
-               } elseif (is_link($path)) {
-                       $OK = unlink($path);
-                       clearstatcache();
+               $this->getDatabaseConnection()->exec_UPDATEquery('pages', 'uid=' . $pageId, $pagesFields);
+
+               $templateFields = array(
+                       'pid' => $pageId,
+                       'title' => '',
+                       'config' => '',
+                       'clear' => 3,
+                       'root' => 1,
+               );
+
+               foreach ($typoScriptFiles as $typoScriptFile) {
+                       $templateFields['config'] .= '<INCLUDE_TYPOSCRIPT: source="FILE:' . $typoScriptFile . '">' . LF;
                }
-               return $OK;
+
+               $this->getDatabaseConnection()->exec_INSERTquery('sys_template', $templateFields);
        }
 
        /**
-        * Writes $content to the file $file
-        *
-        * @param string $file Filepath to write to
-        * @param string $content Content to write
-        * @return boolean TRUE if the file was successfully opened and written to.
+        * @param int $pageId
+        * @param int $languageId
+        * @param int $backendUserId
+        * @param int $workspaceId
+        * @param bool $failOnFailure
+        * @param int $frontendUserId
+        * @return Response
         */
-       private function writeFile($file, $content) {
-               if ($fd = fopen($file, 'wb')) {
-                       $res = fwrite($fd, $content);
-                       fclose($fd);
-                       if ($res === FALSE) {
-                               return FALSE;
-                       }
-                       return TRUE;
+       protected function getFrontendResponse($pageId, $languageId = 0, $backendUserId = 0, $workspaceId = 0, $failOnFailure = TRUE, $frontendUserId = 0) {
+               $pageId = (int)$pageId;
+               $languageId = (int)$languageId;
+
+               $additionalParameter = '';
+
+               if (!empty($frontendUserId)) {
+                       $additionalParameter .= '&frontendUserId=' . (int)$frontendUserId;
+               }
+               if (!empty($backendUserId)) {
+                       $additionalParameter .= '&backendUserId=' . (int)$backendUserId;
+               }
+               if (!empty($workspaceId)) {
+                       $additionalParameter .= '&workspaceId=' . (int)$workspaceId;
                }
-               return FALSE;
-       }
 
-       /**
-        * METHODS COPIED FROM ArrayUtility
-        */
+               $arguments = array(
+                       'documentRoot' => $this->instancePath,
+                       'requestUrl' => 'http://localhost/?id=' . $pageId . '&L=' . $languageId . $additionalParameter,
+               );
 
-       /**
-        * Exports an array as string.
-        * Similar to var_export(), but representation follows the TYPO3 core CGL.
-        *
-        * See unit tests for detailed examples
-        *
-        * @param array $array Array to export
-        * @param integer $level Internal level used for recursion, do *not* set from outside!
-        * @return string String representation of array
-        * @throws \RuntimeException
-        */
-       private function arrayExport(array $array = array(), $level = 0) {
-               $lines = 'array(' . chr(10);
-               $level++;
-               $writeKeyIndex = FALSE;
-               $expectedKeyIndex = 0;
-               foreach ($array as $key => $value) {
-                       if ($key === $expectedKeyIndex) {
-                               $expectedKeyIndex++;
-                       } else {
-                               // Found a non integer or non consecutive key, so we can break here
-                               $writeKeyIndex = TRUE;
-                               break;
-                       }
+               $template = new \Text_Template(ORIGINAL_ROOT . 'typo3/sysext/core/Tests/Functional/Fixtures/Frontend/request.tpl');
+               $template->setVar(
+                       array(
+                               'arguments' => var_export($arguments, TRUE),
+                               'originalRoot' => ORIGINAL_ROOT,
+                       )
+               );
+
+               $php = \PHPUnit_Util_PHP::factory();
+               $response = $php->runJob($template->render());
+               $result = json_decode($response['stdout'], TRUE);
+
+               if ($result === NULL) {
+                       $this->fail('Frontend Response is empty');
                }
-               foreach ($array as $key => $value) {
-                       // Indention
-                       $lines .= str_repeat(chr(9), $level);
-                       if ($writeKeyIndex) {
-                               // Numeric / string keys
-                               $lines .= is_int($key) ? $key . ' => ' : '\'' . $key . '\' => ';
-                       }
-                       if (is_array($value)) {
-                               if (count($value) > 0) {
-                                       $lines .= $this->arrayExport($value, $level);
-                               } else {
-                                       $lines .= 'array(),' . chr(10);
-                               }
-                       } elseif (is_int($value) || is_float($value)) {
-                               $lines .= $value . ',' . chr(10);
-                       } elseif (is_null($value)) {
-                               $lines .= 'NULL' . ',' . chr(10);
-                       } elseif (is_bool($value)) {
-                               $lines .= $value ? 'TRUE' : 'FALSE';
-                               $lines .= ',' . chr(10);
-                       } elseif (is_string($value)) {
-                               // Quote \ to \\
-                               $stringContent = str_replace('\\', '\\\\', $value);
-                               // Quote ' to \'
-                               $stringContent = str_replace('\'', '\\\'', $stringContent);
-                               $lines .= '\'' . $stringContent . '\'' . ',' . chr(10);
-                       } else {
-                               throw new \RuntimeException('Objects are not supported', 1342294986);
-                       }
+
+               if ($failOnFailure && $result['status'] === Response::STATUS_Failure) {
+                       $this->fail('Frontend Response has failure:' . LF . $result['error']);
                }
-               $lines .= str_repeat(chr(9), ($level - 1)) . ')' . ($level - 1 == 0 ? '' : ',' . chr(10));
-               return $lines;
+
+               $response = new Response($result['status'], $result['content'], $result['error']);
+               return $response;
        }
+
 }
-?>
\ No newline at end of file