Ejemplo n.º 1
0
	function setUp() {
		// Mark test as being run
		$this->originalIsRunningTest = self::$is_running_test;
		self::$is_running_test = true;
		
		// Remove password validation
		$this->originalMemberPasswordValidator = Member::password_validator();
		$this->originalRequirements = Requirements::backend();
		Member::set_password_validator(null);
		Cookie::set_report_errors(false);

		$className = get_class($this);
		$fixtureFile = eval("return {$className}::\$fixture_file;");
		
		// Set up fixture
		if($fixtureFile) {
			if(substr(DB::getConn()->currentDatabase(),0,5) != 'tmpdb') {
				//echo "Re-creating temp database... ";
				self::create_temp_db();
				//echo "done.\n";
			}

			// This code is a bit misplaced; we want some way of the whole session being reinitialised...
			Versioned::reading_stage(null);

			singleton('DataObject')->flushCache();

			$dbadmin = new DatabaseAdmin();
			$dbadmin->clearAllData();
			
			// We have to disable validation while we import the fixtures, as the order in
			// which they are imported doesnt guarantee valid relations until after the
			// import is complete.
			$validationenabled = DataObject::get_validation_enabled();
			DataObject::set_validation_enabled(false);
			$this->fixture = new YamlFixture($fixtureFile);
			$this->fixture->saveIntoDatabase();
			DataObject::set_validation_enabled($validationenabled);
		}
		
		// Set up email
		$this->originalMailer = Email::mailer();
		$this->mailer = new TestMailer();
		Email::set_mailer($this->mailer);
	}
 function setUp()
 {
     // Mark test as being run
     $this->originalIsRunningTest = self::$is_running_test;
     self::$is_running_test = true;
     // i18n needs to be set to the defaults or tests fail
     i18n::set_locale(i18n::default_locale());
     i18n::set_date_format(null);
     i18n::set_time_format(null);
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Cookie::set_report_errors(false);
     RootURLController::reset();
     Translatable::reset();
     Versioned::reset();
     DataObject::reset();
     SiteTree::reset();
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(new Session(array()));
     }
     $this->originalTheme = SSViewer::current_theme();
     // Save nested_urls state, so we can restore it later
     $this->originalNestedURLsState = SiteTree::nested_urls();
     $className = get_class($this);
     $fixtureFile = eval("return {$className}::\$fixture_file;");
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
         if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) {
             //echo "Re-creating temp database... ";
             self::create_temp_db();
             //echo "done.\n";
         }
         singleton('DataObject')->flushCache();
         self::empty_temp_db();
         foreach ($this->requireDefaultRecordsFrom as $className) {
             $instance = singleton($className);
             if (method_exists($instance, 'requireDefaultRecords')) {
                 $instance->requireDefaultRecords();
             }
             if (method_exists($instance, 'augmentDefaultRecords')) {
                 $instance->augmentDefaultRecords();
             }
         }
         if ($fixtureFile) {
             $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile);
             $i = 0;
             foreach ($fixtureFiles as $fixtureFilePath) {
                 $fixture = new YamlFixture($fixtureFilePath);
                 $fixture->saveIntoDatabase();
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Email::set_mailer($this->mailer);
     Email::send_all_emails_to(null);
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
 }
