Merge branch 'master' into php8

This commit is contained in:
El RIDO 2022-11-17 06:04:12 +01:00
commit 46c0fc851c
No known key found for this signature in database
GPG key ID: 0F5C940A6BD81F92
44 changed files with 1062 additions and 642 deletions

View file

@ -32,9 +32,9 @@ Helper::updateSubresourceIntegrity();
*/
class StorageClientStub extends StorageClient
{
private $_config = null;
private $_connection = null;
private $_buckets = array();
private $_config = null;
private $_connection = null;
private static $_buckets = array();
public function __construct(array $config = array())
{
@ -44,11 +44,11 @@ class StorageClientStub extends StorageClient
public function bucket($name, $userProject = false)
{
if (!key_exists($name, $this->_buckets)) {
if (!key_exists($name, self::$_buckets)) {
$b = new BucketStub($this->_connection, $name, array(), $this);
$this->_buckets[$name] = $b;
self::$_buckets[$name] = $b;
}
return $this->_buckets[$name];
return self::$_buckets[$name];
}
/**
@ -56,8 +56,8 @@ class StorageClientStub extends StorageClient
*/
public function deleteBucket($name)
{
if (key_exists($name, $this->_buckets)) {
unset($this->_buckets[$name]);
if (key_exists($name, self::$_buckets)) {
unset(self::$_buckets[$name]);
} else {
throw new NotFoundException();
}
@ -110,11 +110,11 @@ class StorageClientStub extends StorageClient
public function createBucket($name, array $options = array())
{
if (key_exists($name, $this->_buckets)) {
if (key_exists($name, self::$_buckets)) {
throw new BadRequestException('already exists');
}
$b = new BucketStub($this->_connection, $name, array(), $this);
$this->_buckets[$name] = $b;
self::$_buckets[$name] = $b;
return $b;
}
}

View file

@ -1,649 +0,0 @@
#!/usr/bin/env php
<?php
/**
* generates a config unit test class
*
* This generator is meant to test all possible configuration combinations
* without having to write endless amounts of code manually.
*
* DANGER: Too many options/settings and too high max iteration setting may trigger
* a fork bomb. Please save your work before executing this script.
*/
include 'Bootstrap.php';
$vd = array('view', 'delete');
$vcd = array('view', 'create', 'delete');
new ConfigurationTestGenerator(array(
'main/discussion' => array(
array(
'setting' => true,
'tests' => array(
array(
'conditions' => array('steps' => $vd),
'type' => 'RegExp',
'args' => array(
'#<div[^>]*id="opendiscussionoption"[^>]*>#',
'$content',
'outputs enabled discussion correctly',
),
), array(
'conditions' => array('steps' => array('create'), 'traffic/limit' => 10),
'settings' => array('$_POST["opendiscussion"] = "neither 1 nor 0"'),
'type' => 'Equals',
'args' => array(
1,
'$response["status"]',
'when discussions are enabled, but invalid flag posted, fail to create paste',
),
), array(
'conditions' => array('steps' => array('create'), 'traffic/limit' => 10),
'settings' => array('$_POST["opendiscussion"] = "neither 1 nor 0"'),
'type' => 'False',
'args' => array(
'$this->_model->exists(Helper::getPasteId())',
'when discussions are enabled, but invalid flag posted, paste is not created',
),
),
),
'affects' => $vcd,
), array(
'setting' => false,
'tests' => array(
array(
'type' => 'NotRegExp',
'args' => array(
'#<div[^>]*id="opendiscussionoption"[^>]*>#',
'$content',
'outputs disabled discussion correctly',
),
),
),
'affects' => $vd,
),
),
'main/opendiscussion' => array(
array(
'setting' => true,
'tests' => array(
array(
'conditions' => array('main/discussion' => true),
'type' => 'RegExp',
'args' => array(
'#<input[^>]+id="opendiscussion"[^>]*checked="checked"[^>]*>#',
'$content',
'outputs checked discussion correctly',
),
),
),
'affects' => $vd,
), array(
'setting' => false,
'tests' => array(
array(
'conditions' => array('main/discussion' => true),
'type' => 'NotRegExp',
'args' => array(
'#<input[^>]+id="opendiscussion"[^>]*checked="checked"[^>]*>#',
'$content',
'outputs unchecked discussion correctly',
),
),
),
'affects' => $vd,
),
),
'main/burnafterreadingselected' => array(
array(
'setting' => true,
'tests' => array(
array(
'type' => 'RegExp',
'args' => array(
'#<input[^>]+id="burnafterreading"[^>]*checked="checked"[^>]*>#',
'$content',
'preselects burn after reading option',
),
),
),
'affects' => array('view'),
), array(
'setting' => false,
'tests' => array(
array(
'type' => 'NotRegExp',
'args' => array(
'#<input[^>]+id="burnafterreading"[^>]*checked="checked"[^>]*>#',
'$content',
'burn after reading option is unchecked',
),
),
),
'affects' => array('view'),
),
),
'main/password' => array(
array(
'setting' => true,
'tests' => array(
array(
'type' => 'RegExp',
'args' => array(
'#<div[^>]*id="password"[^>]*>#',
'$content',
'outputs password input correctly',
),
),
),
'affects' => $vd,
), array(
'setting' => false,
'tests' => array(
array(
'conditions' => array('main/discussion' => true),
'type' => 'NotRegExp',
'args' => array(
'#<div[^>]*id="password"[^>]*>#',
'$content',
'removes password input correctly',
),
),
),
'affects' => $vd,
),
),
'main/template' => array(
array(
'setting' => 'page',
'tests' => array(
array(
'type' => 'RegExp',
'args' => array(
'#<link[^>]+type="text/css"[^>]+rel="stylesheet"[^>]+href="css/privatebin\.css\\?\d[\d\.]+\d+"[^>]*/>#',
'$content',
'outputs "page" stylesheet correctly',
),
), array(
'type' => 'NotRegExp',
'args' => array(
'#<link[^>]+type="text/css"[^>]+rel="stylesheet"[^>]+href="css/bootstrap/bootstrap-\d[\d\.]+\d\.css"[^>]*/>#',
'$content',
'removes "bootstrap" stylesheet correctly',
),
),
),
'affects' => $vd,
), array(
'setting' => 'bootstrap',
'tests' => array(
array(
'type' => 'NotRegExp',
'args' => array(
'#<link[^>]+type="text/css"[^>]+rel="stylesheet"[^>]+href="css/privatebin\.css\\?\d[\d\.]+\d+"[^>]*/>#',
'$content',
'removes "page" stylesheet correctly',
),
), array(
'type' => 'RegExp',
'args' => array(
'#<link[^>]+type="text/css"[^>]+rel="stylesheet"[^>]+href="css/bootstrap/bootstrap-\d[\d\.]+\d\.css"[^>]*/>#',
'$content',
'outputs "bootstrap" stylesheet correctly',
),
),
),
'affects' => $vd,
),
),
'main/sizelimit' => array(
array(
'setting' => 10,
'tests' => array(
array(
'conditions' => array('steps' => array('create'), 'traffic/limit' => 10),
'type' => 'Equals',
'args' => array(
1,
'$response["status"]',
'when sizelimit limit exceeded, fail to create paste',
),
),
),
'affects' => array('create'),
), array(
'setting' => 2097152,
'tests' => array(
array(
'conditions' => array('steps' => array('create'), 'traffic/limit' => 0, 'main/burnafterreadingselected' => true),
'settings' => array('sleep(3)'),
'type' => 'Equals',
'args' => array(
0,
'$response["status"]',
'when sizelimit limit is not reached, successfully create paste',
),
), array(
'conditions' => array('steps' => array('create'), 'traffic/limit' => 0, 'main/burnafterreadingselected' => true),
'settings' => array('sleep(3)'),
'type' => 'True',
'args' => array(
'$this->_model->exists($response["id"])',
'when sizelimit limit is not reached, paste exists after posting data',
),
),
),
'affects' => array('create'),
),
),
'traffic/limit' => array(
array(
'setting' => 0,
'tests' => array(
array(
'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
'type' => 'Equals',
'args' => array(
0,
'$response["status"]',
'when traffic limit is disabled, successfully create paste',
),
), array(
'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
'type' => 'True',
'args' => array(
'$this->_model->exists($response["id"])',
'when traffic limit is disabled, paste exists after posting data',
),
),
),
'affects' => array('create'),
), array(
'setting' => 10,
'tests' => array(
array(
'conditions' => array('steps' => array('create')),
'type' => 'Equals',
'args' => array(
1,
'$response["status"]',
'when traffic limit is on and we do not wait, fail to create paste',
),
),
),
'affects' => array('create'),
), array(
'setting' => 2,
'tests' => array(
array(
'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
'settings' => array('sleep(3)'),
'type' => 'Equals',
'args' => array(
0,
'$response["status"]',
'when traffic limit is on and we wait, successfully create paste',
),
), array(
'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
'settings' => array('sleep(3)'),
'type' => 'True',
'args' => array(
'$this->_model->exists($response["id"])',
'when traffic limit is on and we wait, paste exists after posting data',
),
),
),
'affects' => array('create'),
),
),
));
class ConfigurationTestGenerator
{
/**
* endless loop protection, since we're working with a recursive function,
* creating factorial configurations
* @var int
*/
const MAX_ITERATIONS = 2000;
/**
* options to test
* @var array
*/
private $_options;
/**
* iteration count to guarantee timely end
* @var int
*/
private $_iterationCount = 0;
/**
* generated configurations
* @var array
*/
private $_configurations = array(
array('options' => array(), 'tests' => array(), 'affects' => array()),
);
/**
* constructor, generates the configuration test
* @param array $options
*/
public function __construct($options)
{
$this->_options = $options;
// generate all possible combinations of options: options^settings
$this->_generateConfigurations();
$this->_writeConfigurationTest();
}
/**
* write configuration test file based on generated configuration array
*/
private function _writeConfigurationTest()
{
$defaultOptions = parse_ini_file(CONF_SAMPLE, true);
$code = $this->_getHeader();
foreach ($this->_configurations as $key => $conf) {
$fullOptions = array_replace_recursive($defaultOptions, $conf['options']);
$options = Helper::varExportMin($fullOptions, true);
foreach ($conf['affects'] as $step) {
$testCode = $preCode = array();
foreach ($conf['tests'] as $tests) {
foreach ($tests[0] as $test) {
// skip if test does not affect this step
if (!in_array($step, $tests[1])) {
continue;
}
// skip if not all test conditions are met
if (array_key_exists('conditions', $test)) {
while (list($path, $setting) = each($test['conditions'])) {
if ($path == 'steps' && !in_array($step, $setting)) {
continue 2;
} elseif ($path != 'steps') {
list($section, $option) = explode('/', $path);
if ($fullOptions[$section][$option] !== $setting) {
continue 2;
}
}
}
}
if (array_key_exists('settings', $test)) {
foreach ($test['settings'] as $setting) {
$preCode[$setting] = $setting;
}
}
$args = array();
foreach ($test['args'] as $arg) {
if (is_string($arg) && strpos($arg, '$') === 0) {
$args[] = $arg;
} else {
$args[] = Helper::varExportMin($arg, true);
}
}
$testCode[] = array($test['type'], implode(', ', $args));
}
}
$code .= $this->_getFunction(
ucfirst($step), $key, $options, $preCode, $testCode, $fullOptions['main']['discussion']
);
}
}
$code .= '}' . PHP_EOL;
file_put_contents('ConfigurationCombinationsTest.php', $code);
}
/**
* get header of configuration test file
*
* @return string
*/
private function _getHeader()
{
return <<<'EOT'
<?php
/**
* DO NOT EDIT: This file is generated automatically using configGenerator.php
*/
use PHPUnit\Framework\TestCase;
use PrivateBin\Controller;
use PrivateBin\Data\Filesystem;
use PrivateBin\Persistence\ServerSalt;
use PrivateBin\Persistence\TrafficLimiter;
use PrivateBin\Request;
class ConfigurationCombinationsTest extends TestCase
{
private $_conf;
private $_model;
private $_path;
public function setUp(): void
{
/* Setup Routine */
Helper::confBackup();
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
$this->_model = Filesystem::getInstance(array('dir' => $this->_path));
$this->reset();
}
public function tearDown(): void
{
/* Tear Down Routine */
unlink(CONF);
Helper::confRestore();
Helper::rmDir($this->_path);
}
public function reset($configuration = array())
{
$_POST = array();
$_GET = array();
$_SERVER = array();
if ($this->_model->exists(Helper::getPasteId()))
$this->_model->delete(Helper::getPasteId());
$configuration['model_options']['dir'] = $this->_path;
Helper::createIniFile(CONF, $configuration);
}
EOT;
}
/**
* get unit tests function block
*
* @param string $step
* @param int $key
* @param array $options
* @param array $preCode
* @param array $testCode
* @return string
*/
private function _getFunction($step, $key, &$options, $preCode, $testCode, $discussionEnabled)
{
if (count($testCode) == 0) {
echo "skipping creation of test$step$key, no valid tests found for configuration: $options" . PHP_EOL;
return '';
}
$preString = $testString = '';
foreach ($preCode as $setting) {
$preString .= " $setting;" . PHP_EOL;
}
foreach ($testCode as $test) {
$type = $test[0];
$args = $test[1];
$testString .= " \$this->assert$type($args);" . PHP_EOL;
}
$code = <<<EOT
/**
* @runInSeparateProcess
*/
public function test$step$key()
{
\$this->reset($options);
EOT;
// step specific initialization
switch ($step) {
case 'Create':
if ($discussionEnabled) {
$code .= PHP_EOL . <<<'EOT'
$paste = Helper::getPasteJson();
EOT;
} else {
$code .= PHP_EOL . <<<'EOT'
$paste = json_decode(Helper::getPasteJson(), true);
$paste['adata'][2] = 0;
$paste = json_encode($paste);
EOT;
}
$code .= PHP_EOL . <<<'EOT'
$file = tempnam(sys_get_temp_dir(), 'FOO');
file_put_contents($file, $paste);
Request::setInputStream($file);
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'JSONHttpRequest';
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['REMOTE_ADDR'] = '::1';
TrafficLimiter::canPass();
EOT;
break;
case 'Read':
$code .= PHP_EOL . <<<'EOT'
$this->_model->create(Helper::getPasteId(), Helper::getPaste());
$_SERVER['QUERY_STRING'] = Helper::getPasteId();
$_GET[Helper::getPasteId()] = '';
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'JSONHttpRequest';
EOT;
break;
case 'Delete':
$code .= PHP_EOL . <<<'EOT'
$this->_model->create(Helper::getPasteId(), Helper::getPaste());
$this->assertTrue($this->_model->exists(Helper::getPasteId()), 'paste exists before deleting data');
$_GET['pasteid'] = Helper::getPasteId();
$_GET['deletetoken'] = hash_hmac('sha256', Helper::getPasteId(), $this->_model->read(Helper::getPasteId())['meta']['salt']);
EOT;
break;
}
// all steps
$code .= PHP_EOL . $preString;
$code .= <<<'EOT'
ob_start();
new Controller;
$content = ob_get_contents();
ob_end_clean();
EOT;
// step specific tests
switch ($step) {
case 'Create':
$code .= <<<'EOT'
$response = json_decode($content, true);
EOT;
break;
case 'Read':
$code .= <<<'EOT'
$response = json_decode($content, true);
$this->assertEquals(0, $response['status'], 'outputs success status');
$this->assertEquals(Helper::getPasteId(), $response['id'], 'outputs id correctly');
$this->assertEquals(Helper::getPaste()['data'], $response['data'], 'outputs data correctly');
EOT;
break;
case 'Delete':
$code .= <<<'EOT'
$this->assertMatchesRegularExpression(
'#<div[^>]*id="status"[^>]*>.*Paste was properly deleted[^<]*</div>#s',
$content,
'outputs deleted status correctly'
);
$this->assertFalse($this->_model->exists(Helper::getPasteId()), 'paste successfully deleted');
EOT;
break;
}
return $code . PHP_EOL . PHP_EOL . $testString . ' }' . PHP_EOL . PHP_EOL;
}
/**
* recursive function to generate configurations based on options
*
* @throws Exception
* @return array
*/
private function _generateConfigurations()
{
// recursive factorial function
if (++$this->_iterationCount > self::MAX_ITERATIONS) {
echo 'max iterations reached, stopping', PHP_EOL;
return $this->_configurations;
}
echo "generateConfigurations: iteration $this->_iterationCount", PHP_EOL;
$continue = list($path, $settings) = each($this->_options);
if ($continue === false) {
return $this->_configurations;
}
list($section, $option) = explode('/', $path);
for ($c = 0, $max = count($this->_configurations); $c < $max; ++$c) {
if (!array_key_exists($section, $this->_configurations[$c]['options'])) {
$this->_configurations[$c]['options'][$section] = array();
}
if (count($settings) == 0) {
throw new Exception("Check your \$options: option $option has no settings!");
}
// set the first setting in the original configuration
$setting = current($settings);
$this->_addSetting($this->_configurations[$c], $setting, $section, $option);
// create clones for each of the other settings
while ($setting = next($settings)) {
$clone = $this->_configurations[$c];
$this->_configurations[] = $this->_addSetting($clone, $setting, $section, $option);
}
reset($settings);
}
return $this->_generateConfigurations();
}
/**
* add a setting to the given configuration
*
* @param array $configuration
* @param array $setting
* @param string $section
* @param string $option
* @throws Exception
* @return array
*/
private function _addSetting(&$configuration, &$setting, &$section, &$option)
{
if (++$this->_iterationCount > self::MAX_ITERATIONS) {
echo 'max iterations reached, stopping', PHP_EOL;
return $configuration;
}
echo "addSetting: iteration $this->_iterationCount", PHP_EOL;
if (
array_key_exists($option, $configuration['options'][$section]) &&
$configuration['options'][$section][$option] === $setting['setting']
) {
$val = Helper::varExportMin($setting['setting'], true);
throw new Exception("Endless loop or error in options detected: option '$option' already exists with setting '$val' in one of the configurations!");
}
$configuration['options'][$section][$option] = $setting['setting'];
$configuration['tests'][$option] = array($setting['tests'], $setting['affects']);
foreach ($setting['affects'] as $affects) {
if (!in_array($affects, $configuration['affects'])) {
$configuration['affects'][] = $affects;
}
}
return $configuration;
}
}

View file

@ -17,7 +17,7 @@ class ControllerTest extends TestCase
{
/* Setup Routine */
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
$this->_data = Filesystem::getInstance(array('dir' => $this->_path));
$this->_data = new Filesystem(array('dir' => $this->_path));
ServerSalt::setStore($this->_data);
TrafficLimiter::setStore($this->_data);
$this->reset();

View file

@ -25,7 +25,7 @@ class ControllerWithDbTest extends ControllerTest
mkdir($this->_path);
}
$this->_options['dsn'] = 'sqlite:' . $this->_path . DIRECTORY_SEPARATOR . 'tst.sq3';
$this->_data = Database::getInstance($this->_options);
$this->_data = new Database($this->_options);
ServerSalt::setStore($this->_data);
TrafficLimiter::setStore($this->_data);
$this->reset();

View file

@ -39,7 +39,7 @@ class ControllerWithGcsTest extends ControllerTest
'bucket' => self::$_bucket->name(),
'prefix' => 'pastes',
);
$this->_data = GoogleCloudStorage::getInstance($this->_options);
$this->_data = new GoogleCloudStorage($this->_options);
ServerSalt::setStore($this->_data);
TrafficLimiter::setStore($this->_data);
$this->reset();

View file

@ -23,7 +23,7 @@ class DatabaseTest extends TestCase
{
/* Setup Routine */
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
$this->_model = Database::getInstance($this->_options);
$this->_model = new Database($this->_options);
}
public function tearDown(): void
@ -36,7 +36,7 @@ class DatabaseTest extends TestCase
public function testSaltMigration()
{
ServerSalt::setStore(Filesystem::getInstance(array('dir' => 'data')));
ServerSalt::setStore(new Filesystem(array('dir' => 'data')));
$salt = ServerSalt::get();
$file = 'data' . DIRECTORY_SEPARATOR . 'salt.php';
$this->assertFileExists($file, 'ServerSalt got initialized and stored on disk');
@ -140,7 +140,7 @@ class DatabaseTest extends TestCase
public function testGetIbmInstance()
{
$this->expectException(PDOException::class);
Database::getInstance(array(
new Database(array(
'dsn' => 'ibm:', 'usr' => null, 'pwd' => null,
'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
));
@ -149,7 +149,7 @@ class DatabaseTest extends TestCase
public function testGetInformixInstance()
{
$this->expectException(PDOException::class);
Database::getInstance(array(
new Database(array(
'dsn' => 'informix:', 'usr' => null, 'pwd' => null,
'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
));
@ -158,7 +158,7 @@ class DatabaseTest extends TestCase
public function testGetMssqlInstance()
{
$this->expectException(PDOException::class);
Database::getInstance(array(
new Database(array(
'dsn' => 'mssql:', 'usr' => null, 'pwd' => null,
'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
));
@ -167,7 +167,7 @@ class DatabaseTest extends TestCase
public function testGetMysqlInstance()
{
$this->expectException(PDOException::class);
Database::getInstance(array(
new Database(array(
'dsn' => 'mysql:', 'usr' => null, 'pwd' => null,
'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
));
@ -176,7 +176,7 @@ class DatabaseTest extends TestCase
public function testGetOciInstance()
{
$this->expectException(PDOException::class);
Database::getInstance(array(
new Database(array(
'dsn' => 'oci:', 'usr' => null, 'pwd' => null,
'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
));
@ -185,7 +185,7 @@ class DatabaseTest extends TestCase
public function testGetPgsqlInstance()
{
$this->expectException(PDOException::class);
Database::getInstance(array(
new Database(array(
'dsn' => 'pgsql:', 'usr' => null, 'pwd' => null,
'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
));
@ -195,7 +195,7 @@ class DatabaseTest extends TestCase
{
$this->expectException(Exception::class);
$this->expectExceptionCode(5);
Database::getInstance(array(
new Database(array(
'dsn' => 'foo:', 'usr' => null, 'pwd' => null, 'opt' => null,
));
}
@ -206,7 +206,7 @@ class DatabaseTest extends TestCase
unset($options['dsn']);
$this->expectException(Exception::class);
$this->expectExceptionCode(6);
Database::getInstance($options);
new Database($options);
}
public function testMissingUsr()
@ -215,7 +215,7 @@ class DatabaseTest extends TestCase
unset($options['usr']);
$this->expectException(Exception::class);
$this->expectExceptionCode(6);
Database::getInstance($options);
new Database($options);
}
public function testMissingPwd()
@ -224,7 +224,7 @@ class DatabaseTest extends TestCase
unset($options['pwd']);
$this->expectException(Exception::class);
$this->expectExceptionCode(6);
Database::getInstance($options);
new Database($options);
}
public function testMissingOpt()
@ -233,7 +233,7 @@ class DatabaseTest extends TestCase
unset($options['opt']);
$this->expectException(Exception::class);
$this->expectExceptionCode(6);
Database::getInstance($options);
new Database($options);
}
public function testOldAttachments()
@ -245,7 +245,7 @@ class DatabaseTest extends TestCase
}
$this->_options['dsn'] = 'sqlite:' . $path;
$this->_options['tbl'] = 'bar_';
$model = Database::getInstance($this->_options);
$model = new Database($this->_options);
$original = $paste = Helper::getPasteWithAttachment(1, array('expire_date' => 1344803344));
$meta = $paste['meta'];
@ -290,7 +290,7 @@ class DatabaseTest extends TestCase
}
$this->_options['dsn'] = 'sqlite:' . $path;
$this->_options['tbl'] = 'baz_';
$model = Database::getInstance($this->_options);
$model = new Database($this->_options);
$paste = Helper::getPaste(1, array('expire_date' => 1344803344));
unset($paste['meta']['formatter'], $paste['meta']['opendiscussion'], $paste['meta']['salt']);
$model->delete(Helper::getPasteId());
@ -357,7 +357,7 @@ class DatabaseTest extends TestCase
'vizhash BLOB, ' .
'postdate INT );'
);
$this->assertInstanceOf('PrivateBin\\Data\\Database', Database::getInstance($this->_options));
$this->assertInstanceOf('PrivateBin\\Data\\Database', new Database($this->_options));
// check if version number was upgraded in created configuration table
$statement = $db->prepare('SELECT value FROM foo_config WHERE id LIKE ?');

View file

@ -16,7 +16,7 @@ class FilesystemTest extends TestCase
/* Setup Routine */
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
$this->_invalidPath = $this->_path . DIRECTORY_SEPARATOR . 'bar';
$this->_model = Filesystem::getInstance(array('dir' => $this->_path));
$this->_model = new Filesystem(array('dir' => $this->_path));
if (!is_dir($this->_path)) {
mkdir($this->_path);
}

View file

@ -27,7 +27,7 @@ class GoogleCloudStorageTest extends TestCase
public function setUp(): void
{
ini_set('error_log', stream_get_meta_data(tmpfile())['uri']);
$this->_model = GoogleCloudStorage::getInstance(array(
$this->_model = new GoogleCloudStorage(array(
'bucket' => self::$_bucket->name(),
'prefix' => 'pastes',
));

View file

@ -1,97 +0,0 @@
#!/usr/bin/env php
<?php
define('ITERATIONS', 100000);
require dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
use Identicon\Generator\GdGenerator;
use Identicon\Generator\ImageMagickGenerator;
use Identicon\Generator\SvgGenerator;
use Identicon\Identicon;
use PrivateBin\Vizhash16x16;
$vizhash = new Vizhash16x16();
$identiconGenerators = array(
'identicon GD' => new Identicon(new GdGenerator()),
'identicon ImageMagick' => new Identicon(new ImageMagickGenerator()),
'identicon SVG' => new Identicon(new SvgGenerator())
);
$results = array(
'vizhash' => array(
'lengths' => array(),
'time' => 0
),
'identicon GD' => array(
'lengths' => array(),
'time' => 0
),
'identicon ImageMagick' => array(
'lengths' => array(),
'time' => 0
),
'identicon SVG' => array(
'lengths' => array(),
'time' => 0
)
);
$hmacs = array();
echo 'generate ', ITERATIONS, ' hmacs and pre-populate the result array, so tests wont be slowed down', PHP_EOL;
for ($i = 0; $i < ITERATIONS; ++$i) {
$hmacs[$i] = hash_hmac('sha512', '127.0.0.1', bin2hex(random_bytes(256)));
$results['vizhash']['lengths'][$i] = 0;
$results['identicon GD']['lengths'][$i] = 0;
$results['identicon ImageMagick']['lengths'][$i] = 0;
$results['identicon SVG']['lengths'][$i] = 0;
}
echo 'run vizhash tests', PHP_EOL;
$start = microtime(true);
foreach ($hmacs as $i => $hmac) {
$data = 'data:image/png;base64,' . base64_encode(
$vizhash->generate($hmac)
);
$results['vizhash']['lengths'][$i] = strlen($data);
}
$results['vizhash']['time'] = microtime(true) - $start;
foreach ($identiconGenerators as $key => $identicon) {
echo 'run ', $key,' tests', PHP_EOL;
$start = microtime(true);
foreach ($hmacs as $i => $hmac) {
$data = $identicon->getImageDataUri($hmac, 16);
$results[$key]['lengths'][$i] = strlen($data);
}
$results[$key]['time'] = microtime(true) - $start;
}
define('PADDING_LENGTH', max(array_map(function ($key) { return strlen($key); }, array_keys($results))) + 1);
function format_result_line($generator, $min, $max, $avg, $sec) {
echo str_pad($generator, PADDING_LENGTH, ' '), "\t",
str_pad($min, 4, ' ', STR_PAD_LEFT), "\t",
str_pad($max, 4, ' ', STR_PAD_LEFT), "\t",
str_pad($avg, 4, ' ', STR_PAD_LEFT), "\t",
str_pad($sec, 7, ' ', STR_PAD_LEFT), PHP_EOL;
}
echo PHP_EOL;
format_result_line('Generator:', 'min', 'max', 'avg', 'seconds');
format_result_line(str_repeat('─', PADDING_LENGTH), str_repeat('─', 4), str_repeat('─', 4), str_repeat('─', 4), str_repeat('─', 7));
foreach ($results as $generator => $result) {
sort($result['lengths']);
format_result_line(
$generator . ':',
$result['lengths'][0],
$result['lengths'][ITERATIONS-1],
round(array_sum($result['lengths']) / ITERATIONS),
round($result['time'], 3)
);
}

View file

@ -19,7 +19,7 @@ class JsonApiTest extends TestCase
if (!is_dir($this->_path)) {
mkdir($this->_path);
}
$this->_model = Filesystem::getInstance(array('dir' => $this->_path));
$this->_model = new Filesystem(array('dir' => $this->_path));
ServerSalt::setStore($this->_model);
$_POST = array();

82
tst/MigrateTest.php Normal file
View file

@ -0,0 +1,82 @@
<?php
use PHPUnit\Framework\TestCase;
use PrivateBin\Data\Database;
use PrivateBin\Data\Filesystem;
class MigrateTest extends TestCase
{
protected $_model_1;
protected $_model_2;
protected $_path;
protected $_path_instance_1;
protected $_path_instance_2;
public function setUp(): void
{
/* Setup Routine */
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
$this->_path_instance_1 = $this->_path . DIRECTORY_SEPARATOR . 'instance_1';
$this->_path_instance_2 = $this->_path . DIRECTORY_SEPARATOR . 'instance_2';
if (!is_dir($this->_path)) {
mkdir($this->_path);
}
mkdir($this->_path_instance_1);
mkdir($this->_path_instance_1 . DIRECTORY_SEPARATOR . 'cfg');
mkdir($this->_path_instance_2);
mkdir($this->_path_instance_2 . DIRECTORY_SEPARATOR . 'cfg');
$options = parse_ini_file(CONF_SAMPLE, true);
$options['purge']['limit'] = 0;
$options['model_options']['dir'] = $this->_path_instance_1 . DIRECTORY_SEPARATOR . 'data';
$this->_model_1 = new Filesystem($options['model_options']);
Helper::createIniFile($this->_path_instance_1 . DIRECTORY_SEPARATOR . 'cfg' . DIRECTORY_SEPARATOR . 'conf.php', $options);
$options['model'] = array(
'class' => 'Database',
);
$options['model_options'] = array(
'dsn' => 'sqlite:' . $this->_path_instance_2 . DIRECTORY_SEPARATOR . 'test.sq3',
'usr' => null,
'pwd' => null,
'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
);
$this->_model_2 = new Database($options['model_options']);
Helper::createIniFile($this->_path_instance_2 . DIRECTORY_SEPARATOR . 'cfg' . DIRECTORY_SEPARATOR . 'conf.php', $options);
}
public function tearDown(): void
{
/* Tear Down Routine */
Helper::rmDir($this->_path);
}
public function testMigrate()
{
$this->_model_1->delete(Helper::getPasteId());
$this->_model_2->delete(Helper::getPasteId());
// storing paste & comment
$this->_model_1->create(Helper::getPasteId(), Helper::getPaste());
$this->_model_1->createComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId(), Helper::getComment());
// migrate files to database
$output = null;
$exit_code = 255;
exec('php ' . PATH . 'bin' . DIRECTORY_SEPARATOR . 'migrate --delete-after ' . $this->_path_instance_1 . DIRECTORY_SEPARATOR . 'cfg ' . $this->_path_instance_2 . DIRECTORY_SEPARATOR . 'cfg', $output, $exit_code);
$this->assertEquals(0, $exit_code, 'migrate script exits 0');
$this->assertFalse($this->_model_1->exists(Helper::getPasteId()), 'paste removed after migrating it');
$this->assertFalse($this->_model_1->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId()), 'comment removed after migrating it');
$this->assertTrue($this->_model_2->exists(Helper::getPasteId()), 'paste migrated');
$this->assertTrue($this->_model_2->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId()), 'comment migrated');
// migrate back to files
$exit_code = 255;
exec('php ' . PATH . 'bin' . DIRECTORY_SEPARATOR . 'migrate ' . $this->_path_instance_2 . DIRECTORY_SEPARATOR . 'cfg ' . $this->_path_instance_1 . DIRECTORY_SEPARATOR . 'cfg', $output, $exit_code);
$this->assertEquals(0, $exit_code, 'migrate script exits 0');
$this->assertTrue($this->_model_1->exists(Helper::getPasteId()), 'paste migrated back');
$this->assertTrue($this->_model_1->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId()), 'comment migrated back');
}
}

View file

@ -1,6 +1,6 @@
<?php
use Jdenticon\Identicon;
use Identicon\Identicon;
use PHPUnit\Framework\TestCase;
use PrivateBin\Configuration;
use PrivateBin\Data\Database;
@ -39,7 +39,7 @@ class ModelTest extends TestCase
);
Helper::confBackup();
Helper::createIniFile(CONF, $options);
ServerSalt::setStore(Database::getInstance($options['model_options']));
ServerSalt::setStore(new Database($options['model_options']));
$this->_conf = new Configuration;
$this->_model = new Model($this->_conf);
$_SERVER['REMOTE_ADDR'] = '::1';
@ -157,10 +157,10 @@ class ModelTest extends TestCase
public function testCommentDefaults()
{
$class = 'PrivateBin\\Data\\' . $this->_conf->getKey('class', 'model');
$comment = new Comment(
$this->_conf,
forward_static_call(
'PrivateBin\\Data\\' . $this->_conf->getKey('class', 'model') . '::getInstance',
new $class(
$this->_conf->getSection('model_options')
)
);
@ -252,7 +252,10 @@ class ModelTest extends TestCase
$paste = $model->getPaste();
$paste->setData($pasteData);
$paste->store();
$paste->exists();
$this->assertTrue($paste->exists(), 'paste exists before creating comment');
$comment = $paste->getComment(Helper::getPasteId());
$comment->setData($commentData);
$db = new PDO(
$options['model_options']['dsn'],
@ -264,8 +267,6 @@ class ModelTest extends TestCase
$statement->execute();
$statement->closeCursor();
$comment = $paste->getComment(Helper::getPasteId());
$comment->setData($commentData);
$this->expectException(Exception::class);
$this->expectExceptionCode(70);
$comment->store();
@ -307,15 +308,8 @@ class ModelTest extends TestCase
$comment->get();
$comment->store();
$identicon = new Identicon(array(
'hash' => TrafficLimiter::getHash(),
'size' => 16,
'style' => array(
'backgroundColor' => '#fff0', // fully transparent, for dark mode
'padding' => 0,
),
));
$pngdata = $identicon->getImageDataUri('png');
$identicon = new Identicon();
$pngdata = $identicon->getImageDataUri(TrafficLimiter::getHash(), 16);
$comment = current($this->_model->getPaste(Helper::getPasteId())->get()['comments']);
$this->assertEquals($pngdata, $comment['meta']['icon'], 'icon gets set');
}
@ -428,7 +422,7 @@ class ModelTest extends TestCase
public function testPurge()
{
$conf = new Configuration;
$store = Database::getInstance($conf->getSection('model_options'));
$store = new Database($conf->getSection('model_options'));
$store->delete(Helper::getPasteId());
$expired = Helper::getPaste(2, array('expire_date' => 1344803344));
$paste = Helper::getPaste(2, array('expire_date' => time() + 3600));

View file

@ -16,7 +16,7 @@ class PurgeLimiterTest extends TestCase
mkdir($this->_path);
}
PurgeLimiter::setStore(
Filesystem::getInstance(array('dir' => $this->_path))
new Filesystem(array('dir' => $this->_path))
);
}

View file

@ -22,7 +22,7 @@ class ServerSaltTest extends TestCase
mkdir($this->_path);
}
ServerSalt::setStore(
Filesystem::getInstance(array('dir' => $this->_path))
new Filesystem(array('dir' => $this->_path))
);
$this->_otherPath = $this->_path . DIRECTORY_SEPARATOR . 'foo';
@ -45,17 +45,17 @@ class ServerSaltTest extends TestCase
{
// generating new salt
ServerSalt::setStore(
Filesystem::getInstance(array('dir' => $this->_path))
new Filesystem(array('dir' => $this->_path))
);
$salt = ServerSalt::get();
// try setting a different path and resetting it
ServerSalt::setStore(
Filesystem::getInstance(array('dir' => $this->_otherPath))
new Filesystem(array('dir' => $this->_otherPath))
);
$this->assertNotEquals($salt, ServerSalt::get());
ServerSalt::setStore(
Filesystem::getInstance(array('dir' => $this->_path))
new Filesystem(array('dir' => $this->_path))
);
$this->assertEquals($salt, ServerSalt::get());
}
@ -64,7 +64,7 @@ class ServerSaltTest extends TestCase
{
// try setting an invalid path
chmod($this->_invalidPath, 0000);
$store = Filesystem::getInstance(array('dir' => $this->_invalidPath));
$store = new Filesystem(array('dir' => $this->_invalidPath));
ServerSalt::setStore($store);
$salt = ServerSalt::get();
ServerSalt::setStore($store);
@ -77,7 +77,7 @@ class ServerSaltTest extends TestCase
chmod($this->_invalidPath, 0700);
file_put_contents($this->_invalidFile, '');
chmod($this->_invalidFile, 0000);
$store = Filesystem::getInstance(array('dir' => $this->_invalidPath));
$store = new Filesystem(array('dir' => $this->_invalidPath));
ServerSalt::setStore($store);
$salt = ServerSalt::get();
ServerSalt::setStore($store);
@ -94,7 +94,7 @@ class ServerSaltTest extends TestCase
}
file_put_contents($this->_invalidPath . DIRECTORY_SEPARATOR . '.htaccess', '');
chmod($this->_invalidPath, 0500);
$store = Filesystem::getInstance(array('dir' => $this->_invalidPath));
$store = new Filesystem(array('dir' => $this->_invalidPath));
ServerSalt::setStore($store);
$salt = ServerSalt::get();
ServerSalt::setStore($store);
@ -106,9 +106,9 @@ class ServerSaltTest extends TestCase
// try creating an invalid path
chmod($this->_invalidPath, 0000);
ServerSalt::setStore(
Filesystem::getInstance(array('dir' => $this->_invalidPath . DIRECTORY_SEPARATOR . 'baz'))
new Filesystem(array('dir' => $this->_invalidPath . DIRECTORY_SEPARATOR . 'baz'))
);
$store = Filesystem::getInstance(array('dir' => $this->_invalidPath));
$store = new Filesystem(array('dir' => $this->_invalidPath));
ServerSalt::setStore($store);
$salt = ServerSalt::get();
ServerSalt::setStore($store);

View file

@ -13,7 +13,7 @@ class TrafficLimiterTest extends TestCase
{
/* Setup Routine */
$this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'trafficlimit';
$store = Filesystem::getInstance(array('dir' => $this->_path));
$store = new Filesystem(array('dir' => $this->_path));
ServerSalt::setStore($store);
TrafficLimiter::setStore($store);
}

View file

@ -19,7 +19,7 @@ class Vizhash16x16Test extends TestCase
mkdir($this->_path);
}
$this->_file = $this->_path . DIRECTORY_SEPARATOR . 'vizhash.png';
ServerSalt::setStore(Filesystem::getInstance(array('dir' => $this->_path)));
ServerSalt::setStore(new Filesystem(array('dir' => $this->_path)));
}
public function tearDown(): void

View file

@ -14,7 +14,6 @@
</coverage>
<testsuite name="PrivateBin Test Suite">
<directory suffix=".php">./</directory>
<exclude>ConfigurationTestGenerator.php</exclude>
</testsuite>
<logging>
<testdoxHtml outputFile="log/testdox.html"/>