Files
monolog-gdpr-filter/tests/JsonMaskerEnhancedTest.php
Ismo Vuorinen 00c6f76c97 feat: performance, integrations, advanced features (#2)
* feat: performance, integrations, advanced features

* chore: fix linting problems

* chore: suppressions and linting

* chore(lint): pre-commit linting, fixes

* feat: comprehensive input validation, security hardening, and regression testing

- Add extensive input validation throughout codebase with proper error handling
- Implement comprehensive security hardening with ReDoS protection and bounds checking
- Add 3 new regression test suites covering critical bugs, security, and validation scenarios
- Enhance rate limiting with memory management and configurable cleanup intervals
- Update configuration security settings and improve Laravel integration
- Fix TODO.md timestamps to reflect actual development timeline
- Strengthen static analysis configuration and improve code quality standards

* feat: configure static analysis tools and enhance development workflow

- Complete configuration of Psalm, PHPStan, and Rector for harmonious static analysis.
- Fix invalid configurations and tool conflicts that prevented proper code quality analysis.
- Add comprehensive safe analysis script with interactive workflow, backup/restore
  capabilities, and dry-run modes. Update documentation with linting policy
  requiring issue resolution over suppression.
- Clean completed items from TODO to focus on actionable improvements.
- All static analysis tools now work together seamlessly to provide
  code quality insights without breaking existing functionality.

* fix(test): update Invalid regex pattern expectation

* chore: phpstan, psalm fixes

* chore: phpstan, psalm fixes, more tests

* chore: tooling tweaks, cleanup

* chore: tweaks to get the tests pass

* fix(lint): rector config tweaks and successful run

* feat: refactoring, more tests, fixes, cleanup

* chore: deduplication, use constants

* chore: psalm fixes

* chore: ignore phpstan deliberate errors in tests

* chore: improve codebase, deduplicate code

* fix: lint

* chore: deduplication, codebase simplification, sonarqube fixes

* fix: resolve SonarQube reliability rating issues

Fix useless object instantiation warnings in test files by assigning
instantiated objects to variables. This resolves the SonarQube reliability
rating issue (was C, now targeting A).

Changes:
- tests/Strategies/MaskingStrategiesTest.php: Fix 3 instances
- tests/Strategies/FieldPathMaskingStrategyTest.php: Fix 1 instance

The tests use expectException() to verify that constructors throw
exceptions for invalid input. SonarQube flagged standalone `new`
statements as useless. Fixed by assigning to variables with explicit
unset() and fail() calls.

All tests pass (623/623) and static analysis tools pass.

* fix: resolve more SonarQube detected issues

* fix: resolve psalm detected issues

* fix: resolve more SonarQube detected issues

* fix: resolve psalm detected issues

* fix: duplications

* fix: resolve SonarQube reliability rating issues

* fix: resolve psalm and phpstan detected issues
2025-10-31 13:59:01 +02:00

210 lines
6.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests;
use Tests\TestConstants;
use Ivuorinen\MonologGdprFilter\JsonMasker;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
#[CoversClass(JsonMasker::class)]
final class JsonMaskerEnhancedTest extends TestCase
{
public function testEncodePreservingEmptyObjectsWithEmptyString(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$result = $masker->encodePreservingEmptyObjects('', '{}');
$this->assertSame('{}', $result);
}
public function testEncodePreservingEmptyObjectsWithZeroString(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$result = $masker->encodePreservingEmptyObjects('0', '{}');
$this->assertSame('{}', $result);
}
public function testEncodePreservingEmptyObjectsWithEmptyArray(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$result = $masker->encodePreservingEmptyObjects([], '[]');
$this->assertSame('[]', $result);
}
public function testEncodePreservingEmptyObjectsWithEmptyArrayButObjectOriginal(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$result = $masker->encodePreservingEmptyObjects([], '{}');
$this->assertSame('{}', $result);
}
public function testEncodePreservingEmptyObjectsReturnsFalseOnEncodingFailure(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
// Create a resource which cannot be JSON encoded
$resource = fopen('php://memory', 'r');
$this->assertIsResource($resource);
$result = $masker->encodePreservingEmptyObjects(['resource' => $resource], '{}');
fclose($resource);
$this->assertFalse($result);
}
public function testProcessCandidateWithNullDecoded(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
// JSON string "null" decodes to null
$result = $masker->processCandidate('null');
// Should return original since decoded is null
$this->assertSame('null', $result);
}
public function testProcessCandidateWithInvalidJson(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$result = $masker->processCandidate('{invalid json}');
$this->assertSame('{invalid json}', $result);
}
public function testProcessCandidateWithAuditLoggerWhenUnchanged(): void
{
$auditLog = [];
$auditLogger = function (string $path, mixed $original, mixed $masked) use (&$auditLog): void {
$auditLog[] = ['path' => $path, 'original' => $original, TestConstants::DATA_MASKED => $masked];
};
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback, $auditLogger);
$json = TestConstants::JSON_KEY_VALUE;
$masker->processCandidate($json);
// Should not log when unchanged
$this->assertCount(0, $auditLog);
}
public function testProcessCandidateWithEncodingFailure(): void
{
$recursiveCallback = function (array|string $val): array|string {
// Return something that can't be re-encoded
if (is_array($val)) {
$resource = fopen('php://memory', 'r');
return ['resource' => $resource];
}
return $val;
};
$masker = new JsonMasker($recursiveCallback);
$json = TestConstants::JSON_KEY_VALUE;
$result = $masker->processCandidate($json);
// Should return original when encoding fails
$this->assertSame($json, $result);
}
public function testFixEmptyObjectsWithNoEmptyObjects(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$encoded = TestConstants::JSON_KEY_VALUE;
$original = TestConstants::JSON_KEY_VALUE;
$result = $masker->fixEmptyObjects($encoded, $original);
$this->assertSame($encoded, $result);
}
public function testFixEmptyObjectsReplacesEmptyArrays(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$encoded = '{"a":[],"b":[]}';
$original = '{"a":{},"b":{}}';
$result = $masker->fixEmptyObjects($encoded, $original);
$this->assertSame('{"a":{},"b":{}}', $result);
}
public function testExtractBalancedStructureWithUnbalancedJson(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$message = '{"unclosed":';
$result = $masker->extractBalancedStructure($message, 0);
$this->assertNull($result);
}
public function testExtractBalancedStructureWithEscapedQuotes(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$message = '{"key":"value with \\" quote"}';
$result = $masker->extractBalancedStructure($message, 0);
$this->assertSame('{"key":"value with \\" quote"}', $result);
}
public function testExtractBalancedStructureWithNestedArrays(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$message = '[[1,2,[3,4]]]';
$result = $masker->extractBalancedStructure($message, 0);
$this->assertSame('[[1,2,[3,4]]]', $result);
}
public function testProcessMessageWithNoJson(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$message = 'Plain text message';
$result = $masker->processMessage($message);
$this->assertSame($message, $result);
}
public function testProcessMessageWithInvalidJsonLike(): void
{
$recursiveCallback = fn($val) => $val;
$masker = new JsonMasker($recursiveCallback);
$message = 'Text {not json} more text';
$result = $masker->processMessage($message);
$this->assertSame($message, $result);
}
}