Files
FreshRSS/tests/lib/Minz/ConfigurationTest.php
T
S M Nazmuz SakibandAlexandre Alapetite 6048309573 Make configuration saves crash-safe (#9651)
Fixes #9650

Writes the temporary config file with a checked full write followed by `fflush()` and `fsync()` before the atomic rename, so an unclean shutdown cannot leave `config.php` truncated to zero bytes. The backup is now only replaced when the current config file is non-empty, preserving the last known-good backup if a previous save was interrupted.

Adds regression tests covering a normal save (previous config backed up) and a save when the current config file is empty (existing backup preserved).

* Make configuration saves crash-safe

* Simplify comments

---------

Co-authored-by: Alexandre Alapetite <alexandre@alapetite.fr>
2026-11-29 17:55:33 +01:00

62 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
class ConfigurationTest extends TestCase {
/** @var array<string,string> */
private array $files = [];
#[\Override]
protected function setUp(): void {
$directory = sys_get_temp_dir() . '/freshrss-config-test-' . bin2hex(random_bytes(8));
mkdir($directory);
$this->files['directory'] = $directory;
$this->files['config'] = $directory . '/config.php';
$this->files['default'] = $directory . '/default.php';
$this->files['backup'] = $this->files['config'] . '.bak.php';
file_put_contents($this->files['default'], "<?php\nreturn ['title' => 'Default'];\n");
}
#[\Override]
protected function tearDown(): void {
foreach ($this->files as $file) {
if (is_file($file)) {
@unlink($file);
}
}
@rmdir($this->files['directory']);
}
private function configuration(): Minz_Configuration {
$namespace = 'test-' . bin2hex(random_bytes(8));
Minz_Configuration::register($namespace, $this->files['config'], $this->files['default']);
return Minz_Configuration::get($namespace);
}
public function testSaveBacksUpThePreviousConfiguration(): void {
$previous = "<?php\nreturn ['title' => 'Previous'];\n";
file_put_contents($this->files['config'], $previous);
$configuration = $this->configuration();
$configuration->title = 'Current';
self::assertTrue($configuration->save());
self::assertSame($previous, file_get_contents($this->files['backup']));
self::assertSame(['title' => 'Current'], include $this->files['config']);
self::assertFileDoesNotExist($this->files['config'] . '.tmp.php');
}
public function testSaveKeepsTheBackupWhenTheConfigurationFileIsEmpty(): void {
$goodBackup = "<?php\nreturn ['title' => 'Good backup'];\n";
file_put_contents($this->files['backup'], $goodBackup);
file_put_contents($this->files['config'], '');
$configuration = $this->configuration();
$configuration->title = 'Recovered';
self::assertTrue($configuration->save());
self::assertSame($goodBackup, file_get_contents($this->files['backup']));
self::assertSame(['title' => 'Recovered'], include $this->files['config']);
}
}