Skip to content
Snippets Groups Projects
Unverified Commit 6d3fbe9a authored by Alex Pott's avatar Alex Pott
Browse files

Issue #3002121 by Lendude, jibran, borisson_: Session: Convert system functional tests to phpunit

parent d29f0464
No related branches found
No related tags found
2 merge requests!7452Issue #1797438. HTML5 validation is preventing form submit and not fully...,!789Issue #3210310: Adjust Database API to remove deprecated Drupal 9 code in Drupal 10
<?php <?php
namespace Drupal\system\Tests\Session; namespace Drupal\Tests\system\Functional\Session;
use Drupal\Core\Url; use Drupal\Core\Url;
use Drupal\basic_auth\Tests\BasicAuthTestTrait; use Drupal\Tests\basic_auth\Traits\BasicAuthTestTrait;
use Drupal\simpletest\WebTestBase; use Drupal\Tests\BrowserTestBase;
/** /**
* Tests if sessions are correctly handled when a user authenticates. * Tests if sessions are correctly handled when a user authenticates.
* *
* @group Session * @group Session
*/ */
class SessionAuthenticationTest extends WebTestBase { class SessionAuthenticationTest extends BrowserTestBase {
use BasicAuthTestTrait; use BasicAuthTestTrait;
...@@ -52,20 +52,22 @@ public function testSessionFromBasicAuthenticationDoesNotLeak() { ...@@ -52,20 +52,22 @@ public function testSessionFromBasicAuthenticationDoesNotLeak() {
// Test that the route is not accessible as an anonymous user. // Test that the route is not accessible as an anonymous user.
$this->drupalGet($protected_url); $this->drupalGet($protected_url);
$session = $this->getSession();
$this->assertResponse(401, 'An anonymous user cannot access a route protected with basic authentication.'); $this->assertResponse(401, 'An anonymous user cannot access a route protected with basic authentication.');
// We should be able to access the route with basic authentication. // We should be able to access the route with basic authentication.
$this->basicAuthGet($protected_url, $this->user->getAccountName(), $this->user->pass_raw); $this->basicAuthGet($protected_url, $this->user->getAccountName(), $this->user->passRaw);
$this->assertResponse(200, 'A route protected with basic authentication can be accessed by an authenticated user.'); $this->assertResponse(200, 'A route protected with basic authentication can be accessed by an authenticated user.');
// Check that the correct user is logged in. // Check that the correct user is logged in.
$this->assertEqual($this->user->id(), json_decode($this->getRawContent())->user, 'The correct user is authenticated on a route with basic authentication.'); $this->assertEqual($this->user->id(), json_decode($session->getPage()->getContent())->user, 'The correct user is authenticated on a route with basic authentication.');
$session->restart();
// If we now try to access a page without basic authentication then we // If we now try to access a page without basic authentication then we
// should no longer be logged in. // should no longer be logged in.
$this->drupalGet($unprotected_url); $this->drupalGet($unprotected_url);
$this->assertResponse(200, 'An unprotected route can be accessed without basic authentication.'); $this->assertResponse(200, 'An unprotected route can be accessed without basic authentication.');
$this->assertFalse(json_decode($this->getRawContent())->user, 'The user is no longer authenticated after visiting a page without basic authentication.'); $this->assertFalse(json_decode($session->getPage()->getContent())->user, 'The user is no longer authenticated after visiting a page without basic authentication.');
// If we access the protected page again without basic authentication we // If we access the protected page again without basic authentication we
// should get 401 Unauthorized. // should get 401 Unauthorized.
...@@ -113,20 +115,24 @@ public function testBasicAuthNoSession() { ...@@ -113,20 +115,24 @@ public function testBasicAuthNoSession() {
$no_cookie_url = Url::fromRoute('session_test.get_session_basic_auth'); $no_cookie_url = Url::fromRoute('session_test.get_session_basic_auth');
// A route that is authorized with standard cookie authentication. // A route that is authorized with standard cookie authentication.
$cookie_url = '<front>'; $cookie_url = 'user/login';
// If we authenticate with a third party authentication system then no // If we authenticate with a third party authentication system then no
// session cookie should be set, the third party system is responsible for // session cookie should be set, the third party system is responsible for
// sustaining the session. // sustaining the session.
$this->basicAuthGet($no_cookie_url, $this->user->getAccountName(), $this->user->pass_raw); $this->basicAuthGet($no_cookie_url, $this->user->getAccountName(), $this->user->passRaw);
$this->assertResponse(200, 'The user is successfully authenticated using basic authentication.'); $this->assertResponse(200, 'The user is successfully authenticated using basic authentication.');
$this->assertFalse($this->drupalGetHeader('set-cookie', TRUE), 'No cookie is set on a route protected with basic authentication.'); $this->assertEmpty($this->getSessionCookies());
// Mink stores some information in the session that breaks the next check if
// not reset.
$this->getSession()->restart();
// On the other hand, authenticating using Cookie sets a cookie. // On the other hand, authenticating using Cookie sets a cookie.
$edit = ['name' => $this->user->getAccountName(), 'pass' => $this->user->pass_raw]; $this->drupalGet($cookie_url);
$this->assertEmpty($this->getSessionCookies());
$edit = ['name' => $this->user->getAccountName(), 'pass' => $this->user->passRaw];
$this->drupalPostForm($cookie_url, $edit, t('Log in')); $this->drupalPostForm($cookie_url, $edit, t('Log in'));
$this->assertResponse(200, 'The user is successfully authenticated using cookie authentication.'); $this->assertNotEmpty($this->getSessionCookies());
$this->assertTrue($this->drupalGetHeader('set-cookie', TRUE), 'A cookie is set on a route protected with cookie authentication.');
} }
} }
<?php <?php
namespace Drupal\system\Tests\Session; namespace Drupal\Tests\system\Functional\Session;
use Drupal\simpletest\WebTestBase; use Drupal\Tests\BrowserTestBase;
/** /**
* Drupal session handling tests. * Drupal session handling tests.
* *
* @group Session * @group Session
*/ */
class SessionTest extends WebTestBase { class SessionTest extends BrowserTestBase {
/** /**
* Modules to enable. * Modules to enable.
...@@ -36,12 +36,15 @@ public function testSessionSaveRegenerate() { ...@@ -36,12 +36,15 @@ public function testSessionSaveRegenerate() {
$user = $this->drupalCreateUser(); $user = $this->drupalCreateUser();
// Enable sessions. // Enable sessions.
$this->sessionReset($user->id()); $this->sessionReset();
// Make sure the session cookie is set as HttpOnly. // Make sure the session cookie is set as HttpOnly. We can only test this in
$this->drupalLogin($user); // the header, with the test setup
// \GuzzleHttp\Cookie\SetCookie::getHttpOnly() always returns FALSE.
// Start a new session by setting a message.
$this->drupalGet('session-test/set-message');
$this->assertSessionCookie(TRUE);
$this->assertTrue(preg_match('/HttpOnly/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as HttpOnly.'); $this->assertTrue(preg_match('/HttpOnly/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as HttpOnly.');
$this->drupalLogout();
// Verify that the session is regenerated if a module calls exit // Verify that the session is regenerated if a module calls exit
// in hook_user_login(). // in hook_user_login().
...@@ -49,7 +52,7 @@ public function testSessionSaveRegenerate() { ...@@ -49,7 +52,7 @@ public function testSessionSaveRegenerate() {
$user->save(); $user->save();
$this->drupalGet('session-test/id'); $this->drupalGet('session-test/id');
$matches = []; $matches = [];
preg_match('/\s*session_id:(.*)\n/', $this->getRawContent(), $matches); preg_match('/\s*session_id:(.*)\n/', $this->getSession()->getPage()->getContent(), $matches);
$this->assertTrue(!empty($matches[1]), 'Found session ID before logging in.'); $this->assertTrue(!empty($matches[1]), 'Found session ID before logging in.');
$original_session = $matches[1]; $original_session = $matches[1];
...@@ -57,7 +60,7 @@ public function testSessionSaveRegenerate() { ...@@ -57,7 +60,7 @@ public function testSessionSaveRegenerate() {
// session_test_user_login() which breaks a normal assertion. // session_test_user_login() which breaks a normal assertion.
$edit = [ $edit = [
'name' => $user->getAccountName(), 'name' => $user->getAccountName(),
'pass' => $user->pass_raw, 'pass' => $user->passRaw,
]; ];
$this->drupalPostForm('user/login', $edit, t('Log in')); $this->drupalPostForm('user/login', $edit, t('Log in'));
$this->drupalGet('user'); $this->drupalGet('user');
...@@ -66,7 +69,7 @@ public function testSessionSaveRegenerate() { ...@@ -66,7 +69,7 @@ public function testSessionSaveRegenerate() {
$this->drupalGet('session-test/id'); $this->drupalGet('session-test/id');
$matches = []; $matches = [];
preg_match('/\s*session_id:(.*)\n/', $this->getRawContent(), $matches); preg_match('/\s*session_id:(.*)\n/', $this->getSession()->getPage()->getContent(), $matches);
$this->assertTrue(!empty($matches[1]), 'Found session ID after logging in.'); $this->assertTrue(!empty($matches[1]), 'Found session ID after logging in.');
$this->assertTrue($matches[1] != $original_session, 'Session ID changed after login.'); $this->assertTrue($matches[1] != $original_session, 'Session ID changed after login.');
} }
...@@ -91,14 +94,22 @@ public function testDataPersistence() { ...@@ -91,14 +94,22 @@ public function testDataPersistence() {
// properly, val_1 will still be set. // properly, val_1 will still be set.
$value_2 = $this->randomMachineName(); $value_2 = $this->randomMachineName();
$this->drupalGet('session-test/no-set/' . $value_2); $this->drupalGet('session-test/no-set/' . $value_2);
$session = $this->getSession();
$this->assertText($value_2, 'The session value was correctly passed to session-test/no-set.', 'Session'); $this->assertText($value_2, 'The session value was correctly passed to session-test/no-set.', 'Session');
$this->drupalGet('session-test/get'); $this->drupalGet('session-test/get');
$this->assertText($value_1, 'Session data is not saved for drupal_save_session(FALSE).', 'Session'); $this->assertText($value_1, 'Session data is not saved for drupal_save_session(FALSE).', 'Session');
// Switch browser cookie to anonymous user, then back to user 1. // Switch browser cookie to anonymous user, then back to user 1.
$this->sessionReset(); $session_cookie_name = $this->getSessionName();
$this->sessionReset($user->id()); $session_cookie_value = $session->getCookie($session_cookie_name);
$session->restart();
$this->initFrontPage();
// Session restart always resets all the cookies by design, so we need to
// add the old session cookie again.
$session->setCookie($session_cookie_name, $session_cookie_value);
$this->drupalGet('session-test/get');
$this->assertText($value_1, 'Session data persists through browser close.', 'Session'); $this->assertText($value_1, 'Session data persists through browser close.', 'Session');
$this->mink->setDefaultSessionName('default');
// Logout the user and make sure the stored value no longer persists. // Logout the user and make sure the stored value no longer persists.
$this->drupalLogout(); $this->drupalLogout();
...@@ -242,8 +253,6 @@ public function testSessionWrite() { ...@@ -242,8 +253,6 @@ public function testSessionWrite() {
$this->assertEqual($times4->timestamp, $times3->timestamp, 'Sessions table was not updated.'); $this->assertEqual($times4->timestamp, $times3->timestamp, 'Sessions table was not updated.');
// Force updating of users and sessions table once per second. // Force updating of users and sessions table once per second.
$this->settingsSet('session_write_interval', 0);
// Write that value also into the test settings.php file.
$settings['settings']['session_write_interval'] = (object) [ $settings['settings']['session_write_interval'] = (object) [
'value' => 0, 'value' => 0,
'required' => TRUE, 'required' => TRUE,
...@@ -270,8 +279,7 @@ public function testEmptySessionID() { ...@@ -270,8 +279,7 @@ public function testEmptySessionID() {
// Send a blank sid in the session cookie, and the session should no longer // Send a blank sid in the session cookie, and the session should no longer
// be valid. Closing the curl handler will stop the previous session ID // be valid. Closing the curl handler will stop the previous session ID
// from persisting. // from persisting.
$this->curlClose(); $this->mink->resetSessions();
$this->additionalCurlOptions[CURLOPT_COOKIE] = rawurlencode($this->getSessionName()) . '=;';
$this->drupalGet('session-test/id-from-cookie'); $this->drupalGet('session-test/id-from-cookie');
$this->assertRaw("session_id:\n", 'Session ID is blank as sent from cookie header.'); $this->assertRaw("session_id:\n", 'Session ID is blank as sent from cookie header.');
// Assert that we have an anonymous session now. // Assert that we have an anonymous session now.
...@@ -281,19 +289,13 @@ public function testEmptySessionID() { ...@@ -281,19 +289,13 @@ public function testEmptySessionID() {
/** /**
* Reset the cookie file so that it refers to the specified user. * Reset the cookie file so that it refers to the specified user.
*
* @param $uid
* User id to set as the active session.
*/ */
public function sessionReset($uid = 0) { public function sessionReset() {
// Close the internal browser. // Close the internal browser.
$this->curlClose(); $this->mink->resetSessions();
$this->loggedInUser = FALSE; $this->loggedInUser = FALSE;
// Change cookie file for user. // Change cookie file for user.
$this->cookieFile = \Drupal::service('stream_wrapper_manager')->getViaScheme('temporary')->getDirectoryPath() . '/cookie.' . $uid . '.txt';
$this->additionalCurlOptions[CURLOPT_COOKIEFILE] = $this->cookieFile;
$this->additionalCurlOptions[CURLOPT_COOKIESESSION] = TRUE;
$this->drupalGet('session-test/get'); $this->drupalGet('session-test/get');
$this->assertResponse(200, 'Session test module is correctly enabled.', 'Session'); $this->assertResponse(200, 'Session test module is correctly enabled.', 'Session');
} }
...@@ -303,10 +305,10 @@ public function sessionReset($uid = 0) { ...@@ -303,10 +305,10 @@ public function sessionReset($uid = 0) {
*/ */
public function assertSessionCookie($sent) { public function assertSessionCookie($sent) {
if ($sent) { if ($sent) {
$this->assertNotNull($this->sessionId, 'Session cookie was sent.'); $this->assertNotEmpty($this->getSessionCookies()->count(), 'Session cookie was sent.');
} }
else { else {
$this->assertNull($this->sessionId, 'Session cookie was not sent.'); $this->assertEmpty($this->getSessionCookies()->count(), 'Session cookie was not sent.');
} }
} }
......
<?php <?php
namespace Drupal\system\Tests\Session; namespace Drupal\Tests\system\Functional\Session;
use Drupal\simpletest\WebTestBase; use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Tests\BrowserTestBase;
/** /**
* Tests the stacked session handler functionality. * Tests the stacked session handler functionality.
* *
* @group Session * @group Session
*/ */
class StackSessionHandlerIntegrationTest extends WebTestBase { class StackSessionHandlerIntegrationTest extends BrowserTestBase {
/** /**
* Modules to enable. * {@inheritdoc}
*
* @var array
*/ */
public static $modules = ['session_test']; protected static $modules = ['session_test'];
/** /**
* Tests a request. * Tests a request.
*/ */
public function testRequest() { public function testRequest() {
$actual_trace = $this->drupalGetAjax('session-test/trace-handler'); $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'drupal_ajax';
$headers[] = 'X-Requested-With: XMLHttpRequest';
$actual_trace = json_decode($this->drupalGet('session-test/trace-handler', $options, $headers));
$sessionId = $this->getSessionCookies()->getCookieByName($this->getSessionName())->getValue();
$expect_trace = [ $expect_trace = [
['BEGIN', 'test_argument', 'open'], ['BEGIN', 'test_argument', 'open'],
['BEGIN', NULL, 'open'], ['BEGIN', NULL, 'open'],
['END', NULL, 'open'], ['END', NULL, 'open'],
['END', 'test_argument', 'open'], ['END', 'test_argument', 'open'],
['BEGIN', 'test_argument', 'read', $this->sessionId], ['BEGIN', 'test_argument', 'read', $sessionId],
['BEGIN', NULL, 'read', $this->sessionId], ['BEGIN', NULL, 'read', $sessionId],
['END', NULL, 'read', $this->sessionId], ['END', NULL, 'read', $sessionId],
['END', 'test_argument', 'read', $this->sessionId], ['END', 'test_argument', 'read', $sessionId],
['BEGIN', 'test_argument', 'write', $this->sessionId], ['BEGIN', 'test_argument', 'write', $sessionId],
['BEGIN', NULL, 'write', $this->sessionId], ['BEGIN', NULL, 'write', $sessionId],
['END', NULL, 'write', $this->sessionId], ['END', NULL, 'write', $sessionId],
['END', 'test_argument', 'write', $this->sessionId], ['END', 'test_argument', 'write', $sessionId],
['BEGIN', 'test_argument', 'close'], ['BEGIN', 'test_argument', 'close'],
['BEGIN', NULL, 'close'], ['BEGIN', NULL, 'close'],
['END', NULL, 'close'], ['END', NULL, 'close'],
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment