ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,40 @@
<?php
/**
* Integration test for Magento\Framework\Session\Config\Validator\CookieDomainValidator
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Session\Config\Validator;
class CookieDomainValidatorTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Framework\Session\Config\Validator\CookieDomainValidator */
private $model;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $objectManager->create(\Magento\Framework\Session\Config\Validator\CookieDomainValidator::class);
}
public function testEmptyString()
{
$this->assertTrue($this->model->isValid(''));
}
public function testInvalidHostname()
{
$this->assertFalse($this->model->isValid('http://'));
}
public function testNotString()
{
$this->assertFalse($this->model->isValid(1));
}
public function testNonemptyValid()
{
$this->assertTrue($this->model->isValid('domain.com'));
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Integration test for Magento\Framework\Session\Config\Validator\CookieLifetimeValidator
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Session\Config\Validator;
class CookieLifetimeValidatorTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Framework\Session\Config\Validator\CookieLifetimeValidator */
private $model;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $objectManager->create(
\Magento\Framework\Session\Config\Validator\CookieLifetimeValidator::class
);
}
public function testNonNumeric()
{
$this->assertFalse($this->model->isValid('non-numeric value'));
}
public function testNegative()
{
$this->assertFalse($this->model->isValid(-1));
}
public function testPositive()
{
$this->assertTrue($this->model->isValid(1));
}
public function testZero()
{
$this->assertTrue($this->model->isValid(0));
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Integration test for Magento\Framework\Session\Config\Validator\CookiePathValidator
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Session\Config\Validator;
class CookiePathValidatorTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Framework\Session\Config\Validator\CookiePathValidator */
private $model;
protected function setUp(): void
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $objectManager->create(\Magento\Framework\Session\Config\Validator\CookiePathValidator::class);
}
public function testNoLeadingSlash()
{
$path = 'path';
$this->assertFalse($this->model->isValid($path));
}
public function testInvalidPath()
{
$path = '/path?query=query';
$this->assertFalse($this->model->isValid($path));
}
public function testValidPath()
{
$path = '/';
$this->assertTrue($this->model->isValid($path));
}
}
@@ -0,0 +1,394 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
// @codingStandardsIgnoreStart
namespace {
$mockPHPFunctions = false;
}
namespace Magento\Framework\Session {
use Magento\Framework\App\Filesystem\DirectoryList;
/**
* Mock ini_get global function
*
* @return string
*/
function ini_get($varName)
{
global $mockPHPFunctions;
if ($mockPHPFunctions == 1) {
switch ($varName) {
case 'session.save_path':
return 'preset_save_path';
case 'session.save_handler':
return 'php';
default:
return '';
}
} elseif ($mockPHPFunctions == 2) {
return null;
}
//phpcs:ignore PHPCompatibility
return call_user_func_array('\ini_get', func_get_args());
}
// @codingStandardsIgnoreEnd
/**
* @magentoAppIsolation enabled
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/** @var string */
private $_cacheLimiter = 'private_no_expire';
/** @var \Magento\TestFramework\ObjectManager */
private $_objectManager;
/** @var string Default value for session.save_path setting */
private $defaultSavePath;
/** @var \Magento\Framework\App\DeploymentConfig | \PHPUnit\Framework\MockObject\MockObject */
private $deploymentConfigMock;
protected function setUp(): void
{
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class);
$this->deploymentConfigMock
->method('get')
->willReturnCallback(function ($configPath) {
switch ($configPath) {
case Config::PARAM_SESSION_SAVE_METHOD:
return 'files';
case Config::PARAM_SESSION_CACHE_LIMITER:
return $this->_cacheLimiter;
default:
return null;
}
});
$this->defaultSavePath = $this->_objectManager
->get(\Magento\Framework\Filesystem\DirectoryList::class)
->getPath(DirectoryList::SESSION);
}
/**
* @magentoAppIsolation enabled
*/
public function testDefaultConfiguration()
{
$model = $this->getModel();
/** @var \Magento\Framework\Filesystem $filesystem */
$filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\Filesystem::class
);
$path = ini_get('session.save_path') ?:
$filesystem->getDirectoryRead(DirectoryList::SESSION)->getAbsolutePath();
$this->assertEquals(
$path,
$model->getSavePath()
);
$this->assertEquals(
\Magento\Framework\Session\Config::COOKIE_LIFETIME_DEFAULT,
$model->getCookieLifetime()
);
$this->assertEquals($this->_cacheLimiter, $model->getCacheLimiter());
$this->assertEquals('/', $model->getCookiePath());
$this->assertEquals('localhost', $model->getCookieDomain());
$this->assertFalse($model->getCookieSecure());
$this->assertTrue($model->getCookieHttpOnly());
$this->assertEquals($model->getSavePath(), $model->getOption('save_path'));
}
public function testSetOptionsInvalidValue()
{
$model = $this->getModel();
$preValue = $model->getOptions();
$model->setOptions('');
$this->assertEquals($preValue, $model->getOptions());
}
/**
* @dataProvider optionsProvider
*/
public function testSetOptions($option, $getter, $value)
{
$model = $this->getModel();
$options = [$option => $value];
$model->setOptions($options);
$this->assertSame($value, $model->{$getter}());
}
public function optionsProvider()
{
return [
['save_path', 'getSavePath', __DIR__],
['name', 'getName', 'FOOBAR'],
['gc_probability', 'getGcProbability', 42],
['gc_divisor', 'getGcDivisor', 3],
['gc_maxlifetime', 'getGcMaxlifetime', 180],
['serialize_handler', 'getSerializeHandler', 'php_binary'],
['cookie_lifetime', 'getCookieLifetime', 180],
['cookie_path', 'getCookiePath', '/foo/bar'],
['cookie_domain', 'getCookieDomain', 'framework.zend.com'],
['cookie_secure', 'getCookieSecure', true],
['cookie_httponly', 'getCookieHttpOnly', true],
['use_cookies', 'getUseCookies', false],
['use_only_cookies', 'getUseOnlyCookies', true],
['referer_check', 'getRefererCheck', 'foobar'],
['entropy_file', 'getEntropyFile', __FILE__],
['entropy_length', 'getEntropyLength', 42],
['cache_limiter', 'getCacheLimiter', 'private'],
['cache_expire', 'getCacheExpire', 42],
['use_trans_sid', 'getUseTransSid', true],
['hash_function', 'getHashFunction', 'md5'],
['hash_bits_per_character', 'getHashBitsPerCharacter', 5],
['url_rewriter_tags', 'getUrlRewriterTags', 'a=href']
];
}
public function testNameIsMutable()
{
$model = $this->getModel();
$model->setName('FOOBAR');
$this->assertEquals('FOOBAR', $model->getName());
}
public function testCookieLifetimeIsMutable()
{
$model = $this->getModel();
$model->setCookieLifetime(20);
$this->assertEquals(20, $model->getCookieLifetime());
}
public function testCookieLifetimeCanBeZero()
{
$model = $this->getModel();
$model->setCookieLifetime(0);
$this->assertEquals(0, $model->getCookieLifetime());
}
public function testSettingInvalidCookieLifetime()
{
$model = $this->getModel();
$preVal = $model->getCookieLifetime();
$model->setCookieLifetime('foobar_bogus');
$this->assertEquals($preVal, $model->getCookieLifetime());
}
public function testSettingInvalidCookieLifetime2()
{
$model = $this->getModel();
$preVal = $model->getCookieLifetime();
$model->setCookieLifetime(-1);
$this->assertEquals($preVal, $model->getCookieLifetime());
}
public function testWrongMethodCall()
{
$model = $this->getModel();
$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage(
'Method "methodThatNotExist" does not exist in Magento\Framework\Session\Config'
);
$model->methodThatNotExist();
}
public function testCookieSecureDefaultsToIniSettings()
{
$model = $this->getModel();
$this->assertSame((bool)ini_get('session.cookie_secure'), $model->getCookieSecure());
}
public function testSetCookieSecureInOptions()
{
$model = $this->getModel();
$model->setCookieSecure(true);
$this->assertTrue($model->getCookieSecure());
}
public function testCookieDomainIsMutable()
{
$model = $this->getModel();
$model->setCookieDomain('example.com');
$this->assertEquals('example.com', $model->getCookieDomain());
}
public function testCookieDomainCanBeEmpty()
{
$model = $this->getModel();
$model->setCookieDomain('');
$this->assertEquals('', $model->getCookieDomain());
}
public function testSettingInvalidCookieDomain()
{
$model = $this->getModel();
$preVal = $model->getCookieDomain();
$model->setCookieDomain(24);
$this->assertEquals($preVal, $model->getCookieDomain());
}
public function testSettingInvalidCookieDomain2()
{
$model = $this->getModel();
$preVal = $model->getCookieDomain();
$model->setCookieDomain('D:\\WINDOWS\\System32\\drivers\\etc\\hosts');
$this->assertEquals($preVal, $model->getCookieDomain());
}
public function testSetCookieHttpOnlyInOptions()
{
$model = $this->getModel();
$model->setCookieHttpOnly(true);
$this->assertTrue($model->getCookieHttpOnly());
}
public function testUseCookiesDefaultsToIniSettings()
{
$model = $this->getModel();
$this->assertSame((bool)ini_get('session.use_cookies'), $model->getUseCookies());
}
public function testSetUseCookiesInOptions()
{
$model = $this->getModel();
$model->setUseCookies(true);
$this->assertTrue($model->getUseCookies());
}
public function testUseOnlyCookiesDefaultsToIniSettings()
{
$model = $this->getModel();
$this->assertSame((bool)ini_get('session.use_only_cookies'), $model->getUseOnlyCookies());
}
public function testSetUseOnlyCookiesInOptions()
{
$model = $this->getModel();
$model->setOption('use_only_cookies', true);
$this->assertTrue((bool)$model->getOption('use_only_cookies'));
}
public function testRefererCheckDefaultsToIniSettings()
{
$model = $this->getModel();
$this->assertSame(ini_get('session.referer_check'), $model->getRefererCheck());
}
public function testRefererCheckIsMutable()
{
$model = $this->getModel();
$model->setOption('referer_check', 'FOOBAR');
$this->assertEquals('FOOBAR', $model->getOption('referer_check'));
}
public function testRefererCheckMayBeEmpty()
{
$model = $this->getModel();
$model->setOption('referer_check', '');
$this->assertEquals('', $model->getOption('referer_check'));
}
public function testSetSavePath()
{
$model = $this->getModel();
$model->setSavePath('some_save_path');
$this->assertEquals($model->getOption('save_path'), 'some_save_path');
}
/**
* @param $mockPHPFunctionNum
* @param $givenSavePath
* @param $expectedSavePath
* @param $givenSaveHandler
* @param $expectedSaveHandler
* @dataProvider constructorDataProvider
*/
public function testConstructor(
$mockPHPFunctionNum,
$givenSavePath,
$expectedSavePath,
$givenSaveHandler,
$expectedSaveHandler
) {
global $mockPHPFunctions;
$mockPHPFunctions = $mockPHPFunctionNum;
$sessionSaveHandler = ini_get('session.save_handler');
if ($expectedSavePath === 'default') {
$expectedSavePath = $this->defaultSavePath . '/';
}
if ($expectedSaveHandler === 'php') {
$expectedSaveHandler = $sessionSaveHandler;
}
$deploymentConfigMock = $this->createMock(\Magento\Framework\App\DeploymentConfig::class);
$deploymentConfigMock
->method('get')
->willReturnCallback(function ($configPath) use ($givenSavePath, $givenSaveHandler) {
switch ($configPath) {
case Config::PARAM_SESSION_SAVE_METHOD:
return $givenSaveHandler;
case Config::PARAM_SESSION_CACHE_LIMITER:
return $this->_cacheLimiter;
case Config::PARAM_SESSION_SAVE_PATH:
return $givenSavePath;
default:
return null;
}
});
$model = $this->_objectManager->create(
\Magento\Framework\Session\Config::class,
['deploymentConfig' => $deploymentConfigMock]
);
$this->assertEquals($expectedSavePath, $model->getOption('save_path'));
$this->assertEquals($expectedSaveHandler, $model->getOption('session.save_handler'));
global $mockPHPFunctions;
$mockPHPFunctions = false;
}
public function constructorDataProvider()
{
// preset value (null = not set), input value (null = not set), expected value
$savePathGiven = 'explicit_save_path';
$presetPath = 'preset_save_path';
return [
[2, $savePathGiven, $savePathGiven, 'db', 'db'],
[2, null, 'default', 'redis', 'redis'],
[1, $savePathGiven, $savePathGiven, null, 'php'],
[1, null, $presetPath, 'files', 'files'],
];
}
private function getModel(): \Magento\Framework\Session\Config
{
return $this->_objectManager->create(
\Magento\Framework\Session\Config::class,
['deploymentConfig' => $this->deploymentConfigMock]
);
}
/**
* Test Set SameSite Attribute
*
* @return void
*/
public function testSetCookieInvalidSameSite(): void
{
$model = $this->getModel();
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Invalid Samesite attribute.');
$model->setCookieSameSite('foobar');
}
}
}
@@ -0,0 +1,222 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Session\SaveHandler;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Encryption\EncryptorInterface;
class DbTableTest extends \PHPUnit\Framework\TestCase
{
/**
* Test session ID
*/
const SESSION_ID = 'session_id_value';
/**#@+
* Session keys
*/
const SESSION_NEW = 'session_new';
const SESSION_EXISTS = 'session_exists';
/**#@-*/
/**#@+
* Table column names
*/
const COLUMN_SESSION_ID = 'session_id';
const COLUMN_SESSION_DATA = 'session_data';
const COLUMN_SESSION_EXPIRES = 'session_expires';
/**#@-*/
/**
* Test session data
*
* @var array
*/
protected $_sourceData = [
self::SESSION_NEW => ['new key' => 'new value'],
self::SESSION_EXISTS => ['existing key' => 'existing value'],
];
/**
* Data as objects for serialization
*
* @var array
*/
protected $_sessionData;
/**
* @var \Magento\TestFramework\ObjectManager
*/
protected $_objectManager;
/**
* Model under test
*
* @var \Magento\Framework\Session\SaveHandler\DbTable
*/
protected $_model;
/**
* Write connection adapter
*
* @var \Magento\Framework\DB\Adapter\AdapterInterface
*/
protected $_connection;
/**
* Session table name
*
* @var string
*/
protected $_sessionTable;
/**
* @var EncryptorInterface
*/
private $_encryptor;
/**
* @return void
*/
protected function setUp(): void
{
$this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_model = $this->_objectManager->get(\Magento\Framework\Session\SaveHandler\DbTable::class);
/** @var $resource \Magento\Framework\App\ResourceConnection */
$resource = $this->_objectManager->get(\Magento\Framework\App\ResourceConnection::class);
$this->_connection = $resource->getConnection();
$this->_sessionTable = $resource->getTableName('session');
$this->_encryptor = $this->_objectManager->get(EncryptorInterface::class);
// session stores serialized objects with protected properties
// we need to test this case to ensure that DB adapter successfully processes "\0" symbols in serialized data
foreach ($this->_sourceData as $key => $data) {
$this->_sessionData[$key] = new \Magento\Framework\DataObject($data);
}
}
/**
* @return void
*/
public function testCheckConnection()
{
$method = new \ReflectionMethod(\Magento\Framework\Session\SaveHandler\DbTable::class, 'checkConnection');
$method->setAccessible(true);
$this->assertNull($method->invoke($this->_model));
}
/**
* @return void
*/
public function testOpenAndClose()
{
$this->assertTrue($this->_model->open('', 'test'));
$this->assertTrue($this->_model->close());
}
/**
* @return void
*/
public function testWriteReadDestroy()
{
// We have to use serialize here.
// phpcs:ignore Magento2.Security.InsecureFunction
$data = serialize($this->_sessionData[self::SESSION_NEW]);
$this->_model->write(self::SESSION_ID, $data);
$this->assertEquals($data, $this->_model->read(self::SESSION_ID));
// We have to use serialize here.
// phpcs:ignore Magento2.Security.InsecureFunction
$data = serialize($this->_sessionData[self::SESSION_EXISTS]);
$this->_model->write(self::SESSION_ID, $data);
$this->assertEquals($data, $this->_model->read(self::SESSION_ID));
$this->_model->destroy(self::SESSION_ID);
$this->assertEmpty($this->_model->read(self::SESSION_ID));
}
/**
* @return void
*/
public function testGc()
{
$this->_model->write('test', 'test');
$this->assertEquals('test', $this->_model->read('test'));
$this->_model->gc(-1);
$this->assertEmpty($this->_model->read('test'));
}
/**
* Assert that session data writes to DB in base64 encoding
*
* @return void
*/
public function testWriteEncoded()
{
// We have to use serialize here.
// phpcs:ignore Magento2.Security.InsecureFunction
$data = serialize($this->_sessionData[self::SESSION_NEW]);
$this->_model->write(self::SESSION_ID, $data);
$select = $this->_connection->select()->from(
$this->_sessionTable
)->where(
self::COLUMN_SESSION_ID . ' = :' . self::COLUMN_SESSION_ID
);
$bind = [self::COLUMN_SESSION_ID => $this->_encryptor->hash(self::SESSION_ID)];
$session = $this->_connection->fetchRow($select, $bind);
$this->assertEquals($this->_encryptor->hash(self::SESSION_ID), $session[self::COLUMN_SESSION_ID]);
$this->assertTrue(
ctype_digit((string)$session[self::COLUMN_SESSION_EXPIRES]),
'Value of session expire field must have integer type'
);
$this->assertEquals($data, base64_decode($session[self::COLUMN_SESSION_DATA]));
}
/**
* Data provider for testReadEncoded
*
* @return array
*/
public function readEncodedDataProvider()
{
// we can't use object data as a fixture because not encoded serialized object
// might cause DB adapter fatal error, so we have to use array as a fixture
// phpcs:ignore Magento2.Security.InsecureFunction
$sessionData = serialize($this->_sourceData[self::SESSION_NEW]);
return [
'session_encoded' => ['$sessionData' => base64_encode($sessionData)],
'session_not_encoded' => ['$sessionData' => $sessionData]
];
}
/**
* Assert that session data reads from DB correctly regardless of encoding
*
* @param string $sessionData
*
* @dataProvider readEncodedDataProvider
*
* @return void
*/
public function testReadEncoded($sessionData)
{
$sessionRecord = [self::COLUMN_SESSION_ID => $this->_encryptor->hash(self::SESSION_ID), self::COLUMN_SESSION_DATA => $sessionData];
$this->_connection->insertOnDuplicate($this->_sessionTable, $sessionRecord, [self::COLUMN_SESSION_DATA]);
$sessionData = $this->_model->read(self::SESSION_ID);
// We have to use unserialize here.
// phpcs:ignore Magento2.Security.InsecureFunction
$this->assertEquals($this->_sourceData[self::SESSION_NEW], unserialize($sessionData));
}
}
@@ -0,0 +1,126 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Session;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\Exception\SessionException;
use Magento\Framework\Phrase;
use Magento\Framework\Session\Config\ConfigInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
/**
* Tests \Magento\Framework\Session\SaveHandler functionality.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SaveHandlerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var DeploymentConfig|\PHPUnit\Framework\MockObject\MockObject
*/
private $deploymentConfigMock;
/**
* @var SaveHandlerFactory|\PHPUnit\Framework\MockObject\MockObject
*/
private $saveHandlerFactoryMock;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->deploymentConfigMock = $this->createMock(DeploymentConfig::class);
$this->objectManager->addSharedInstance($this->deploymentConfigMock, DeploymentConfig::class);
$this->saveHandlerFactoryMock = $this->createMock(SaveHandlerFactory::class);
$this->objectManager->addSharedInstance($this->saveHandlerFactoryMock, SaveHandlerFactory::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->objectManager->removeSharedInstance(DeploymentConfig::class);
$this->objectManager->removeSharedInstance(SaveHandlerFactory::class);
}
/**
* @return void
*/
public function testRedisSaveHandler(): void
{
$this->deploymentConfigMock->method('get')
->willReturnMap(
[
[Config::PARAM_SESSION_SAVE_METHOD, null, 'redis'],
[Config::PARAM_SESSION_SAVE_PATH, null, 'explicit_save_path'],
]
);
$redisHandlerMock = $this->getMockBuilder(SaveHandler\Redis::class)
->disableOriginalConstructor()
->getMock();
$redisHandlerMock->method('open')
->with('explicit_save_path', 'test_session_id')
->willReturn(true);
$this->saveHandlerFactoryMock->expects($this->exactly(1))
->method('create')
->with('redis')
->willReturn($redisHandlerMock);
$sessionConfig = $this->objectManager->create(ConfigInterface::class);
/** @var SaveHandler $saveHandler */
$saveHandler = $this->objectManager->create(SaveHandler::class, ['sessionConfig' => $sessionConfig]);
$result = $saveHandler->open('explicit_save_path', 'test_session_id');
$this->assertTrue($result);
}
/**
* @return void
*/
public function testRedisSaveHandlerFallbackToDefaultOnSessionException(): void
{
$this->deploymentConfigMock->method('get')
->willReturnMap(
[
[Config::PARAM_SESSION_SAVE_METHOD, null, 'redis'],
[Config::PARAM_SESSION_SAVE_PATH, null, 'explicit_save_path'],
]
);
$redisHandlerMock = $this->getMockBuilder(SaveHandler\Redis::class)
->disableOriginalConstructor()
->getMock();
$redisHandlerMock->method('open')
->with('explicit_save_path', 'test_session_id')
->willThrowException(new SessionException(new Phrase('Session Exception')));
$defaultHandlerMock = $this->getMockBuilder(SaveHandler\Native::class)
->disableOriginalConstructor()
->getMock();
$defaultHandlerMock->expects($this->once())->method('open')->with('explicit_save_path', 'test_session_id');
$this->saveHandlerFactoryMock
->method('create')
->withConsecutive(['redis'], [SaveHandlerInterface::DEFAULT_HANDLER])
->willReturnOnConsecutiveCalls($redisHandlerMock, $defaultHandlerMock);
$sessionConfig = $this->objectManager->create(ConfigInterface::class);
/** @var SaveHandler $saveHandler */
$saveHandler = $this->objectManager->create(SaveHandler::class, ['sessionConfig' => $sessionConfig]);
$saveHandler->open('explicit_save_path', 'test_session_id');
}
}
@@ -0,0 +1,362 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreStart
namespace {
$mockPHPFunctions = false;
}
namespace Magento\Framework\Session {
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\State;
// @codingStandardsIgnoreEnd
/**
* Mock session_status if in test mode, or continue normal execution otherwise
*
* @return int Session status code
*/
function session_status()
{
global $mockPHPFunctions;
if ($mockPHPFunctions) {
return PHP_SESSION_NONE;
}
return call_user_func_array('\session_status', func_get_args());
}
function headers_sent()
{
global $mockPHPFunctions;
if ($mockPHPFunctions) {
return false;
}
return call_user_func_array('\headers_sent', func_get_args());
}
/**
* Mock ini_set global function
*
* @param string $varName
* @param string $newValue
* @return bool|string
*/
function ini_set($varName, $newValue)
{
global $mockPHPFunctions;
if ($mockPHPFunctions) {
SessionManagerTest::$isIniSetInvoked[$varName] = $newValue;
return true;
}
return call_user_func_array('\ini_set', [$varName, $newValue]);
}
/**
* Mock session_set_save_handler global function
*
* @return bool
*/
function session_set_save_handler()
{
global $mockPHPFunctions;
if ($mockPHPFunctions) {
SessionManagerTest::$isSessionSetSaveHandlerInvoked = true;
return true;
}
return call_user_func_array('\session_set_save_handler', func_get_args());
}
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class SessionManagerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var string[]
*/
public static $isIniSetInvoked = [];
/**
* @var bool
*/
public static $isSessionSetSaveHandlerInvoked;
/**
* @var \Magento\Framework\Session\SessionManagerInterface
*/
private $model;
/**
* @var \Magento\Framework\Session\SidResolverInterface
*/
private $sidResolver;
/**
* @var string
*/
private $sessionName;
/**
* @var \Magento\TestFramework\ObjectManager
*/
private $objectManager;
/**
* @var \Magento\Framework\App\RequestInterface
*/
private $request;
/**
* @var State|\PHPUnit\Framework\MockObject\MockObject
*/
private $appState;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->sessionName = 'frontEndSession';
ini_set('session.use_only_cookies', '0');
ini_set('session.name', $this->sessionName);
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\Session\SidResolverInterface $sidResolver */
$this->appState = $this->getMockBuilder(State::class)
->setMethods(['getAreaCode'])
->disableOriginalConstructor()
->getMock();
/** @var \Magento\Framework\Session\SidResolver $sidResolver */
$this->sidResolver = $this->objectManager->create(
\Magento\Framework\Session\SidResolver::class,
[
'appState' => $this->appState,
]
);
$this->request = $this->objectManager->get(\Magento\Framework\App\RequestInterface::class);
}
protected function tearDown(): void
{
global $mockPHPFunctions;
$mockPHPFunctions = false;
self::$isIniSetInvoked = [];
self::$isSessionSetSaveHandlerInvoked = false;
if ($this->model !== null) {
$this->model->destroy();
$this->model = null;
}
}
public function testSessionNameFromIni()
{
$this->initializeModel();
$this->model->start();
$this->assertSame($this->sessionName, $this->model->getName());
$this->model->destroy();
}
public function testSessionUseOnlyCookies()
{
$this->initializeModel();
$expectedValue = '1';
$sessionUseOnlyCookies = ini_get('session.use_only_cookies');
$this->assertSame($expectedValue, $sessionUseOnlyCookies);
}
public function testGetData()
{
$this->initializeModel();
$this->model->setData(['test_key' => 'test_value']);
$this->assertEquals('test_value', $this->model->getData('test_key', true));
$this->assertNull($this->model->getData('test_key'));
}
public function testGetSessionId()
{
$this->initializeModel();
$this->assertEquals(session_id(), $this->model->getSessionId());
}
public function testGetName()
{
$this->initializeModel();
$this->assertEquals(session_name(), $this->model->getName());
}
public function testSetName()
{
$this->initializeModel();
$this->model->destroy();
$this->model->setName('test');
$this->model->start();
$this->assertEquals('test', $this->model->getName());
}
public function testDestroy()
{
$this->initializeModel();
$data = ['key' => 'value'];
$this->model->setData($data);
$this->assertEquals($data, $this->model->getData());
$this->model->destroy();
$this->assertEquals([], $this->model->getData());
}
public function testSetSessionId()
{
$this->initializeModel();
$this->assertNotEmpty($this->model->getSessionId());
$this->appState->expects($this->any())
->method('getAreaCode')
->willReturn(\Magento\Framework\App\Area::AREA_FRONTEND);
$this->model->setSessionId('test');
$this->assertEquals('test', $this->model->getSessionId());
/* Use not valid identifier */
$this->model->setSessionId('test_id');
$this->assertEquals('test', $this->model->getSessionId());
}
public function testGetSessionIdForHost()
{
$this->initializeModel();
$_SERVER['HTTP_HOST'] = 'localhost';
$this->model->start();
$this->assertEmpty($this->model->getSessionIdForHost('localhost'));
$this->assertNotEmpty($this->model->getSessionIdForHost('test'));
$this->model->destroy();
}
public function testIsValidForHost()
{
$this->initializeModel();
$_SERVER['HTTP_HOST'] = 'localhost';
$this->model->start();
$reflection = new \ReflectionMethod($this->model, '_addHost');
$reflection->setAccessible(true);
$reflection->invoke($this->model);
$this->assertFalse($this->model->isValidForHost('test.com'));
$this->assertTrue($this->model->isValidForHost('localhost'));
$this->model->destroy();
}
public function testStartAreaNotSet()
{
$this->expectException(\Magento\Framework\Exception\SessionException::class);
$this->expectExceptionMessage('Area code not set: Area code must be set before starting a session.');
$scope = $this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class);
$appState = new \Magento\Framework\App\State($scope);
/**
* Must be created by "new" in order to get a real Magento\Framework\App\State object that
* is not overridden in the TestFramework
*
* @var \Magento\Framework\Session\SessionManager _model
*/
$this->model = new \Magento\Framework\Session\SessionManager(
$this->objectManager->get(\Magento\Framework\App\Request\Http::class),
$this->sidResolver,
$this->objectManager->get(\Magento\Framework\Session\Config\ConfigInterface::class),
$this->objectManager->get(\Magento\Framework\Session\SaveHandlerInterface::class),
$this->objectManager->get(\Magento\Framework\Session\ValidatorInterface::class),
$this->objectManager->get(\Magento\Framework\Session\StorageInterface::class),
$this->objectManager->get(\Magento\Framework\Stdlib\CookieManagerInterface::class),
$this->objectManager->get(\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class),
$appState
);
global $mockPHPFunctions;
$mockPHPFunctions = true;
$this->model->start();
}
/**
* @param string $saveMethod
* @dataProvider dataConstructor
*
* @return void
*/
public function testConstructor(string $saveMethod): void
{
global $mockPHPFunctions;
$mockPHPFunctions = true;
$deploymentConfigMock = $this->createMock(DeploymentConfig::class);
$deploymentConfigMock->method('get')
->willReturnCallback(function ($configPath) use ($saveMethod) {
switch ($configPath) {
case Config::PARAM_SESSION_SAVE_METHOD:
return $saveMethod;
case Config::PARAM_SESSION_CACHE_LIMITER:
return 'private_no_expire';
case Config::PARAM_SESSION_SAVE_PATH:
return 'explicit_save_path';
default:
return null;
}
});
$sessionConfig = $this->objectManager->create(Config::class, ['deploymentConfig' => $deploymentConfigMock]);
$saveHandler = $this->objectManager->create(SaveHandler::class, ['sessionConfig' => $sessionConfig]);
$this->model = $this->objectManager->create(
\Magento\Framework\Session\SessionManager::class,
[
'sidResolver' => $this->sidResolver,
'saveHandler' => $saveHandler,
'sessionConfig' => $sessionConfig,
]
);
$this->assertEquals($saveMethod, $sessionConfig->getOption('session.save_handler'));
$this->assertEquals('private_no_expire', $sessionConfig->getOption('session.cache_limiter'));
$this->assertEquals('explicit_save_path', $sessionConfig->getOption('session.save_path'));
$this->assertArrayHasKey('session.use_only_cookies', self::$isIniSetInvoked);
$this->assertEquals('1', self::$isIniSetInvoked['session.use_only_cookies']);
foreach ($sessionConfig->getOptions() as $option => $value) {
if ($option === 'session.save_handler' && $value !== 'memcached') {
$this->assertArrayNotHasKey('session.save_handler', self::$isIniSetInvoked);
} else {
$this->assertArrayHasKey($option, self::$isIniSetInvoked);
$this->assertEquals($value, self::$isIniSetInvoked[$option]);
}
}
$this->assertTrue(self::$isSessionSetSaveHandlerInvoked);
}
/**
* @return array
*/
public function dataConstructor(): array
{
return [
[Config::PARAM_SESSION_SAVE_METHOD =>'db'],
[Config::PARAM_SESSION_SAVE_METHOD =>'redis'],
[Config::PARAM_SESSION_SAVE_METHOD =>'memcached'],
[Config::PARAM_SESSION_SAVE_METHOD =>'user'],
];
}
private function initializeModel(): void
{
$this->model = $this->objectManager->create(
\Magento\Framework\Session\SessionManager::class,
[
'sidResolver' => $this->sidResolver
]
);
}
}
}