https://github.com/chqthomas/approval-tests-php
A PHP assertion library for approval testing with PHPUnit
https://github.com/chqthomas/approval-tests-php
approval-testing assertion-library phpunit snapshot-testing
Last synced: 3 months ago
JSON representation
A PHP assertion library for approval testing with PHPUnit
- Host: GitHub
- URL: https://github.com/chqthomas/approval-tests-php
- Owner: ChqThomas
- Created: 2025-02-15T17:54:22.000Z (3 months ago)
- Default Branch: main
- Last Pushed: 2025-02-16T15:33:39.000Z (3 months ago)
- Last Synced: 2025-02-16T16:41:15.567Z (3 months ago)
- Topics: approval-testing, assertion-library, phpunit, snapshot-testing
- Language: PHP
- Homepage:
- Size: 60.5 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# PHP Approval Tests
A PHP library for approval testing. This approach allows you to verify complex results by comparing them with approved versions.
> [!WARNING]
> This library is still in development. It is not recommended for production use. A lot of features are still missing, and the API may change.## Installation
```bash
composer require chqthomas/approval-tests
```## Basic Usage
### Simple Test
```php
use ApprovalTests\Approvals;public function testSimpleString(): void
{
Approvals::verify("Hello World");
}
```### Structured Data Test
```php
public function testArray(): void
{
$data = [
'name' => 'John Doe',
'age' => 30,
'roles' => ['admin', 'user']
];
Approvals::verify($data);
}
```## Specialized Verifications
### HTML
```php
public function testHtml(): void
{
$html = 'Hello World';
Approvals::verifyHtml($html);
}
```### JSON
```php
public function testJson(): void
{
$json = '{"name":"John","age":30}';
Approvals::verifyJson($json); // Automatically formatted
}
```### XML
```php
public function testXml(): void
{
$xml = 'John';
Approvals::verifyXml($xml);
}
```### CSV
```php
public function testCsv(): void
{
$csv = "name,age\nJohn,30\nJane,25";
Approvals::verifyCsv($csv);
}
```### Binary Files
```php
public function testBinaryFile(): void
{
Approvals::verifyBinaryFile('path/to/image.png', 'png');
}
```## Advanced Features
### Tests with Data Providers
```php
/**
* @dataProvider provideTestData
*/
public function testWithDataProvider(array $data, string $expected): void
{
$result = processData($data);
Approvals::verify($result);
}
```### Verify All Combinations
```php
public function testAllCombinations(): void
{
$operations = ['+', '-', '*', '/'];
$numbers = [1, 2, 3];
Approvals::verifyAllCombinations(
function($op, $a, $b) {
switch($op) {
case '+': return $a + $b;
case '-': return $a - $b;
case '*': return $a * $b;
case '/': return $b != 0 ? $a / $b : 'Division by zero';
}
},
[$operations, $numbers, $numbers]
);
}
```### Environment-Specific Tests
```php
public function testEnvironmentSpecific(): void
{
Approvals::verifyWithEnvironment(
"Windows-specific content",
"Windows_10_Pro"
);
}
```## Scrubbers
Scrubbers allow you to normalize content before comparison.
### JSON Scrubbing
```php
public function testJsonScrubbing(): void
{
$json = <<ignoreMember('sensitive')); // Member will be removed
}
```#### Scrub JSON Members
```php
public function testJsonScrubMember(): void
{
$json = <<scrubMember('password', 'api_key')); // Members will be replaced with "[scrubbed]"
}
```### XML Scrubbing
```php
public function testXmlScrubbing(): void
{
$xml = <<John
2024-01-01T12:00:00
550e8400-e29b-41d4-a716-446655440000XML;
// Custom scrubber for XML
Approvals::verifyXml($xml, XmlScrubber::create()
->addScrubber(fn($content) => preg_replace('/John/', '[NAME]', $content)));
}
```## Regex Scrubbing
`RegexScrubber` allows you to normalize content using regular expressions before comparison. This is particularly useful for replacing values that may change, such as identifiers or names.
### Example of Regex Scrubbing
```php
public function testRegexScrubbing(): void
{
$json = <<addScrubber(RegexScrubber::create(['/"id": "([A-Z]{3}\d{3})"/' => '"id": "MATCHED"'])));
}
```### Example of Multiple Regex Scrubbing
```php
public function testMultipleRegexScrubbing(): void
{
$json = <<addScrubber(RegexScrubber::create([
'/user\d{3}/' => 'userXXX',
'/[A-Z][a-z]+ [A-Z][a-z]+/' => 'PERSON_NAME'
])));
}
```### Generic Custom Scrubber
For any type of content, you can create a custom scrubber:
```php
class MyScrubber extends AbstractScrubber
{
public function scrub(string $content): string
{
// Apply base scrubbers first (GUIDs, dates)
$content = $this->scrubGuids($content);
$content = $this->scrubDates($content);
// Add your custom rules
$content = preg_replace('/secret-\d+/', '[SECRET]', $content);
// Apply additional scrubbers
return $this->applyAdditionalScrubbers($content);
}
}// Usage
public function testWithCustomScrubber(): void
{
$content = "ID: secret-123\nDate: 2024-01-01";
Approvals::verifyWithExtension(
$content,
"txt",
MyScrubber::create()
->addScrubber(fn($text) => str_replace('ID:', 'Reference:', $text))
);
}
```### Auto-accepting Snapshots
To automatically accept new snapshots or changes:
```bash
APPROVE_SNAPSHOTS=true vendor/bin/phpunit
```## Maintenance
### Cleanup Received Files
```php
use ApprovalTests\ApprovalMaintenance;// Delete .received files that match .approved files
ApprovalMaintenance::cleanUpReceivedFiles(__DIR__ . '/tests/approvals');
```### Detect Orphaned Files
```php
// Find .approved files without associated tests
$orphanedFiles = ApprovalMaintenance::findOrphanedApprovedFiles(__DIR__ . '/tests');
```## Reporters
Reporters define how differences are reported.
### CLI Reporter
```php
use ApprovalTests\Reporter\CliReporter;// Default configuration
Configuration::getInstance()->setReporter(new CliReporter());
```### Diff Reporter
```php
use ApprovalTests\Reporter\DiffReporter;// Show differences using diff
Configuration::getInstance()->setReporter(new DiffReporter());
```### Composite Reporter
```php
use ApprovalTests\Reporter\CompositeReporter;// Combine multiple reporters
$reporter = new CompositeReporter([
new CliReporter(),
new DiffReporter()
]);
Configuration::getInstance()->setReporter($reporter);
```## Best Practices
1. Store approved files in version control
2. Use scrubbers for variable data (dates, IDs, etc.)
3. Regularly clean up received files
4. Check for orphaned approved files
5. Use descriptive test names## Contributing
Contributions are welcome! Feel free to:
1. Fork the project
2. Create a feature branch
3. Submit a pull request## License
MIT License