Ejemplo n.º 3
0
 /**
  * Test a URL request, returning a response object.
  * 
  * This method is the counterpart of Director::direct() that is used in functional testing.  It will execute the URL given,
  * 
  * @param string $url The URL to visit
  * @param array $postVars The $_POST & $_FILES variables
  * @param Session $session The {@link Session} object representing the current session.  By passing the same object to multiple
  * calls of Director::test(), you can simulate a persisted session.
  * @param string $httpMethod The HTTP method, such as GET or POST.  It will default to POST if postVars is set, GET otherwise.
  *  Overwritten by $postVars['_method'] if present.
  * @param string $body The HTTP body
  * @param array $headers HTTP headers with key-value pairs
  * @param array $cookies to populate $_COOKIE
  * @return SS_HTTPResponse
  * 
  * @uses getControllerForURL() The rule-lookup logic is handled by this.
  * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call.
  */
 static function test($url, $postVars = null, $session = null, $httpMethod = null, $body = null, $headers = null, $cookies = null)
 {
     // These are needed so that calling Director::test() doesnt muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics
     $oldStage = Versioned::current_stage();
     $getVars = array();
     if (!$httpMethod) {
         $httpMethod = $postVars || is_array($postVars) ? "POST" : "GET";
     }
     if (!$session) {
         $session = new Session(null);
     }
     // Back up the current values of the superglobals
     $existingRequestVars = isset($_REQUEST) ? $_REQUEST : array();
     $existingGetVars = isset($_GET) ? $_GET : array();
     $existingPostVars = isset($_POST) ? $_POST : array();
     $existingSessionVars = isset($_SESSION) ? $_SESSION : array();
     $existingCookies = isset($_COOKIE) ? $_COOKIE : array();
     $existingServer = isset($_SERVER) ? $_SERVER : array();
     $existingCookieReportErrors = Cookie::report_errors();
     $existingRequirementsBackend = Requirements::backend();
     Cookie::set_report_errors(false);
     Requirements::set_backend(new Requirements_Backend());
     // Handle absolute URLs
     if (@parse_url($url, PHP_URL_HOST) != '') {
         $bits = parse_url($url);
         $_SERVER['HTTP_HOST'] = $bits['host'];
         $url = Director::makeRelative($url);
     }
     $urlWithQuerystring = $url;
     if (strpos($url, '?') !== false) {
         list($url, $getVarsEncoded) = explode('?', $url, 2);
         parse_str($getVarsEncoded, $getVars);
     }
     // Replace the superglobals with appropriate test values
     $_REQUEST = array_merge((array) $getVars, (array) $postVars);
     $_GET = (array) $getVars;
     $_POST = (array) $postVars;
     $_SESSION = $session ? $session->inst_getAll() : array();
     $_COOKIE = (array) $cookies;
     $_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring;
     $req = new SS_HTTPRequest($httpMethod, $url, $getVars, $postVars, $body);
     if ($headers) {
         foreach ($headers as $k => $v) {
             $req->addHeader($k, $v);
         }
     }
     $result = Director::handleRequest($req, $session);
     // Restore the superglobals
     $_REQUEST = $existingRequestVars;
     $_GET = $existingGetVars;
     $_POST = $existingPostVars;
     $_SESSION = $existingSessionVars;
     $_COOKIE = $existingCookies;
     $_SERVER = $existingServer;
     Cookie::set_report_errors($existingCookieReportErrors);
     Requirements::set_backend($existingRequirementsBackend);
     // These are needed so that calling Director::test() doesnt muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics
     Versioned::reading_stage($oldStage);
     return $result;
 }
Ejemplo n.º 4
0
 public function setUp()
 {
     // We cannot run the tests on this abstract class.
     if (get_class($this) == "SapphireTest") {
         $this->skipTest = true;
     }
     if ($this->skipTest) {
         $this->markTestSkipped(sprintf('Skipping %s ', get_class($this)));
         return;
     }
     // Mark test as being run
     $this->originalIsRunningTest = self::$is_running_test;
     self::$is_running_test = true;
     // i18n needs to be set to the defaults or tests fail
     i18n::set_locale(i18n::default_locale());
     i18n::set_date_format(null);
     i18n::set_time_format(null);
     // Set default timezone consistently to avoid NZ-specific dependencies
     date_default_timezone_set('UTC');
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Cookie::set_report_errors(false);
     if (class_exists('RootURLController')) {
         RootURLController::reset();
     }
     if (class_exists('Translatable')) {
         Translatable::reset();
     }
     Versioned::reset();
     DataObject::reset();
     if (class_exists('SiteTree')) {
         SiteTree::reset();
     }
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(new Session(array()));
     }
     Security::$database_is_ready = null;
     $this->originalTheme = SSViewer::current_theme();
     if (class_exists('SiteTree')) {
         // Save nested_urls state, so we can restore it later
         $this->originalNestedURLsState = SiteTree::nested_urls();
     }
     $className = get_class($this);
     $fixtureFile = eval("return {$className}::\$fixture_file;");
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Todo: this could be a special test model
     $this->model = DataModel::inst();
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
         if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) {
             //echo "Re-creating temp database... ";
             self::create_temp_db();
             //echo "done.\n";
         }
         singleton('DataObject')->flushCache();
         self::empty_temp_db();
         foreach ($this->requireDefaultRecordsFrom as $className) {
             $instance = singleton($className);
             if (method_exists($instance, 'requireDefaultRecords')) {
                 $instance->requireDefaultRecords();
             }
             if (method_exists($instance, 'augmentDefaultRecords')) {
                 $instance->augmentDefaultRecords();
             }
         }
         if ($fixtureFile) {
             $pathForClass = $this->getCurrentAbsolutePath();
             $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile);
             $i = 0;
             foreach ($fixtureFiles as $fixtureFilePath) {
                 // Support fixture paths relative to the test class, rather than relative to webroot
                 // String checking is faster than file_exists() calls.
                 $isRelativeToFile = strpos('/', $fixtureFilePath) === false || preg_match('/^\\.\\./', $fixtureFilePath);
                 if ($isRelativeToFile) {
                     $resolvedPath = realpath($pathForClass . '/' . $fixtureFilePath);
                     if ($resolvedPath) {
                         $fixtureFilePath = $resolvedPath;
                     }
                 }
                 $fixture = new YamlFixture($fixtureFilePath);
                 $fixture->saveIntoDatabase($this->model);
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Email::set_mailer($this->mailer);
     Email::send_all_emails_to(null);
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
     // turn off template debugging
     SSViewer::set_source_file_comments(false);
     // Clear requirements
     Requirements::clear();
 }