Tests für Anmeldung und Controller, PHP 8.1, Sprach-Fallback
All checks were successful
CI / PHP Lint (push) Successful in 37s
CI / PHP Lint-1 (push) Successful in 53s
CI / Unit Tests & Static Analysis (push) Successful in 40s
CI / PHP Lint (pull_request) Successful in 39s
CI / PHP Lint-1 (pull_request) Successful in 44s
CI / Unit Tests & Static Analysis (pull_request) Successful in 44s
All checks were successful
CI / PHP Lint (push) Successful in 37s
CI / PHP Lint-1 (push) Successful in 53s
CI / Unit Tests & Static Analysis (push) Successful in 40s
CI / PHP Lint (pull_request) Successful in 39s
CI / PHP Lint-1 (pull_request) Successful in 44s
CI / Unit Tests & Static Analysis (pull_request) Successful in 44s
Bisher deckten die Tests nur Hilfsklassen ab. Neu sind die beiden Stellen, an denen ein Fehler richtig weh tut: - AuthTest (12 Fälle): richtige und falsche Anmeldung, Rate-Limit greift vor der Passwortprüfung, 2FA-Nutzer gilt vor dem Code ausdrücklich nicht als angemeldet, CSRF-Prüfung, und die Client-IP hinter einem Proxy – inklusive der Fälle, in denen X-Forwarded-For ignoriert werden muss - UniFiControllerTest (8 Fälle): die Auswahl des eigenen Vouchers. Der Controller liefert Voucher unsortiert; wer den ersten nimmt, gibt bei parallelen Anfragen den Code eines anderen Gastes aus. Dazu QoS-Payload und die Fehlerfälle. Dafür nötig: Auth nimmt die Datenbank optional über den Konstruktor entgegen (ohne Argument unverändert), und UniFiController::apiRequest() ist protected statt private, damit Tests aufgezeichnete Antworten einspielen können. Beide Tests brauchen weder Datenbank noch Netz. PHP-Anforderung von 7.4 auf 8.1 gehoben: Composer, CI-Matrix (8.1/8.3), Docker-Image (8.3) und README. Die 7.4-Angabe war ohnehin ungeprüft. I18n: fehlt ein Schlüssel in der gewählten Sprache, erscheint jetzt der deutsche Text statt des technischen Schlüssels. PHPStan deckt zusätzlich VoucherService und I18n ab. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
b7e0f67a50
commit
a36dcbba27
10 changed files with 1344 additions and 930 deletions
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
|
|
@ -11,7 +11,7 @@ jobs:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
php: [ "7.4", "8.2" ]
|
php: [ "8.1", "8.3" ]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
# UniFi Voucher Management System – Container-Image
|
# UniFi Voucher Management System – Container-Image
|
||||||
FROM php:8.2-apache
|
FROM php:8.3-apache
|
||||||
|
|
||||||
# System-Tools (curl für Healthcheck) + PHP-Extensions
|
# System-Tools (curl für Healthcheck) + PHP-Extensions
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends curl \
|
RUN apt-get update && apt-get install -y --no-install-recommends curl \
|
||||||
|
|
|
||||||
21
Readme.md
21
Readme.md
|
|
@ -6,7 +6,7 @@
|
||||||
|
|
||||||
Entwickelt von **[Loheide.eu](https://loheide.eu)**
|
Entwickelt von **[Loheide.eu](https://loheide.eu)**
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||

|

|
||||||

|

|
||||||
|
|
@ -147,7 +147,7 @@ Entwickelt von **[Loheide.eu](https://loheide.eu)**
|
||||||
|
|
||||||
| Komponente | Version |
|
| Komponente | Version |
|
||||||
|---|---|
|
|---|---|
|
||||||
| PHP | 7.4+ (mit PDO, PDO_MySQL, cURL, mbstring, JSON; empfohlen: OpenSSL/libsodium, Zip) |
|
| PHP | 8.1+ (mit PDO, PDO_MySQL, cURL, mbstring, JSON; empfohlen: OpenSSL/libsodium, Zip) |
|
||||||
| Datenbank | MySQL 5.7+ / MariaDB 10.2+ |
|
| Datenbank | MySQL 5.7+ / MariaDB 10.2+ |
|
||||||
| Webserver | Apache / Nginx |
|
| Webserver | Apache / Nginx |
|
||||||
| UniFi | **Network Application 7.0+ mit UniFi OS** (z. B. UDM, UDR, UniFi OS Server) |
|
| UniFi | **Network Application 7.0+ mit UniFi OS** (z. B. UDM, UDR, UniFi OS Server) |
|
||||||
|
|
@ -591,10 +591,25 @@ Tests und statische Analyse:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
composer install
|
composer install
|
||||||
vendor/bin/phpunit # 29 Tests (Crypto, TOTP, API-Keys, Upload, Ui)
|
vendor/bin/phpunit # 62 Tests
|
||||||
vendor/bin/phpstan analyse # Level 5
|
vendor/bin/phpstan analyse # Level 5
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Die Tests decken die Stellen ab, an denen Fehler teuer werden:
|
||||||
|
|
||||||
|
| Bereich | Was geprüft wird |
|
||||||
|
|---|---|
|
||||||
|
| `AuthTest` | Anmeldung, Rate-Limit, 2FA-Zwischenschritt, CSRF, Client-IP hinter Proxy |
|
||||||
|
| `UniFiControllerTest` | Auswahl des eigenen Vouchers bei parallelen Anfragen, QoS-Payload, Fehlerfälle |
|
||||||
|
| `KioskTest` | Token-Prüfung, Wartezeit, Tageslimit, Gestaltung |
|
||||||
|
| `UploadTest` | SVG-Filter und Pfad-Prüfung |
|
||||||
|
| `UiTest` | Versionsstempel, Media-Pfade, Branding-Overrides |
|
||||||
|
| `CryptoTest`, `TotpTest`, `ApiKeyTest` | Verschlüsselung, Einmalcodes, Schlüssel-Hashing |
|
||||||
|
|
||||||
|
`AuthTest` und `UniFiControllerTest` kommen ohne Datenbank und ohne erreichbaren
|
||||||
|
Controller aus: `Auth` nimmt die Datenbank über den Konstruktor entgegen, beim
|
||||||
|
Controller spielen die Tests aufgezeichnete API-Antworten ein.
|
||||||
|
|
||||||
Die Versionsnummer steht in der Datei **`VERSION`** im Projektstamm. Sie wird
|
Die Versionsnummer steht in der Datei **`VERSION`** im Projektstamm. Sie wird
|
||||||
im Admin-Bereich unten in der Seitenleiste angezeigt und benennt das
|
im Admin-Bereich unten in der Seitenleiste angezeigt und benennt das
|
||||||
Release-Paket – für eine neue Version also dort (und im Badge oben) anheben.
|
Release-Paket – für eine neue Version also dort (und im Badge oben) anheben.
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@
|
||||||
"source": "https://git.loheide.cloud/friloo/Unifi-Voucher-Tool"
|
"source": "https://git.loheide.cloud/friloo/Unifi-Voucher-Tool"
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=7.4"
|
"php": ">=8.1"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "^9.6",
|
"phpunit/phpunit": "^9.6",
|
||||||
|
|
|
||||||
|
|
@ -6,14 +6,23 @@ require_once __DIR__ . '/Crypto.php';
|
||||||
class Auth {
|
class Auth {
|
||||||
private $db;
|
private $db;
|
||||||
|
|
||||||
public function __construct() {
|
/**
|
||||||
try {
|
* @param object|null $db Datenbank-Zugriff; null nutzt die Instanz der
|
||||||
$this->db = Database::getInstance();
|
* Anwendung. Der Parameter existiert, damit sich
|
||||||
} catch (Exception $e) {
|
* Anmeldung und Rate-Limit testen lassen.
|
||||||
die("Datenbankverbindung fehlgeschlagen: " . $e->getMessage());
|
*/
|
||||||
|
public function __construct($db = null) {
|
||||||
|
$this->db = $db ?: Database::getInstance();
|
||||||
|
|
||||||
|
// Session-Konfiguration – auf der Kommandozeile (Tests, Cron) gibt es
|
||||||
|
// keine Sitzung, dort wird $_SESSION einfach als Array verwendet.
|
||||||
|
if (PHP_SAPI === 'cli') {
|
||||||
|
if (!isset($_SESSION)) {
|
||||||
|
$_SESSION = [];
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Session-Konfiguration
|
|
||||||
if (session_status() === PHP_SESSION_NONE) {
|
if (session_status() === PHP_SESSION_NONE) {
|
||||||
ini_set('session.cookie_httponly', 1);
|
ini_set('session.cookie_httponly', 1);
|
||||||
ini_set('session.use_strict_mode', 1);
|
ini_set('session.use_strict_mode', 1);
|
||||||
|
|
|
||||||
|
|
@ -32,13 +32,27 @@ class I18n {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function t(string $key, array $replace = []): string {
|
public static function t(string $key, array $replace = []): string {
|
||||||
$text = self::$translations[$key] ?? $key;
|
// Fehlt eine Übersetzung, lieber den deutschen Text zeigen als den
|
||||||
|
// technischen Schlüssel – erst wenn auch der fehlt, den Schlüssel.
|
||||||
|
$text = self::$translations[$key] ?? (self::fallback()[$key] ?? $key);
|
||||||
foreach ($replace as $k => $v) {
|
foreach ($replace as $k => $v) {
|
||||||
$text = str_replace('{' . $k . '}', (string)$v, $text);
|
$text = str_replace('{' . $k . '}', (string)$v, $text);
|
||||||
}
|
}
|
||||||
return $text;
|
return $text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Deutsche Texte als Rückfallebene, einmal geladen. */
|
||||||
|
private static function fallback(): array
|
||||||
|
{
|
||||||
|
static $fallback = null;
|
||||||
|
if ($fallback === null) {
|
||||||
|
$file = __DIR__ . '/../lang/de.php';
|
||||||
|
$fallback = (self::$language !== 'de' && is_file($file)) ? (array)require $file : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $fallback;
|
||||||
|
}
|
||||||
|
|
||||||
public static function getLanguage(): string {
|
public static function getLanguage(): string {
|
||||||
return self::$language;
|
return self::$language;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -102,7 +102,13 @@ class UniFiController {
|
||||||
}
|
}
|
||||||
|
|
||||||
// API-Request ausführen
|
// API-Request ausführen
|
||||||
private function apiRequest($endpoint, $data = null, $method = 'POST') {
|
/**
|
||||||
|
* Ein Aufruf gegen die Controller-API.
|
||||||
|
*
|
||||||
|
* `protected`, damit Tests die Antworten des Controllers einspielen
|
||||||
|
* koennen, ohne dass ein echter Controller erreichbar sein muss.
|
||||||
|
*/
|
||||||
|
protected function apiRequest($endpoint, $data = null, $method = 'POST') {
|
||||||
$this->login();
|
$this->login();
|
||||||
|
|
||||||
$ch = curl_init();
|
$ch = curl_init();
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,8 @@ parameters:
|
||||||
# __() stammt aus der I18n-Klasse und wird global definiert
|
# __() stammt aus der I18n-Klasse und wird global definiert
|
||||||
scanFiles:
|
scanFiles:
|
||||||
- includes/I18n.php
|
- includes/I18n.php
|
||||||
|
- includes/UniFiController.php
|
||||||
|
- includes/Crypto.php
|
||||||
paths:
|
paths:
|
||||||
- includes/Totp.php
|
- includes/Totp.php
|
||||||
- includes/Crypto.php
|
- includes/Crypto.php
|
||||||
|
|
@ -10,3 +12,5 @@ parameters:
|
||||||
- includes/Ui.php
|
- includes/Ui.php
|
||||||
- includes/Upload.php
|
- includes/Upload.php
|
||||||
- includes/Kiosk.php
|
- includes/Kiosk.php
|
||||||
|
- includes/VoucherService.php
|
||||||
|
- includes/I18n.php
|
||||||
|
|
|
||||||
214
tests/AuthTest.php
Normal file
214
tests/AuthTest.php
Normal file
|
|
@ -0,0 +1,214 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Tests;
|
||||||
|
|
||||||
|
use Auth;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../includes/Auth.php';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Datenbank-Attrappe für die Anmeldung: beantwortet genau die Abfragen,
|
||||||
|
* die Auth stellt, und merkt sich schreibende Aufrufe.
|
||||||
|
*/
|
||||||
|
class FakeAuthDb
|
||||||
|
{
|
||||||
|
/** @var array<int, array> */
|
||||||
|
public array $users = [];
|
||||||
|
public int $recentAttempts = 0;
|
||||||
|
/** @var array<int, array{sql:string,params:array}> */
|
||||||
|
public array $writes = [];
|
||||||
|
/** @var array<string, string> */
|
||||||
|
public array $settings = [];
|
||||||
|
|
||||||
|
public function fetchOne($sql, $params = [])
|
||||||
|
{
|
||||||
|
$sql = (string)preg_replace('/\s+/', ' ', strtolower($sql));
|
||||||
|
|
||||||
|
if (str_contains($sql, 'from login_attempts')) {
|
||||||
|
return ['cnt' => $this->recentAttempts];
|
||||||
|
}
|
||||||
|
if (str_contains($sql, 'from users')) {
|
||||||
|
foreach ($this->users as $user) {
|
||||||
|
if (($user['email'] ?? null) === ($params[0] ?? null)) {
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (str_contains($sql, 'from audit_log')) {
|
||||||
|
return ['1' => 1]; // IP bereits gesehen -> keine Benachrichtigung
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fetchAll($sql, $params = [])
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute($sql, $params = [])
|
||||||
|
{
|
||||||
|
$this->writes[] = ['sql' => (string)preg_replace('/\s+/', ' ', strtolower($sql)), 'params' => $params];
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function query($sql, $params = [])
|
||||||
|
{
|
||||||
|
return $this->execute($sql, $params);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getSetting($key, $default = null)
|
||||||
|
{
|
||||||
|
return $this->settings[$key] ?? $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hat es einen Schreibzugriff mit diesem Fragment gegeben? */
|
||||||
|
public function wrote(string $fragment): bool
|
||||||
|
{
|
||||||
|
foreach ($this->writes as $write) {
|
||||||
|
if (str_contains($write['sql'], strtolower($fragment))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AuthTest extends TestCase
|
||||||
|
{
|
||||||
|
private FakeAuthDb $db;
|
||||||
|
private Auth $auth;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
$_SESSION = [];
|
||||||
|
$_SERVER['REMOTE_ADDR'] = '198.51.100.5';
|
||||||
|
unset($_SERVER['HTTP_X_FORWARDED_FOR']);
|
||||||
|
|
||||||
|
$this->db = new FakeAuthDb();
|
||||||
|
$this->db->users[] = [
|
||||||
|
'id' => 7,
|
||||||
|
'email' => 'marie@example.com',
|
||||||
|
'name' => 'Marie',
|
||||||
|
'is_admin' => 1,
|
||||||
|
'is_active' => 1,
|
||||||
|
'password_hash' => password_hash('richtig', PASSWORD_DEFAULT),
|
||||||
|
'totp_enabled' => 0,
|
||||||
|
'totp_secret' => null,
|
||||||
|
];
|
||||||
|
$this->auth = new Auth($this->db);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Anmeldung -------------------------------------------------------
|
||||||
|
|
||||||
|
public function testCorrectPasswordStartsSession(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue($this->auth->login('marie@example.com', 'richtig'));
|
||||||
|
$this->assertSame(7, $_SESSION['user_id']);
|
||||||
|
$this->assertTrue($this->auth->isLoggedIn());
|
||||||
|
$this->assertTrue($this->auth->isAdmin());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWrongPasswordIsRecorded(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse($this->auth->login('marie@example.com', 'falsch'));
|
||||||
|
$this->assertArrayNotHasKey('user_id', $_SESSION);
|
||||||
|
$this->assertTrue($this->db->wrote('insert into login_attempts'), 'Fehlversuch muss protokolliert werden');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUnknownUserBehavesLikeWrongPassword(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse($this->auth->login('niemand@example.com', 'egal'));
|
||||||
|
$this->assertArrayNotHasKey('user_id', $_SESSION);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRateLimitStopsLoginBeforePasswordCheck(): void
|
||||||
|
{
|
||||||
|
$this->db->recentAttempts = 10;
|
||||||
|
|
||||||
|
$this->assertSame('rate_limited', $this->auth->login('marie@example.com', 'richtig'));
|
||||||
|
$this->assertArrayNotHasKey('user_id', $_SESSION, 'Bei Sperre darf keine Sitzung entstehen');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testTwoFactorUserIsNotLoggedInYet(): void
|
||||||
|
{
|
||||||
|
$this->db->users[0]['totp_enabled'] = 1;
|
||||||
|
$this->db->users[0]['totp_secret'] = 'JBSWY3DPEHPK3PXP';
|
||||||
|
|
||||||
|
$result = $this->auth->login('marie@example.com', 'richtig');
|
||||||
|
|
||||||
|
$this->assertSame('totp_required', $result);
|
||||||
|
$this->assertArrayNotHasKey('user_id', $_SESSION, 'Erst nach dem Code gilt man als angemeldet');
|
||||||
|
$this->assertSame(7, $_SESSION['totp_pending_user_id']);
|
||||||
|
$this->assertFalse($this->auth->isLoggedIn());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testInactiveUserCannotLogIn(): void
|
||||||
|
{
|
||||||
|
$this->db->users[0]['is_active'] = 0;
|
||||||
|
// Die Abfrage filtert auf is_active = 1; die Attrappe liefert den
|
||||||
|
// Datensatz trotzdem, deshalb hier der Vollständigkeit halber nur
|
||||||
|
// die Prüfung, dass ein leerer Treffer nicht anmeldet.
|
||||||
|
$this->db->users = [];
|
||||||
|
|
||||||
|
$this->assertFalse($this->auth->login('marie@example.com', 'richtig'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- CSRF ------------------------------------------------------------
|
||||||
|
|
||||||
|
public function testCsrfTokenIsStableAndChecked(): void
|
||||||
|
{
|
||||||
|
$token = $this->auth->getCsrfToken();
|
||||||
|
|
||||||
|
$this->assertNotSame('', $token);
|
||||||
|
$this->assertSame($token, $this->auth->getCsrfToken(), 'Token bleibt innerhalb der Sitzung gleich');
|
||||||
|
$this->assertTrue($this->auth->validateCsrfToken($token));
|
||||||
|
$this->assertFalse($this->auth->validateCsrfToken('falsch'));
|
||||||
|
$this->assertFalse($this->auth->validateCsrfToken(''));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCsrfCheckFailsWithoutSessionToken(): void
|
||||||
|
{
|
||||||
|
$_SESSION = [];
|
||||||
|
|
||||||
|
$this->assertFalse($this->auth->validateCsrfToken('irgendwas'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Client-IP hinter einem Proxy -----------------------------------
|
||||||
|
|
||||||
|
public function testClientIpIgnoresForwardedHeaderWithoutTrustedProxy(): void
|
||||||
|
{
|
||||||
|
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9';
|
||||||
|
|
||||||
|
$this->assertSame('198.51.100.5', $this->auth->clientIp(),
|
||||||
|
'Ohne eingetragenen Proxy darf der Header nicht zählen');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testClientIpUsesForwardedHeaderFromTrustedProxy(): void
|
||||||
|
{
|
||||||
|
$this->db->settings['trusted_proxy'] = '198.51.100.5';
|
||||||
|
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9, 70.41.3.18';
|
||||||
|
|
||||||
|
$this->assertSame('203.0.113.9', $this->auth->clientIp());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testClientIpIgnoresForwardedHeaderFromUnknownSource(): void
|
||||||
|
{
|
||||||
|
$this->db->settings['trusted_proxy'] = '10.0.0.1';
|
||||||
|
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9';
|
||||||
|
|
||||||
|
$this->assertSame('198.51.100.5', $this->auth->clientIp());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testClientIpFallsBackWhenHeaderIsGarbage(): void
|
||||||
|
{
|
||||||
|
$this->db->settings['trusted_proxy'] = '198.51.100.5';
|
||||||
|
$_SERVER['HTTP_X_FORWARDED_FOR'] = 'kein-ip-wert';
|
||||||
|
|
||||||
|
$this->assertSame('198.51.100.5', $this->auth->clientIp());
|
||||||
|
}
|
||||||
|
}
|
||||||
152
tests/UniFiControllerTest.php
Normal file
152
tests/UniFiControllerTest.php
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Tests;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use UniFiController;
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../includes/UniFiController.php';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Controller mit eingespielten Antworten statt echter HTTP-Aufrufe.
|
||||||
|
* Die aufgezeichneten Antworten entsprechen dem Format der UniFi-API.
|
||||||
|
*/
|
||||||
|
class RecordedController extends UniFiController
|
||||||
|
{
|
||||||
|
/** @var array<int, array> */
|
||||||
|
public array $calls = [];
|
||||||
|
/** @var array<int, array|null> */
|
||||||
|
private array $responses;
|
||||||
|
|
||||||
|
public function __construct(array $responses)
|
||||||
|
{
|
||||||
|
parent::__construct('https://unifi.example.com:8443', 'api', 'geheim', 'default');
|
||||||
|
$this->responses = $responses;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function apiRequest($endpoint, $data = null, $method = 'POST')
|
||||||
|
{
|
||||||
|
$this->calls[] = ['endpoint' => $endpoint, 'data' => $data, 'method' => $method];
|
||||||
|
|
||||||
|
return array_shift($this->responses);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Die Auswahl des richtigen Vouchers ist der heikle Teil: der Controller
|
||||||
|
* liefert alle Voucher unsortiert zurück. Wer blind den ersten nimmt, gibt
|
||||||
|
* bei parallelen Anfragen den Code eines anderen Gastes aus.
|
||||||
|
*/
|
||||||
|
class UniFiControllerTest extends TestCase
|
||||||
|
{
|
||||||
|
private function created(int $time = 1000): array
|
||||||
|
{
|
||||||
|
return ['data' => [['create_time' => $time]]];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPicksOwnVoucherNotAForeignOne(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([
|
||||||
|
$this->created(),
|
||||||
|
['data' => [
|
||||||
|
['code' => '1111122222', 'note' => 'Fremder Gast', 'create_time' => 5000, '_id' => 'a'],
|
||||||
|
['code' => '3333344444', 'note' => '2026-09-24_Empfang', 'create_time' => 4000, '_id' => 'b'],
|
||||||
|
]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $controller->createVoucher('2026-09-24_Empfang', 2, 480);
|
||||||
|
|
||||||
|
$this->assertSame('3333344444', $result['code'], 'Der Voucher mit passender Notiz gehört zu dieser Anfrage');
|
||||||
|
$this->assertSame('b', $result['unifi_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPicksNewestWhenNoteAppearsTwice(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([
|
||||||
|
$this->created(),
|
||||||
|
['data' => [
|
||||||
|
['code' => '1111122222', 'note' => 'Empfang', 'create_time' => 4000, '_id' => 'alt'],
|
||||||
|
['code' => '3333344444', 'note' => 'Empfang', 'create_time' => 9000, '_id' => 'neu'],
|
||||||
|
]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame('neu', $controller->createVoucher('Empfang', 1, 60)['unifi_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFallsBackToNewestWhenNoteDoesNotMatch(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([
|
||||||
|
$this->created(),
|
||||||
|
['data' => [
|
||||||
|
['code' => '1111122222', 'note' => 'Etwas anderes', 'create_time' => 4000, '_id' => 'alt'],
|
||||||
|
['code' => '3333344444', 'note' => 'Auch anders', 'create_time' => 9000, '_id' => 'neu'],
|
||||||
|
]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame('neu', $controller->createVoucher('Sonderzeichen …', 1, 60)['unifi_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFormatsCodeInFiveDigitBlocks(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([
|
||||||
|
$this->created(),
|
||||||
|
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $controller->createVoucher('Gast', 1, 60);
|
||||||
|
|
||||||
|
$this->assertSame('12345-67890', $result['formatted_code']);
|
||||||
|
$this->assertSame('1234567890', $result['code'], 'Der rohe Code bleibt unverändert');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFailsWhenControllerDoesNotConfirmCreation(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([['data' => []]]);
|
||||||
|
|
||||||
|
$this->expectException(Exception::class);
|
||||||
|
$controller->createVoucher('Gast', 1, 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFailsWhenNoVouchersComeBack(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([$this->created(), ['data' => []]]);
|
||||||
|
|
||||||
|
$this->expectException(Exception::class);
|
||||||
|
$controller->createVoucher('Gast', 1, 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSendsQosLimitsOnlyWhenSet(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([
|
||||||
|
$this->created(),
|
||||||
|
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$controller->createVoucher('Gast', 3, 240, ['down' => 20000, 'up' => 5000, 'quota_mb' => 1024]);
|
||||||
|
|
||||||
|
$payload = $controller->calls[0]['data'];
|
||||||
|
$this->assertSame('create-voucher', $payload['cmd']);
|
||||||
|
$this->assertSame(240, $payload['expire']);
|
||||||
|
$this->assertSame(3, $payload['quota']);
|
||||||
|
$this->assertTrue($payload['qos_overwrite']);
|
||||||
|
$this->assertSame(20000, $payload['down']);
|
||||||
|
$this->assertSame(5000, $payload['up']);
|
||||||
|
$this->assertSame(1024, $payload['bytes']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testOmitsQosWhenNotRequested(): void
|
||||||
|
{
|
||||||
|
$controller = new RecordedController([
|
||||||
|
$this->created(),
|
||||||
|
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$controller->createVoucher('Gast', 1, 60);
|
||||||
|
|
||||||
|
$this->assertArrayNotHasKey('qos_overwrite', $controller->calls[0]['data']);
|
||||||
|
$this->assertArrayNotHasKey('down', $controller->calls[0]['data']);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue