ApiTestCase returns empty Collections
API Platform version(s) affected: 3.0.2
Description
When running test suites using the provided ApiPlatform\Symfony\Bundle\Test\ApiTestCase, attempting to fetch a collection returns an empty set instead of an array of resources.
How to reproduce
// src/ApiResource/Person.php
namespace App\ApiResource;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Elasticsearch\Filter\MatchFilter;
use ApiPlatform\Elasticsearch\State\CollectionProvider;
use ApiPlatform\Elasticsearch\State\ItemProvider;
#[ApiResource(
operations: [
new Get(
provider: ItemProvider::class,
uriTemplate: '/person/{id}',
),
new GetCollection(
provider: CollectionProvider::class,
uriTemplate: '/people',
),
],
)]
#[ApiFilter(MatchFilter::class, properties: ['name'])]
final class Person
{
#[ApiProperty(identifier: true)]
public string $id;
public string $name;
}
// tests/ApiResource/PersonTest.php
namespace App\Tests\ApiResource;
use App\ApiResource\Person;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
final class PersonTest extends ApiTestCase
{
public static function setUpBeforeClass(): void
{
$container = static::getContainer();
$client = $container->get('api_platform.elasticsearch.client');
$indices = [
'index' => 'people',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'_source' => [
'enabled' => true
],
'properties' => [
'id' => [
'type' => 'keyword',
],
'name' => [
'type' => 'text',
'analyzer' => 'standard',
'search_analyzer' => 'standard',
],
'alias' => [
'type' => 'text',
'analyzer' => 'standard',
'search_analyzer' => 'standard',
],
],
],
],
];
$content = [
'body' => [
[
'index' => [
'_index' => 'people',
'_id' => '1234',
],
],
[
//'id' => '1234',
'name' => 'John Smith'
],
[
'index' => [
'_index' => 'people',
'_id' => '5678',
],
],
[
//'id' => '5678',
'name' => 'Jane Doe'
],
],
];
// Tidy-up indices in case of previous test failures
if ($client->indices()->exists([ 'index' => 'people' ])) {
$client->indices()->delete([ 'index' => 'people' ]);
}
$client->indices()->create($indices);
$client->bulk($content);
}
public static function tearDownAfterClass(): void
{
$container = static::getContainer();
$client = $container->get('api_platform.elasticsearch.client');
$params = ['index' => 'people'];
$client->indices()->delete($params);
}
public function testGetCollection(): void
{
// The client implements Symfony HttpClient's `HttpClientInterface`, and the response `ResponseInterface`
$response = static::createClient()->request('GET', '/api/people');
$this->assertResponseIsSuccessful();
// Asserts that the returned content type is JSON-LD (the default)
$this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
// Asserts that the returned JSON is a superset of this one
$this->assertJsonContains([
'@context' => '/api/contexts/Person',
'@id' => '/api/people',
'@type' => 'hydra:Collection',
'hydra:totalItems' => 2,
]);
// Because test fixtures are automatically loaded between each test, you can assert on them
$this->assertCount(2, $response->toArray()['hydra:member']);
// Asserts that the returned JSON is validated by the JSON Schema generated for this resource by API Platform
// This generated JSON Schema is also used in the OpenAPI spec!
$this->assertMatchesResourceCollectionJsonSchema(Person::class);
}
Expected JSON response
{
"@context": "/api/contexts/Person",
"@id": "/api/people",
"@type": "hydra:Collection",
"hydra:member": [
{
"@id": "/api/person/1234",
"@type": "Person",
"id": "1234",
"name": "John Smith"
},
{
"@id": "/api/person/5678",
"@type": "Person",
"id": "5678",
"name": "Jane Doe"
}
],
"hydra:totalItems": 2
}
Actual JSON response
{
"@context": "/api/contexts/Person",
"@id": "/api/people",
"@type": "hydra:Collection",
"hydra:member": [],
"hydra:totalItems": 0
}
I cannot fathom out why this is happening in my tests. The expected JSON output above has come from the SwaggerAPI interface and I can even filter on the results using the MatchFilter applied to the class, yet in tests I cannot return anything other than an empty collection. As you can see, I have copied the testGetCollection from the documentation just to be sure I wasn't missing something.
Strangely I can find single results in both SwaggerAPI and in the test environment. So, for example, if GET /api/person/5678 then the response returns the expected "Jane Doe" person.
I am scratching my head and lost a few hours trying to work out why my test environment fails but the SwaggerAPI works as expected. Please help!
For completeness, here is my composer.json file:
{
"name": "symfony/skeleton",
"type": "project",
"license": "MIT",
"description": "A minimal Symfony project recommended to create bare bones applications",
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": ">=8.1.11",
"ext-ctype": "*",
"ext-iconv": "*",
"api-platform/core": "^3.0",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.7",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.13",
"elasticsearch/elasticsearch": "^7.0",
"nelmio/cors-bundle": "^2.2",
"phpdocumentor/reflection-docblock": "^5.3",
"phpstan/phpdoc-parser": "^1.13",
"symfony/asset": "6.1.*",
"symfony/browser-kit": "6.1.*",
"symfony/console": "6.1.*",
"symfony/dotenv": "6.1.*",
"symfony/expression-language": "6.1.*",
"symfony/flex": "^2",
"symfony/framework-bundle": "6.1.*",
"symfony/http-client": "6.1.*",
"symfony/property-access": "6.1.*",
"symfony/property-info": "6.1.*",
"symfony/proxy-manager-bridge": "6.1.*",
"symfony/runtime": "6.1.*",
"symfony/security-bundle": "6.1.*",
"symfony/serializer": "6.1.*",
"symfony/twig-bundle": "6.1.*",
"symfony/validator": "6.1.*",
"symfony/yaml": "6.1.*"
},
"config": {
"allow-plugins": {
"composer/package-versions-deprecated": true,
"symfony/flex": true,
"symfony/runtime": true
},
"optimize-autoloader": true,
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*",
"symfony/polyfill-php73": "*",
"symfony/polyfill-php74": "*",
"symfony/polyfill-php80": "*",
"symfony/polyfill-php81": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "6.1.*",
"docker": true
}
},
"require-dev": {
"justinrainbow/json-schema": "^5.2",
"phpunit/phpunit": "^9.5",
"symfony/css-selector": "6.1.*",
"symfony/phpunit-bridge": "^6.1"
}
}
I am running the software using Docker on Mac OS X. I can quite easily ping the Elasticsearch containers from the terminal (outside of the containers) and the fact I can get results from SwaggerAPI strongly indicates I have no issues communicating with Elasticsearch containers from PHP - unless someone can advise me otherwise.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.