public function setUp()
 {
     parent::setUp();
     Config::nest();
     Injector::nest();
     $this->securityWasEnabled = SecurityToken::is_enabled();
     // Check dependencies
     if (!class_exists('Phockito')) {
         $this->skipTest = true;
         return $this->markTestSkipped("These tests need the Phockito module installed to run");
     }
     // Reset config
     Config::inst()->update('SpellController', 'required_permission', 'CMS_ACCESS_CMSMain');
     Config::inst()->remove('SpellController', 'locales');
     Config::inst()->update('SpellController', 'locales', array('en_US', 'en_NZ', 'fr_FR'));
     Config::inst()->update('SpellController', 'enable_security_token', true);
     SecurityToken::enable();
     // Setup mock for testing provider
     $spellChecker = Phockito::mock('SpellProvider');
     Phockito::when($spellChecker)->checkWords('en_NZ', array('collor', 'colour', 'color', 'onee', 'correct'))->return(array('collor', 'color', 'onee'));
     Phockito::when($spellChecker)->checkWords('en_US', array('collor', 'colour', 'color', 'onee', 'correct'))->return(array('collor', 'colour', 'onee'));
     Phockito::when($spellChecker)->getSuggestions('en_NZ', 'collor')->return(array('collar', 'colour'));
     Phockito::when($spellChecker)->getSuggestions('en_US', 'collor')->return(array('collar', 'color'));
     Injector::inst()->registerService($spellChecker, 'SpellProvider');
 }
