View source
<?php
namespace Drupal\Tests\farm_inventory\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
use Drupal\Tests\jsonapi\Functional\JsonApiRequestTestTrait;
use GuzzleHttp\RequestOptions;
class InventoryTest extends FarmBrowserTestBase {
use JsonApiRequestTestTrait;
protected static $modules = [
'farm_inventory',
'farm_inventory_test',
'farm_quantity_standard',
'farm_unit',
'farm_api',
];
protected function setUp() : void {
parent::setUp();
$this->user = $this
->createUser([
'administer assets',
]);
$this
->drupalLogin($this->user);
}
public function testApiInventory() {
$entity_type_manager = $this->container
->get('entity_type.manager');
$asset_storage = $entity_type_manager
->getStorage('asset');
$log_storage = $entity_type_manager
->getStorage('log');
$quantity_storage = $entity_type_manager
->getStorage('quantity');
$term_storage = $entity_type_manager
->getStorage('taxonomy_term');
$asset = $asset_storage
->create([
'type' => 'container',
'name' => $this
->randomMachineName(),
'status' => 'active',
]);
$asset
->save();
$response = $this
->requestApiEntity($asset);
$this
->assertArrayHasKey('inventory', $response['data']['attributes']);
$this
->assertEmpty($response['data']['attributes']['inventory']);
$term = $term_storage
->create([
'name' => 'liters',
'vid' => 'unit',
]);
$term
->save();
$quantity = $quantity_storage
->create([
'type' => 'standard',
'measure' => 'volume',
'value' => [
'numerator' => '2',
'denominator' => '1',
],
'units' => [
'target_id' => $term
->id(),
],
'inventory_adjustment' => 'reset',
'inventory_asset' => [
'target_id' => $asset
->id(),
],
]);
$quantity
->save();
$log = $log_storage
->create([
'type' => 'adjustment',
'status' => 'done',
'quantity' => [
'target_id' => $quantity
->id(),
'target_revision_id' => $quantity
->getRevisionId(),
],
]);
$log
->save();
$response = $this
->requestApiEntity($asset);
$this
->assertNotEmpty($response['data']['attributes']['inventory']);
$this
->assertEquals('volume', $response['data']['attributes']['inventory'][0]['measure']);
$this
->assertEquals('2', $response['data']['attributes']['inventory'][0]['value']);
$this
->assertEquals('liters', $response['data']['attributes']['inventory'][0]['units']);
$log
->delete();
$response = $this
->requestApiEntity($asset);
$this
->assertEmpty($response['data']['attributes']['inventory']);
}
protected function requestApiEntity(EntityInterface $entity) {
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$asset_uri = "base://api/{$entity->getEntityType()->id()}/{$entity->bundle()}/{$entity->uuid()}";
$response = $this
->request('GET', Url::fromUri($asset_uri), $request_options);
return Json::decode((string) $response
->getBody());
}
}