Valinor/tests/Unit/Mapper/Source/FileSourceTest.php

85 lines
2.5 KiB
PHP
Raw Normal View History

2021-11-28 17:43:02 +01:00
<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Unit\Mapper\Source;
use CuyZ\Valinor\Mapper\Source\Exception\FileExtensionNotHandled;
use CuyZ\Valinor\Mapper\Source\Exception\UnableToReadFile;
2021-11-28 17:43:02 +01:00
use CuyZ\Valinor\Mapper\Source\FileSource;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
2021-11-28 17:43:02 +01:00
use PHPUnit\Framework\TestCase;
use SplFileObject;
use function function_exists;
use function iterator_to_array;
final class FileSourceTest extends TestCase
{
private vfsStreamDirectory $files;
protected function setUp(): void
{
parent::setUp();
$this->files = vfsStream::setup();
}
2021-11-28 17:43:02 +01:00
/**
* @dataProvider file_is_handled_properly_data_provider
*/
public function test_file_is_handled_properly(string $filename, string $content): void
2021-11-28 17:43:02 +01:00
{
$file = (vfsStream::newFile($filename))->withContent($content)->at($this->files);
$source = new FileSource(new SplFileObject($file->url()));
2021-11-28 17:43:02 +01:00
self::assertSame(['foo' => 'bar'], iterator_to_array($source));
self::assertSame($file->url(), $source->sourceName());
2021-11-28 17:43:02 +01:00
}
public function file_is_handled_properly_data_provider(): iterable
{
yield ['test-json.json', '{"foo": "bar"}'];
yield ['test-json.JSON', '{"foo": "bar"}'];
2021-11-28 17:43:02 +01:00
if (function_exists('yaml_parse')) {
yield ['test-yaml.yaml', 'foo: bar'];
yield ['test-yaml.YAML', 'foo: bar'];
yield ['test-yml.yml', 'foo: bar'];
yield ['test-yml.YML', 'foo: bar'];
2021-11-28 17:43:02 +01:00
}
}
public function test_unhandled_extension_throws_exception(): void
{
$this->expectException(FileExtensionNotHandled::class);
$this->expectExceptionCode(1629991744);
$this->expectExceptionMessage('The file extension `foo` is not handled.');
$file = (vfsStream::newFile('some-unhandled-extension.foo'))
->withContent('foo')
->at($this->files);
2021-11-28 17:43:02 +01:00
new FileSource(new SplFileObject($file->url()));
2021-11-28 17:43:02 +01:00
}
public function test_unreadable_file_throws_exception(): void
2021-11-28 17:43:02 +01:00
{
$file = (vfsStream::newFile('some-file.json'))
->withContent('{"foo": "bar"}')
->at($this->files);
$fileObject = new SplFileObject($file->url());
$file->chmod(0000);
$this->expectException(UnableToReadFile::class);
$this->expectExceptionCode(1629993117);
$this->expectExceptionMessage("Unable to read the file `{$file->url()}`.");
2021-11-28 17:43:02 +01:00
new FileSource($fileObject);
2021-11-28 17:43:02 +01:00
}
}