Skip to content

Commit

Permalink
[UPDATE] Better tests (#52)
Browse files Browse the repository at this point in the history
* Fix risky tests
* Add tests
* Fix issues with parsing int / float
* Add unit of enum PaperSize to tests
  • Loading branch information
Neirda24 committed May 31, 2024
1 parent b3e6d6c commit 1e4348d
Show file tree
Hide file tree
Showing 19 changed files with 543 additions and 391 deletions.
4 changes: 0 additions & 4 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ parameters:
- 'src'
- 'tests'
ignoreErrors:
-
message: "#^Cannot use array destructuring on array\\<int, string\\|null\\>\\|null\\.$#"
count: 1
path: src/DataCollector/GotenbergDataCollector.php
-
message: "#^Method Sensiolabs\\\\GotenbergBundle\\\\Tests\\\\Kernel\\:\\:configureContainer\\(\\) is unused\\.$#"
count: 1
Expand Down
26 changes: 10 additions & 16 deletions src/Builder/Pdf/AbstractChromiumPdfBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Sensiolabs\GotenbergBundle\Builder\Pdf;

use Sensiolabs\GotenbergBundle\Client\GotenbergClientInterface;
use Sensiolabs\GotenbergBundle\Enum\PaperSize;
use Sensiolabs\GotenbergBundle\Enum\EmulatedMediaType;
use Sensiolabs\GotenbergBundle\Enum\PaperSizeInterface;
use Sensiolabs\GotenbergBundle\Enum\Part;
use Sensiolabs\GotenbergBundle\Enum\PdfFormat;
Expand Down Expand Up @@ -315,9 +315,9 @@ public function waitForExpression(string $expression): static
*
* @see https://gotenberg.dev/docs/routes#console-exceptions
*/
public function emulatedMediaType(string $mediaType): static
public function emulatedMediaType(EmulatedMediaType $mediaType): static
{
$this->formFields['emulatedMediaType'] = $mediaType;
$this->formFields['emulatedMediaType'] = $mediaType->value;

return $this;
}
Expand Down Expand Up @@ -525,22 +525,16 @@ protected function withRenderedPart(Part $pdfPart, string $template, array $cont

private function addConfiguration(string $configurationName, mixed $value): void
{
$splitAndParseStringWithUnit = static function (mixed $raw, callable $callback): void {
[$value, $unit] = sscanf((string) $raw, '%d%s') ?? throw new \InvalidArgumentException(sprintf('Unexpected value "%s", expected format is "%%d%%s"', $raw));

$callback((float) $value, Unit::tryFrom((string) $unit) ?? Unit::Inches);
};

match ($configurationName) {
'single_page' => $this->singlePage($value),
'pdf_format' => $this->pdfFormat(PdfFormat::from($value)),
'pdf_universal_access' => $this->pdfUniversalAccess($value),
'paper_width' => $this->paperWidth($value),
'paper_height' => $this->paperHeight($value),
'margin_top' => $splitAndParseStringWithUnit($value, $this->marginTop(...)),
'margin_bottom' => $splitAndParseStringWithUnit($value, $this->marginBottom(...)),
'margin_left' => $splitAndParseStringWithUnit($value, $this->marginLeft(...)),
'margin_right' => $splitAndParseStringWithUnit($value, $this->marginRight(...)),
'paper_width' => $this->paperWidth(...Unit::parse($value)),
'paper_height' => $this->paperHeight(...Unit::parse($value)),
'margin_top' => $this->marginTop(...Unit::parse($value)),
'margin_bottom' => $this->marginBottom(...Unit::parse($value)),
'margin_left' => $this->marginLeft(...Unit::parse($value)),
'margin_right' => $this->marginRight(...Unit::parse($value)),
'prefer_css_page_size' => $this->preferCssPageSize($value),
'print_background' => $this->printBackground($value),
'omit_background' => $this->omitBackground($value),
Expand All @@ -549,7 +543,7 @@ private function addConfiguration(string $configurationName, mixed $value): void
'native_page_ranges' => $this->nativePageRanges($value),
'wait_delay' => $this->waitDelay($value),
'wait_for_expression' => $this->waitForExpression($value),
'emulated_media_type' => $this->emulatedMediaType($value),
'emulated_media_type' => $this->emulatedMediaType(EmulatedMediaType::from($value)),
'cookies' => $this->cookies($value),
'extra_http_headers' => $this->extraHttpHeaders($value),
'fail_on_http_status_codes' => $this->failOnHttpStatusCodes($value),
Expand Down
14 changes: 12 additions & 2 deletions src/Builder/Pdf/AbstractPdfBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function __construct(
return $this->encodeData('failOnHttpStatusCodes', $value);
},
'cookies' => function (mixed $value): array {
return $this->encodeData('cookies', \array_values($value));
return $this->encodeData('cookies', array_values($value));
},
'metadata' => function (mixed $value): array {
return $this->encodeData('metadata', $value);
Expand Down Expand Up @@ -164,12 +164,22 @@ private function addToMultipart(string $key, array|string|int|float|bool|DataPar
]];
}

if (\is_int($value) || \is_float($value)) {
if (\is_int($value)) {
return [[
$key => (string) $value,
]];
}

if (\is_float($value)) {
[$left, $right] = sscanf((string) $value, '%d.%s') ?? [$value, ''];

$right ??= '0';

return [[
$key => "{$left}.{$right}",
]];
}

if (\is_array($value)) {
$result = [];
foreach ($value as $nestedValue) {
Expand Down
12 changes: 11 additions & 1 deletion src/Builder/Screenshot/AbstractScreenshotBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,22 @@ private function addToMultipart(string $key, array|string|int|float|bool|DataPar
]];
}

if (\is_int($value) || \is_float($value)) {
if (\is_int($value)) {
return [[
$key => (string) $value,
]];
}

if (\is_float($value)) {
[$left, $right] = sscanf((string) $value, '%d.%s') ?? [$value, ''];

$right ??= '0';

return [[
$key => "{$left}.{$right}",
]];
}

if (\is_array($value)) {
$result = [];
foreach ($value as $nestedValue) {
Expand Down
11 changes: 5 additions & 6 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use function array_map;

class Configuration implements ConfigurationInterface
{
Expand Down Expand Up @@ -205,7 +204,7 @@ private function addChromiumPdfOptionsNode(NodeBuilder $treeBuilder): void
->end()
->enumNode('emulated_media_type')
->info('The media type to emulate, either "screen" or "print" - default "print". https://gotenberg.dev/docs/routes#emulated-media-type')
->values(array_map(static fn(EmulatedMediaType $case): string => $case->value, EmulatedMediaType::cases()))
->values(\array_map(static fn (EmulatedMediaType $case): string => $case->value, EmulatedMediaType::cases()))
->defaultNull()
->end()
->arrayNode('cookies')
Expand Down Expand Up @@ -274,7 +273,7 @@ private function addChromiumPdfOptionsNode(NodeBuilder $treeBuilder): void
->end()
->enumNode('pdf_format')
->info('Convert the resulting PDF into the given PDF/A format - default None. https://gotenberg.dev/docs/routes#pdfa-chromium')
->values(array_map(static fn(PdfFormat $case): string => $case->value, PdfFormat::cases()))
->values(\array_map(static fn (PdfFormat $case): string => $case->value, PdfFormat::cases()))
->defaultNull()
->end()
->booleanNode('pdf_universal_access')
Expand Down Expand Up @@ -302,7 +301,7 @@ private function addChromiumScreenshotOptionsNode(NodeBuilder $treeBuilder): voi
->end()
->enumNode('format')
->info('The image compression format, either "png", "jpeg" or "webp" - default png. https://gotenberg.dev/docs/routes#screenshots-route')
->values(array_map(static fn(ScreenshotFormat $case): string => $case->value, ScreenshotFormat::cases()))
->values(\array_map(static fn (ScreenshotFormat $case): string => $case->value, ScreenshotFormat::cases()))
->defaultNull()
->end()
->integerNode('quality')
Expand Down Expand Up @@ -341,7 +340,7 @@ private function addChromiumScreenshotOptionsNode(NodeBuilder $treeBuilder): voi
->end()
->enumNode('emulated_media_type')
->info('The media type to emulate, either "screen" or "print" - default "print". https://gotenberg.dev/docs/routes#emulated-media-type')
->values(array_map(static fn(EmulatedMediaType $case): string => $case->value, EmulatedMediaType::cases()))
->values(\array_map(static fn (EmulatedMediaType $case): string => $case->value, EmulatedMediaType::cases()))
->defaultNull()
->end()
->arrayNode('cookies')
Expand Down Expand Up @@ -438,7 +437,7 @@ private function addPdfOfficeNode(): NodeDefinition
->end()
->enumNode('pdf_format')
->info('Convert the resulting PDF into the given PDF/A format - default None. https://gotenberg.dev/docs/routes#pdfa-chromium')
->values(array_map(static fn(PdfFormat $case): string => $case->value, PdfFormat::cases()))
->values(\array_map(static fn (PdfFormat $case): string => $case->value, PdfFormat::cases()))
->defaultNull()
->end()
->booleanNode('pdf_universal_access')
Expand Down
44 changes: 22 additions & 22 deletions src/Enum/PaperSize.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,34 @@ enum PaperSize implements PaperSizeInterface
public function width(): float
{
return match ($this) {
PaperSize::Letter => 8.5,
PaperSize::Legal => 8.5,
PaperSize::Tabloid => 11,
PaperSize::Ledger => 17,
PaperSize::A0 => 33.1,
PaperSize::A1 => 23.4,
PaperSize::A2 => 16.54,
PaperSize::A3 => 11.7,
PaperSize::A4 => 8.27,
PaperSize::A5 => 5.83,
PaperSize::A6 => 4.13,
self::Letter => 8.5,
self::Legal => 8.5,
self::Tabloid => 11,
self::Ledger => 17,
self::A0 => 33.1,
self::A1 => 23.4,
self::A2 => 16.54,
self::A3 => 11.7,
self::A4 => 8.27,
self::A5 => 5.83,
self::A6 => 4.13,
};
}

public function height(): float
{
return match ($this) {
PaperSize::Letter => 11,
PaperSize::Legal => 14,
PaperSize::Tabloid => 17,
PaperSize::Ledger => 11,
PaperSize::A0 => 46.8,
PaperSize::A1 => 33.1,
PaperSize::A2 => 23.4,
PaperSize::A3 => 16.54,
PaperSize::A4 => 11.7,
PaperSize::A5 => 8.27,
PaperSize::A6 => 5.83,
self::Letter => 11,
self::Legal => 14,
self::Tabloid => 17,
self::Ledger => 11,
self::A0 => 46.8,
self::A1 => 33.1,
self::A2 => 23.4,
self::A3 => 16.54,
self::A4 => 11.7,
self::A5 => 8.27,
self::A6 => 5.83,
};
}

Expand Down
16 changes: 14 additions & 2 deletions src/Enum/Unit.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
<?php

declare(strict_types=1);

namespace Sensiolabs\GotenbergBundle\Enum;

enum Unit: string
Expand All @@ -12,4 +10,18 @@ enum Unit: string
case Millimeters = 'mm';
case Centimeters = 'cm';
case Picas = 'pc';

/**
* @param string|int|float $raw Must respect format %f%s like '12in' or '12.2px' or '12'.
*
* @return array{float, self}
*
* @throws \InvalidArgumentException if $raw does not follow correct format
*/
public static function parse(string|int|float $raw, self $defaultUnit = self::Inches): array
{
[$value, $unit] = sscanf((string) $raw, '%f%s') ?? throw new \InvalidArgumentException(sprintf('Unexpected value "%s", expected format is "%%f%%s"', $raw));

return [(float) $value, self::tryFrom((string) $unit) ?? $defaultUnit];
}
}
35 changes: 34 additions & 1 deletion tests/Builder/AbstractBuilderTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

namespace Sensiolabs\GotenbergBundle\Tests\Builder;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Sensiolabs\GotenbergBundle\Client\GotenbergClientInterface;
use Sensiolabs\GotenbergBundle\Formatter\AssetBaseDirFormatter;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Mime\Part\DataPart;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

Expand All @@ -12,8 +17,36 @@ abstract class AbstractBuilderTestCase extends TestCase

protected static Environment $twig;

protected static AssetBaseDirFormatter $assetBaseDirFormatter;

/**
* @var MockObject&GotenbergClientInterface
*/
protected GotenbergClientInterface $gotenbergClient;

public static function setUpBeforeClass(): void
{
self::$twig = new Environment(new FilesystemLoader(self::FIXTURE_DIR.'/templates'));
self::$twig = new Environment(new FilesystemLoader(self::FIXTURE_DIR));
self::$assetBaseDirFormatter = new AssetBaseDirFormatter(new Filesystem(), self::FIXTURE_DIR, self::FIXTURE_DIR);
}

protected function setUp(): void
{
$this->gotenbergClient = $this->createMock(GotenbergClientInterface::class);
}

/**
* @param array<mixed> $data
*/
protected function assertFile(array $data, string $filename, string $expectedContent): void
{
self::assertArrayHasKey('files', $data);

$file = $data['files'];

self::assertInstanceOf(DataPart::class, $file);

self::assertSame($expectedContent, $file->getBody());
self::assertSame($filename, $file->getFilename());
}
}
Loading

0 comments on commit 1e4348d

Please sign in to comment.