Skip to content

Commit

Permalink
Add schema generation and validation to the tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sfreytag committed Oct 15, 2024
1 parent ac66f84 commit af51dee
Show file tree
Hide file tree
Showing 3 changed files with 216 additions and 3 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"require": {
"php": "^8.1",
"guzzlehttp/guzzle": "^7.8",
"phpstan/phpdoc-parser": "^1.33"
"phpstan/phpdoc-parser": "^1.33",
"opis/json-schema": "^2.3"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.59",
Expand Down
192 changes: 191 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 23 additions & 1 deletion tests/api/ListingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
use CloudForest\ApiClientPhp\Schema\Enum\CompartmentTypeEnum;
use CloudForest\ApiClientPhp\Schema\Enum\GeojsonGeometryTypeEnum;
use CloudForest\ApiClientPhp\Schema\Enum\SubcompartmentTypeEnum;
use CloudForest\ApiClientPhp\Scripts\JsonSchema;
use Opis\JsonSchema\Validator;
use Opis\JsonSchema\Errors\ErrorFormatter;


final class ListingTest extends TestBase
{
Expand All @@ -36,7 +40,7 @@ public function testCreate(): void

// Inventory 2, create a centroid Geojson
$centroid = new GeojsonSchema(GeojsonGeometryTypeEnum::Point);
$centroid->geometry->coordinates = [-1.05, 53.25];
$centroid->geometry->coordinates = [[-1.05, 53.25]];

// Inventory 3, create a compartment
$compartment = new CompartmentSchema('2');
Expand Down Expand Up @@ -80,6 +84,24 @@ public function testCreate(): void
$listing->description = 'This is a test Listing from PHP Unit';
$listing->inventory = [$compartment];

// Verify the listing's inventory can be validated against our schema
// This also tests the schema generation as well as ensuring the DTO
// produices valid JSON. The JSON encode then decode casts our schema
// (assoc array) and compartment data (classes) to a stdClass object for
// the validator.
$generator = new JsonSchema();
$schemaObj = json_decode(json_encode($generator->generate('CompartmentSchema')));
$compartmentObj = json_decode(json_encode($compartment));
$validator = new Validator();
$result = $validator->validate($compartmentObj, $schemaObj);
if ($result->isValid()) {
$valid = true;
} else {
$valid = false;
print_r((new ErrorFormatter())->format($result->error()));
}
$this->assertEquals(true, $valid);

// Use the API to create the listing in CloudForest
$listingUuid = $api->listing->create($listing);
$this->assertIsString($listingUuid);
Expand Down

0 comments on commit af51dee

Please sign in to comment.