Esempio n. 2
0
 public function setUp()
 {
     parent::setUp();
     SS_Datetime::clear_mock_now();
     Injector::nest();
     Injector::inst()->load(array('DNProject' => 'DeploynautTest_Project'));
     // Set temp location
     $this->setTemporaryPath(TEMP_FOLDER . '/deploynaut_test/envs');
 }
 public function setUp()
 {
     parent::setUp();
     HybridSessionAbstractTest_TestCookieBackend::$override_headers_sent = false;
     Injector::nest();
     Injector::inst()->registerService(new HybridSessionAbstractTest_TestCookieBackend(), 'HybridSessionStore_Cookie');
     SS_Datetime::set_mock_now('2010-03-15 12:00:00');
     if (get_class() === get_class($this)) {
         $this->markTestSkipped("Skipping abstract test");
         $this->skipTest = true;
     }
 }
 public function setUp()
 {
     parent::setUp();
     Injector::nest();
     Injector::inst()->unregisterAllObjects();
     // Mock service
     Config::nest();
     Config::inst()->update('Injector', 'AkismetService', 'AkismetTest_Service');
     Config::inst()->update('AkismetSpamProtector', 'api_key', 'dummykey');
     AkismetSpamProtector::set_api_key(null);
     // Reset options to reasonable default
     Config::inst()->remove('AkismetSpamProtector', 'save_spam');
     Config::inst()->remove('AkismetSpamProtector', 'require_confirmation');
     Config::inst()->remove('AkismetSpamProtector', 'bypass_members');
     Config::inst()->update('AkismetSpamProtector', 'bypass_permission', 'ADMIN');
 }
 public function setUp()
 {
     parent::setUp();
     // Required for testRequestFilterInDirectorTest
     Injector::nest();
     // Hold the original request URI once so it doesn't get overwritten
     if (!self::$originalRequestURI) {
         self::$originalRequestURI = $_SERVER['REQUEST_URI'];
     }
     $this->originalGet = $_GET;
     $this->originalSession = $_SESSION;
     Config::inst()->update('Director', 'rules', array('DirectorTestRule/$Action/$ID/$OtherID' => 'DirectorTestRequest_Controller', 'en-nz/$Action/$ID/$OtherID' => array('Controller' => 'DirectorTestRequest_Controller', 'Locale' => 'en_NZ')));
     $headers = array('HTTP_X_FORWARDED_PROTOCOL', 'HTTPS', 'SSL');
     foreach ($headers as $header) {
         if (isset($_SERVER[$header])) {
             $this->originalProtocolHeaders[$header] = $_SERVER[$header];
         }
     }
 }
 public function setUp()
 {
     parent::setUp();
     Injector::nest();
     // Check dependencies
     if (!class_exists('Phockito')) {
         $this->skipTest = true;
         return $this->markTestSkipped("These tests need the Phockito module installed to run");
     }
     // Mock link checker
     $checker = Phockito::mock('LinkChecker');
     Phockito::when($checker)->checkLink('http://www.working.com')->return(200);
     Phockito::when($checker)->checkLink('http://www.broken.com/url/thing')->return(404);
     Phockito::when($checker)->checkLink('http://www.broken.com')->return(403);
     Phockito::when($checker)->checkLink('http://www.nodomain.com')->return(0);
     Phockito::when($checker)->checkLink('/internal/link')->return(null);
     Phockito::when($checker)->checkLink('[sitetree_link,id=9999]')->return(null);
     Phockito::when($checker)->checkLink('home')->return(null);
     Phockito::when($checker)->checkLink('broken-internal')->return(null);
     Phockito::when($checker)->checkLink('[sitetree_link,id=1]')->return(null);
     Phockito::when($checker)->checkLink(Hamcrest_Matchers::anything())->return(404);
     Injector::inst()->registerService($checker, 'LinkChecker');
 }
 /**
  * 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, and
  * return the result as an SS_HTTPResponse object.
  *
  * @uses getControllerForURL() The rule-lookup logic is handled by this.
  * @uses Controller::run() Handles the page logic for a Director::direct() call.
  *
  * @param string $url The URL to visit.
  * @param array $postVars The $_POST & $_FILES variables.
  * @param array|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|Cookie_Backend $cookies to populate $_COOKIE.
  * @param HTTP_Request $request The {@see HTTP_Request} object generated as a part of this request.
  *
  * @return SS_HTTPResponse
  *
  * @throws SS_HTTPResponse_Exception
  */
 public static function test($url, $postVars = null, $session = array(), $httpMethod = null, $body = null, $headers = array(), $cookies = array(), &$request = null)
 {
     Config::nest();
     Injector::nest();
     // These are needed so that calling Director::test() does not muck with whoever is calling it.
     // Really, it's some inappropriate coupling and should be resolved by making less use of statics.
     $oldReadingMode = Versioned::get_reading_mode();
     $getVars = array();
     if (!$httpMethod) {
         $httpMethod = $postVars || is_array($postVars) ? "POST" : "GET";
     }
     if (!$session) {
         $session = Injector::inst()->create('Session', array());
     }
     $cookieJar = $cookies instanceof Cookie_Backend ? $cookies : Injector::inst()->createWithArgs('Cookie_Backend', array($cookies ?: array()));
     // 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();
     $existingRequirementsBackend = Requirements::backend();
     Config::inst()->update('Cookie', 'report_errors', false);
     Requirements::set_backend(Injector::inst()->create('Requirements_Backend'));
     // Set callback to invoke prior to return
     $onCleanup = function () use($existingRequestVars, $existingGetVars, $existingPostVars, $existingSessionVars, $existingCookies, $existingServer, $existingRequirementsBackend, $oldReadingMode) {
         // Restore the super globals
         $_REQUEST = $existingRequestVars;
         $_GET = $existingGetVars;
         $_POST = $existingPostVars;
         $_SESSION = $existingSessionVars;
         $_COOKIE = $existingCookies;
         $_SERVER = $existingServer;
         Requirements::set_backend($existingRequirementsBackend);
         // These are needed so that calling Director::test() does not muck with whoever is calling it.
         // Really, it's some inappropriate coupling and should be resolved by making less use of statics
         Versioned::set_reading_mode($oldReadingMode);
         Injector::unnest();
         // Restore old CookieJar, etc
         Config::unnest();
     };
     if (strpos($url, '#') !== false) {
         $url = substr($url, 0, strpos($url, '#'));
     }
     // Handle absolute URLs
     if (parse_url($url, PHP_URL_HOST)) {
         $bits = parse_url($url);
         // If a port is mentioned in the absolute URL, be sure to add that into the HTTP host
         if (isset($bits['port'])) {
             $_SERVER['HTTP_HOST'] = $bits['host'] . ':' . $bits['port'];
         } else {
             $_SERVER['HTTP_HOST'] = $bits['host'];
         }
     }
     // Ensure URL is properly made relative.
     // Example: url passed is "/ss31/my-page" (prefixed with BASE_URL), this should be changed to "my-page"
     $url = self::makeRelative($url);
     $urlWithQuerystring = $url;
     if (strpos($url, '?') !== false) {
         list($url, $getVarsEncoded) = explode('?', $url, 2);
         parse_str($getVarsEncoded, $getVars);
     }
     // Replace the super globals with appropriate test values
     $_REQUEST = ArrayLib::array_merge_recursive((array) $getVars, (array) $postVars);
     $_GET = (array) $getVars;
     $_POST = (array) $postVars;
     $_SESSION = $session ? $session->inst_getAll() : array();
     $_COOKIE = $cookieJar->getAll(false);
     Injector::inst()->registerService($cookieJar, 'Cookie_Backend');
     $_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring;
     $request = new SS_HTTPRequest($httpMethod, $url, $getVars, $postVars, $body);
     if ($headers) {
         foreach ($headers as $k => $v) {
             $request->addHeader($k, $v);
         }
     }
     // Pre-request filtering
     // @see issue #2517
     $model = DataModel::inst();
     $output = Injector::inst()->get('RequestProcessor')->preRequest($request, $session, $model);
     if ($output === false) {
         $onCleanup();
         throw new SS_HTTPResponse_Exception(_t('Director.INVALID_REQUEST', 'Invalid request'), 400);
     }
     // TODO: Pass in the DataModel
     $result = Director::handleRequest($request, $session, $model);
     // Ensure that the result is an SS_HTTPResponse object
     if (is_string($result)) {
         if (substr($result, 0, 9) == 'redirect:') {
             $response = new SS_HTTPResponse();
             $response->redirect(substr($result, 9));
             $result = $response;
         } else {
             $result = new SS_HTTPResponse($result);
         }
     }
     $output = Injector::inst()->get('RequestProcessor')->postRequest($request, $result, $model);
     if ($output === false) {
         $onCleanup();
         throw new SS_HTTPResponse_Exception("Invalid response");
     }
     // Return valid response
     $onCleanup();
     return $result;
 }
 /**
  * Test nesting of injector
  */
 public function testNest()
 {
     // Outer nest to avoid interference with other
     Injector::nest();
     $this->nestingLevel++;
     // Test services
     $config = array('NewRequirementsBackend');
     Injector::inst()->load($config);
     $si = Injector::inst()->get('TestStaticInjections');
     $this->assertInstanceOf('TestStaticInjections', $si);
     $this->assertInstanceOf('NewRequirementsBackend', $si->backend);
     $this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
     $this->assertInstanceOf('MyChildClass', Injector::inst()->get('MyChildClass'));
     // Test that nested injector values can be overridden
     Injector::nest();
     $this->nestingLevel++;
     Injector::inst()->unregisterAllObjects();
     $newsi = Injector::inst()->get('TestStaticInjections');
     $newsi->backend = new OriginalRequirementsBackend();
     Injector::inst()->registerService($newsi, 'TestStaticInjections');
     Injector::inst()->registerService(new MyChildClass(), 'MyParentClass');
     // Check that these overridden values are retrievable
     $si = Injector::inst()->get('TestStaticInjections');
     $this->assertInstanceOf('TestStaticInjections', $si);
     $this->assertInstanceOf('OriginalRequirementsBackend', $si->backend);
     $this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
     $this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyChildClass'));
     // Test that unnesting restores expected behaviour
     Injector::unnest();
     $this->nestingLevel--;
     $si = Injector::inst()->get('TestStaticInjections');
     $this->assertInstanceOf('TestStaticInjections', $si);
     $this->assertInstanceOf('NewRequirementsBackend', $si->backend);
     $this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
     $this->assertInstanceOf('MyChildClass', Injector::inst()->get('MyChildClass'));
     // Test reset of cache
     Injector::inst()->unregisterAllObjects();
     $si = Injector::inst()->get('TestStaticInjections');
     $this->assertInstanceOf('TestStaticInjections', $si);
     $this->assertInstanceOf('NewRequirementsBackend', $si->backend);
     $this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
     $this->assertInstanceOf('MyChildClass', Injector::inst()->get('MyChildClass'));
     // Return to nestingLevel 0
     Injector::unnest();
     $this->nestingLevel--;
 }
 /**
  * Called once per test case ({@link SapphireTest} subclass).
  * This is different to {@link setUp()}, which gets called once
  * per method. Useful to initialize expensive operations which
  * don't change state for any called method inside the test,
  * e.g. dynamically adding an extension. See {@link tearDownOnce()}
  * for tearing down the state again.
  */
 public function setUpOnce()
 {
     //nest config and injector for each suite so they are effectively sandboxed
     Config::nest();
     Injector::nest();
     $isAltered = false;
     if (!Director::isDev()) {
         user_error('Tests can only run in "dev" mode', E_USER_ERROR);
     }
     // Remove any illegal extensions that are present
     foreach ($this->illegalExtensions as $class => $extensions) {
         foreach ($extensions as $extension) {
             if ($class::has_extension($extension)) {
                 if (!isset($this->extensionsToReapply[$class])) {
                     $this->extensionsToReapply[$class] = array();
                 }
                 $this->extensionsToReapply[$class][] = $extension;
                 $class::remove_extension($extension);
                 $isAltered = true;
             }
         }
     }
     // Add any required extensions that aren't present
     foreach ($this->requiredExtensions as $class => $extensions) {
         $this->extensionsToRemove[$class] = array();
         foreach ($extensions as $extension) {
             if (!$class::has_extension($extension)) {
                 if (!isset($this->extensionsToRemove[$class])) {
                     $this->extensionsToReapply[$class] = array();
                 }
                 $this->extensionsToRemove[$class][] = $extension;
                 $class::add_extension($extension);
                 $isAltered = true;
             }
         }
     }
     // If we have made changes to the extensions present, then migrate the database schema.
     if ($isAltered || $this->extensionsToReapply || $this->extensionsToRemove || $this->extraDataObjects) {
         if (!self::using_temp_db()) {
             self::create_temp_db();
         }
         $this->resetDBSchema(true);
     }
     // clear singletons, they're caching old extension info
     // which is used in DatabaseAdmin->doBuild()
     Injector::inst()->unregisterAllObjects();
     // Set default timezone consistently to avoid NZ-specific dependencies
     date_default_timezone_set('UTC');
 }
 public function setUp()
 {
     parent::setUp();
     Injector::nest();
 }
 public function setUpOnce()
 {
     Injector::nest();
     Injector::inst()->registerService(new TestFetcher(), 'Fetcher');
     parent::setUpOnce();
 }
 public function setUp()
 {
     //nest config and injector for each test so they are effectively sandboxed per test
     Config::nest();
     Injector::nest();
     // 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::config()->date_format = null;
     i18n::config()->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);
     Config::inst()->update('Cookie', '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(Injector::inst()->create('Session', array()));
     }
     Security::$database_is_ready = null;
     // Add controller-name auto-routing
     Config::inst()->update('Director', 'rules', array('$Controller//$Action/$ID/$OtherID' => '*'));
     $fixtureFile = static::get_fixture_file();
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Injector::inst()->registerService($this->mailer, 'Mailer');
     Config::inst()->remove('Email', 'send_all_emails_to');
     // 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::get_conn()->getSelectedDatabase(), 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 = Injector::inst()->create('YamlFixture', $fixtureFilePath);
                 $fixture->writeInto($this->getFixtureFactory());
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
     // turn off template debugging
     Config::inst()->update('SSViewer', 'source_file_comments', false);
     // Clear requirements
     Requirements::clear();
 }
Esempio n. 13
0
 public function setUp()
 {
     parent::setUp();
     Injector::nest();
     Injector::inst()->registerService(new CookieJar($_COOKIE), 'Cookie_Backend');
 }