code
stringlengths 31
1.39M
| docstring
stringlengths 23
16.8k
| func_name
stringlengths 1
126
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
166
| url
stringlengths 50
220
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
public function getId(object $resource): string
{
return $resource->getSlug();
}
|
@param Site|object $resource
@return string
|
getId
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Sites/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Sites/Schema.php
|
Apache-2.0
|
public function getAttributes(object $resource): array
{
return [
'domain' => $resource->getDomain(),
'name' => $resource->getName(),
];
}
|
@param Site|object $resource
@return array
|
getAttributes
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Sites/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Sites/Schema.php
|
Apache-2.0
|
public function getAttributes(object $resource): array
{
return ['name' => $resource->name];
}
|
@param Supplier|object $resource
@return array
|
getAttributes
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Suppliers/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Suppliers/Schema.php
|
Apache-2.0
|
public function getRelationships(object $resource, bool $isPrimary, array $includeRelationships): array
{
return [
'userHistory' => [
self::SHOW_SELF => true,
self::SHOW_RELATED => true,
self::SHOW_DATA => isset($includeRelationships['userHistory']),
self::DATA => static function () use ($resource) {
return $resource->userHistory;
},
],
];
}
|
@param Supplier|object $resource
@param bool $isPrimary
@param array $includeRelationships
@return array
|
getRelationships
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Suppliers/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Suppliers/Schema.php
|
Apache-2.0
|
public function getAttributes(object $resource): array
{
return [
'createdAt' => $resource->created_at,
'updatedAt' => $resource->updated_at,
'name' => $resource->name,
];
}
|
@param Tag|object $resource
@return array
|
getAttributes
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Tags/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Tags/Schema.php
|
Apache-2.0
|
public function getAttributes(object $resource): array
{
return [
'createdAt' => $resource->created_at,
'email' => $resource->email,
'name' => $resource->name,
'updatedAt' => $resource->updated_at,
];
}
|
@param User|object $resource
@return array
|
getAttributes
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Users/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Users/Schema.php
|
Apache-2.0
|
public function getRelationships(object $resource, bool $isPrimary, array $includeRelationships): array
{
return [
'phone' => [
self::SHOW_SELF => true,
self::SHOW_RELATED => true,
self::SHOW_DATA => isset($includeRelationships['phone']),
self::DATA => function () use ($resource) {
return $resource->phone;
},
],
'roles' => [
self::SHOW_SELF => true,
self::SHOW_RELATED => true,
self::SHOW_DATA => isset($includeRelationships['roles']),
self::DATA => function () use ($resource) {
return $resource->roles;
},
],
];
}
|
@param User|object $resource
@param bool $isPrimary
@param array $includeRelationships
@return array
|
getRelationships
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Users/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Users/Schema.php
|
Apache-2.0
|
protected function creating(Video $video, $resource)
{
$video->{$video->getKeyName()} = $resource['id'];
$video->user()->associate(Auth::user());
}
|
@param Video $video
@param $resource
@return void
|
creating
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Videos/Adapter.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Videos/Adapter.php
|
Apache-2.0
|
public function getRelationships(object $resource, bool $isPrimary, array $includeRelationships): array
{
return [
'uploadedBy' => [
self::SHOW_SELF => true,
self::SHOW_RELATED => true,
self::SHOW_DATA => isset($includeRelationships['uploadedBy']),
self::DATA => function () use ($resource) {
return $resource->user;
},
],
];
}
|
@param Video|object $resource
@param bool $isPrimary
@param array $includeRelationships
@return array
|
getRelationships
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/JsonApi/Videos/Schema.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/JsonApi/Videos/Schema.php
|
Apache-2.0
|
public function access(User $user)
{
return true;
}
|
Determine if the user is allowed to access posts.
@param User $user
@return bool
|
access
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Policies/PostPolicy.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Policies/PostPolicy.php
|
Apache-2.0
|
public function create(User $user)
{
return (bool) $user->author;
}
|
Determine if the given user can create posts.
@param User $user
@return bool
|
create
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Policies/PostPolicy.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Policies/PostPolicy.php
|
Apache-2.0
|
public function read(User $user, Post $post)
{
if ($post->published) {
return true;
}
return $this->update($user, $post);
}
|
Determine if the given post can be read by the user.
@param User $user
@param Post $post
@return bool
|
read
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Policies/PostPolicy.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Policies/PostPolicy.php
|
Apache-2.0
|
public function update(User $user, Post $post)
{
return $user->is($post->author);
}
|
Determine if the given post can be updated by the user.
@param User $user
@param Post $post
@return bool
|
update
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Policies/PostPolicy.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Policies/PostPolicy.php
|
Apache-2.0
|
public function delete(User $user, Post $post)
{
return $this->update($user, $post);
}
|
Determine if the given post can be deleted by the user.
@param User $user
@param Post $post
@return bool
|
delete
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Policies/PostPolicy.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Policies/PostPolicy.php
|
Apache-2.0
|
public function comment(User $user, Post $post)
{
return Gate::denies('admin', $user);
}
|
Determine if the user can comment on the given post.
@param User $user
@param Post $post
@return bool
|
comment
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Policies/PostPolicy.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Policies/PostPolicy.php
|
Apache-2.0
|
public function boot()
{
//
parent::boot();
}
|
Define your route model bindings, pattern filters, etc.
@return void
|
boot
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Providers/RouteServiceProvider.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Providers/RouteServiceProvider.php
|
Apache-2.0
|
public function map()
{
$this->mapApiRoutes();
}
|
Define the routes for the application.
@return void
|
map
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Providers/RouteServiceProvider.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Providers/RouteServiceProvider.php
|
Apache-2.0
|
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(__DIR__ . '/../../routes/web.php');
}
|
Define the "web" routes for the application.
These routes all receive session state, CSRF protection, etc.
@return void
|
mapWebRoutes
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Providers/RouteServiceProvider.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Providers/RouteServiceProvider.php
|
Apache-2.0
|
protected function mapApiRoutes()
{
Route::middleware('api')
->namespace($this->namespace)
->group(__DIR__ . '/../../routes/api.php');
}
|
Define the "api" routes for the application.
These routes are typically stateless.
@return void
|
mapApiRoutes
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/app/Providers/RouteServiceProvider.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/app/Providers/RouteServiceProvider.php
|
Apache-2.0
|
public function test(string $contentType): void
{
$user = factory(User::class)->create();
$file = UploadedFile::fake()->image('avatar.jpg');
$expected = [
'type' => 'avatars',
'attributes' => ['mediaType' => 'image/jpeg'],
];
$this->actingAs($user, 'api');
$response = $this
->jsonApi()
->includePaths('user')
->contentType($contentType)
->withPayload(['avatar' => $file])
->post('/api/v1/avatars');
$id = $response
->assertCreatedWithServerId(url('/api/v1/avatars'), $expected)
->assertIsIncluded('users', $user)
->id();
$this->assertDatabaseHas('avatars', [
'id' => $id,
'media_type' => 'image/jpeg',
'user_id' => $user->getKey(),
]);
$path = Avatar::whereKey($id)->value('path');
Storage::disk('local')->assertExists($path);
}
|
Test that a user can upload an avatar to the API using a standard
HTML form post. This means our API must allow a non-JSON API content media type
when creating the resource.
@param string $contentType
@dataProvider multipartProvider
|
test
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/CreateTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/CreateTest.php
|
Apache-2.0
|
public function test(): void
{
$avatar = factory(Avatar::class)->create();
$expected = $this->serialize($avatar)->toArray();
$response = $this
->jsonApi()
->get(url('/api/v1/avatars', $avatar));
$response
->assertFetchedOneExact($expected);
}
|
Test that reading an avatar returns the exact resource we are expecting.
|
test
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/ReadTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/ReadTest.php
|
Apache-2.0
|
public function testDownload(): void
{
Storage::fake('local');
$path = UploadedFile::fake()->image('avatar.jpg')->store('avatars');
$avatar = factory(Avatar::class)->create(compact('path'));
$response = $this
->jsonApi()
->accept('image/*')
->get(url('/api/v1/avatars', $avatar));
$response
->assertSuccessful()
->assertHeader('Content-Type', $avatar->media_type);
}
|
Test that reading the avatar with an image media tye results in it being downloaded.
|
testDownload
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/ReadTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/ReadTest.php
|
Apache-2.0
|
public function testDownloadFileDoesNotExist(): void
{
$path = 'avatars/does-not-exist.jpg';
$avatar = factory(Avatar::class)->create(compact('path'));
$response = $this
->jsonApi()
->accept('image/*')
->get(url('/api/v1/avatars', $avatar));
$response
->assertStatus(404)
->assertHeader('Content-Type', 'text/html; charset=UTF-8');
}
|
If the avatar model exists, but the file doesn't, we need to get an error back. As
we have not requested JSON API, this should be the standard Laravel error i.e.
`text/html`.
|
testDownloadFileDoesNotExist
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/ReadTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/ReadTest.php
|
Apache-2.0
|
public function testIncludeUser(): void
{
$avatar = factory(Avatar::class)->create();
$userId = ['type' => 'users', 'id' => (string) $avatar->user_id];
$expected = $this
->serialize($avatar)
->replace('user', $userId);
$response = $this
->jsonApi()
->includePaths('user')
->get(url('/api/v1/avatars', $avatar));
$response
->assertFetchedOneExact($expected)
->assertIncluded([$userId]);
}
|
Test that we can include the user in the response.
|
testIncludeUser
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/ReadTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/ReadTest.php
|
Apache-2.0
|
public function testInvalidInclude(): void
{
$avatar = factory(Avatar::class)->create();
$expected = [
'status' => '400',
'detail' => 'Include path foo is not allowed.',
'source' => ['parameter' => 'include'],
];
$response = $this
->jsonApi()
->includePaths('foo')
->get(url('/api/v1/avatars', $avatar));
$response
->assertErrorStatus($expected);
}
|
Test that include fields are validated.
|
testInvalidInclude
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/ReadTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/ReadTest.php
|
Apache-2.0
|
protected function serialize(Avatar $avatar): ResourceObject
{
$self = url("/api/v1/avatars", $avatar);
return ResourceObject::create([
'type' => 'avatars',
'id' => (string) $avatar->getRouteKey(),
'attributes' => [
'createdAt' => $avatar->created_at->toJSON(),
'mediaType' => $avatar->media_type,
'updatedAt' => $avatar->updated_at->toJSON(),
],
'relationships' => [
'user' => [
'links' => [
'self' => "{$self}/relationships/user",
'related' => "{$self}/user",
],
],
],
'links' => [
'self' => $self,
],
]);
}
|
Get the expected JSON API resource for the avatar model.
@param Avatar $avatar
@return ResourceObject
|
serialize
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/TestCase.php
|
Apache-2.0
|
public function test(string $contentType): void
{
$file = UploadedFile::fake()->image('avatar.jpg');
$expected = [
'type' => 'avatars',
'id' => (string) $this->avatar->getRouteKey(),
'attributes' => ['mediaType' => 'image/jpeg'],
];
$this->actingAs($this->avatar->user, 'api');
$response = $this
->withoutExceptionHandling()
->jsonApi()
->contentType($contentType)
->includePaths('user')
->withPayload(['avatar' => $file])
->patch(url('/api/v1/avatars', $this->avatar));
$response
->assertFetchedOne($expected)
->assertIsIncluded('users', $this->avatar->user)
->id();
$this->assertDatabaseHas('avatars', [
'id' => $this->avatar->getKey(),
'media_type' => 'image/jpeg',
'user_id' => $this->avatar->user->getKey(),
]);
$path = Avatar::whereKey($this->avatar->getKey())->value('path');
Storage::disk('local')->assertExists($path);
}
|
Test that a user can upload an avatar to the API using a standard
HTML form post. This means our API must allow a non-JSON API content media type
when updating the resource.
@param string $contentType
@dataProvider multipartProvider
|
test
|
php
|
cloudcreativity/laravel-json-api
|
tests/dummy/tests/Feature/Avatars/UpdateTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/dummy/tests/Feature/Avatars/UpdateTest.php
|
Apache-2.0
|
public function testRequestedResourceHasRequestHost()
{
$id = factory(Post::class)->create()->getRouteKey();
config()->set('json-api-v1.url.host', null);
$response = $this
->withAppRoutes()
->jsonApi()
->get("http://www.example.com/api/v1/posts/$id");
$json = $response
->assertStatus(200)
->json();
$this->assertSelfLink("http://www.example.com/api/v1/posts/$id", $json);
}
|
If the URL host is set to `null`, we expect the request host to be prepended to links.
|
testRequestedResourceHasRequestHost
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testRequestedResourceDoesNotHaveHost()
{
$id = factory(Post::class)->create()->getRouteKey();
config()->set('json-api-v1.url.host', false);
$response = $this
->withAppRoutes()
->jsonApi()
->get("http://www.example.com/api/v1/posts/$id");
$json = $response
->assertStatus(200)
->json();
$this->assertSelfLink("/api/v1/posts/$id", $json);
}
|
If the URL host is set to `false`, we do not expect a host to be prepended to links.
|
testRequestedResourceDoesNotHaveHost
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testRequestResourceDoesNotHaveUrlNamespace()
{
$id = factory(Post::class)->create()->getRouteKey();
config()->set('json-api-v1.url.namespace', null);
$response = $this
->withAppRoutes()
->jsonApi()
->get("http://www.example.com/posts/$id");
$json = $response
->assertStatus(200)
->json();
$this->assertSelfLink("http://www.example.com/posts/$id", $json);
}
|
If there is no URL namespace, the URL must be properly formed.
|
testRequestResourceDoesNotHaveUrlNamespace
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testRequestResourceHasEmptyUrlNamespace()
{
$id = factory(Post::class)->create()->getRouteKey();
config()->set('json-api-v1.url.namespace', '');
$response = $this
->withAppRoutes()
->jsonApi()
->get("http://www.example.com/posts/$id");
$json = $response
->assertStatus(200)
->json();
$this->assertSelfLink("http://www.example.com/posts/$id", $json);
}
|
If there is no URL namespace, the URL must be properly formed.
|
testRequestResourceHasEmptyUrlNamespace
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testRequestResourceDoesNotHaveHostAndUrlNamespace()
{
$id = factory(Post::class)->create()->getRouteKey();
config()->set('json-api-v1.url.host', false);
config()->set('json-api-v1.url.namespace', null);
$response = $this
->withAppRoutes()
->jsonApi()
->get("http://www.example.com/posts/$id");
$json = $response
->assertStatus(200)
->json();
$this->assertSelfLink("/posts/$id", $json);
}
|
If there is no URL host and namespace, the URL must be properly formed.
|
testRequestResourceDoesNotHaveHostAndUrlNamespace
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testSerializedResourceHasAppHost()
{
$post = factory(Post::class)->create();
config()->set('app.url', $host = 'http://www.example.com');
config()->set('json-api-v1.url.host', null);
$json = json_api()->encoder()->serializeData($post);
$this->assertSelfLink("http://www.example.com/api/v1/posts/{$post->getRouteKey()}", $json);
}
|
When encoding outside of a request and the URL host is set to `null`, we expect the
`app.url` config setting to be used.
|
testSerializedResourceHasAppHost
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testSerializedResourceHasSpecificHost()
{
$post = factory(Post::class)->create();
config()->set('app.url', 'http://localhost');
config()->set('json-api-v1.url.host', $host = 'http://www.example.com');
$json = json_api()->encoder()->serializeData($post);
$this->assertSelfLink("http://www.example.com/api/v1/posts/{$post->getRouteKey()}", $json);
}
|
When encoding outside of a request and the URL host is set to a specified host,
we expect that to be used.
|
testSerializedResourceHasSpecificHost
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testSerializedResourceDoesNotHaveAppHost()
{
$post = factory(Post::class)->create();
config()->set('app.url', 'http://www.example.com');
config()->set('json-api-v1.url.host', false);
$json = json_api()->encoder()->serializeData($post);
$this->assertSelfLink("/api/v1/posts/{$post->getRouteKey()}", $json);
}
|
When encoding outside of a request and the URL host is set to `false`, we expect
no host in the serialized data.
|
testSerializedResourceDoesNotHaveAppHost
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/EncodingTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/EncodingTest.php
|
Apache-2.0
|
public function testCustom404()
{
$this->markTestSkipped('@todo work out how to override translation config');
$expected = $this->withCustomError(ResourceNotFoundException::class);
$response = $this
->jsonApi()
->get('/api/v1/posts/999');
$response->assertStatus(404)->assertExactJson($expected);
}
|
Can override the default 404 error message.
|
testCustom404
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testDocumentRequired($content, $method = 'POST')
{
if ('POST' === $method) {
$uri = '/api/v1/posts';
} else {
$uri = url('/api/v1/posts', factory(Post::class)->create());
}
$expected = [
'errors' => [
[
'title' => 'Document Required',
'status' => '400',
'detail' => 'Expecting request to contain a JSON API document.',
],
],
];
$this->doInvalidRequest($uri, $content, $method)
->assertStatus(400)
->assertHeader('Content-Type', 'application/vnd.api+json')
->assertExactJson($expected);
}
|
Returns a JSON API error when a document is not provided, or is not an object.
@param string $content
@param string $method
@dataProvider invalidDocumentProvider
|
testDocumentRequired
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testIgnoresData($content, $method = 'GET')
{
$model = factory(Post::class)->create();
$uri = url('/api/v1/posts', $model);
$this->doInvalidRequest($uri, $content, $method)
->assertSuccessful();
}
|
@param $content
@param $method
@dataProvider ignoreDocumentProvider
|
testIgnoresData
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testCustomDocumentRequired()
{
$this->markTestSkipped('@todo work out how to override translation config');
$uri = '/api/v1/posts';
$expected = $this->withCustomError(DocumentRequiredException::class);
$this->doInvalidRequest($uri, '')
->assertStatus(400)
->assertHeader('Content-Type', 'application/vnd.api+json')
->assertExactJson($expected);
}
|
Can override the default document required error.
|
testCustomDocumentRequired
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testCustomInvalidJson()
{
$this->markTestSkipped('@todo work out how to override translation config');
$uri = '/api/v1/posts';
$expected = $this->withCustomError(InvalidJsonException::class);
$content = '{"data": {}';
$this->doInvalidRequest($uri, $content)->assertStatus(400)->assertExactJson($expected);
}
|
Can override the invalid JSON error.
|
testCustomInvalidJson
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testClientWantsJsonApiError(): void
{
$expected = [
'errors' => [
[
'title' => 'Not Found',
'status' => '404',
],
],
];
$response = $this
->jsonApi()
->post('/api/v99/posts');
$response
->assertStatus(404)
->assertHeader('Content-Type', 'application/vnd.api+json')
->assertJson($expected);
}
|
If the client sends a request wanting JSON API (i.e. a JSON API Accept header),
whatever error is generated by the application must be returned as a JSON API error
even if the error has not been generated from one of the configured APIs.
|
testClientWantsJsonApiError
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testAcceptAny()
{
$expected = [
'status' => '400',
'source' => [
'parameter' => 'include',
],
];
$response = $this->jsonApi()->accept('*/*')->includePaths('foo')->get('/api/v1/posts');
$response->assertErrorStatus($expected);
}
|
If content negotiation has occurred on a JSON API route, then we always expect
a JSON API response if the matched codec supports encoding to JSON API.
This can occur when the client has said it accepts any media type: the JSON API
media type will match, then any subsequent exceptions should be rendered as JSON
API.
@see https://github.com/cloudcreativity/laravel-json-api/issues/329
|
testAcceptAny
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testNeomerxJsonApiException()
{
config()->set('app.debug', true);
Route::get('/test', function () {
throw new NeomerxException(new NeomerxError(
null,
null,
null,
'422',
null,
null,
'My foobar error message.'
), 418);
});
$this->get('/test', ['Accept' => '*/*'])
->assertStatus(418)
->assertSee('My foobar error message.');
}
|
If we get a JSON API exception outside of a JSON API route, but have not
asked for a JSON API response, then it must be converted to a HTTP exception.
Otherwise it will always render as a 500 Internal Server error.
@see https://github.com/cloudcreativity/laravel-json-api/issues/329
|
testNeomerxJsonApiException
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testJsonApiException2(): void
{
Route::get('/test', function () {
$error = Error::fromArray([
'title' => 'The language you want to use is not active',
'status' => Response::HTTP_UNPROCESSABLE_ENTITY,
]);
throw new JsonApiException($error);
});
$expected = [
'errors' => [
[
'status' => '422',
'title' => 'The language you want to use is not active',
],
],
];
$this->get('/test')
->assertStatus(422)
->assertHeader('Content-Type', 'application/vnd.api+json')
->assertExactJson($expected);
}
|
@see https://github.com/cloudcreativity/laravel-json-api/issues/566
|
testJsonApiException2
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testTokenMismatch()
{
$ex = new TokenMismatchException("The token is not valid.");
$expected = [
'title' => 'Invalid Token',
'detail' => 'The token is not valid.',
'status' => '419',
];
$this->request($ex)
->assertErrorStatus($expected)
->assertHeader('Content-Type', 'application/vnd.api+json');
}
|
By default Laravel sends a 419 response for a TokenMismatchException.
@see https://github.com/cloudcreativity/laravel-json-api/issues/181
|
testTokenMismatch
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testBadRequestException(): void
{
$ex = new BadRequestException('The request format is bad.');
$expected = [
'title' => 'Bad Request',
'detail' => 'The request format is bad.',
'status' => '400',
];
$this->request($ex)
->assertExactErrorStatus($expected)
->assertHeader('Content-Type', 'application/vnd.api+json');
}
|
The Symfony bad request exception does not implement the HTTP exception
interface, so we need to ensure we handle it.
|
testBadRequestException
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testValidationException()
{
$messages = new MessageBag([
'email' => $detail = 'These credentials do not match our records.',
]);
$validator = $this->createMock(Validator::class);
$validator->method('errors')->willReturn($messages);
$ex = new ValidationException($validator);
$this->request($ex)->assertStatus(422)->assertExactErrorStatus([
'title' => 'Unprocessable Entity',
'status' => '422',
'detail' => $detail,
]);
}
|
If we get a Laravel validation exception we need to convert this to
JSON API errors.
@see https://github.com/cloudcreativity/laravel-json-api/issues/182
|
testValidationException
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
private function doInvalidRequest($uri, $content, $method = 'POST')
{
$headers = $this->transformHeadersToServerVars([
'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
'CONTENT_TYPE' => 'application/vnd.api+json',
'Accept' => 'application/vnd.api+json',
]);
return $this->call($method, $uri, [], [], [], $headers, $content);
}
|
@param $uri
@param $content
@param $method
@return \Illuminate\Testing\TestResponse
|
doInvalidRequest
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ErrorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ErrorsTest.php
|
Apache-2.0
|
public function testIdAsMultiple()
{
$user = factory(User::class)->create();
$comments = factory(Comment::class, 2)->create([
'user_id' => $user->getKey(),
]);
$other = factory(Comment::class)->create();
$filter = [
'createdBy' => $user,
'id' => [$comments[0], $comments[1], $other],
];
$response = $this
->actingAsUser()
->jsonApi('comments')
->filter($filter)
->get('/api/v1/comments');
$response
->assertFetchedMany($comments);
}
|
The `id` filter must work with other filters. In this example, if
we filter for `id` plus `created-by` we are asking: *of these
comments, which were created by the specified user?*
@see https://github.com/cloudcreativity/laravel-json-api/issues/219
|
testIdAsMultiple
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/FilterTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/FilterTest.php
|
Apache-2.0
|
public function testFilterResource()
{
$post = factory(Post::class)->states('published')->create();
$retrieved = 0;
Post::retrieved(function () use (&$retrieved) {
$retrieved++;
});
$expected = [
'type' => 'posts',
'id' => (string) $post->getRouteKey(),
'attributes' => [
'title' => $post->title,
],
];
$response = $this
->jsonApi()
->filter(['published' => '1'])
->get(url('/api/v1/posts', $post));
$response
->assertFetchedOne($expected);
$this->assertSame(1, $retrieved, 'retrieved once');
}
|
Must be able to filter a read resource request.
@see https://github.com/cloudcreativity/laravel-json-api/issues/218
for the original issue to add this feature.
@see https://github.com/cloudcreativity/laravel-json-api/issues/256
we expect the resource to be retrieved once.
|
testFilterResource
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/FilterTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/FilterTest.php
|
Apache-2.0
|
public function testFilterResourceRejectsIdFilter()
{
$post = factory(Post::class)->create();
$response = $this
->jsonApi('posts')
->filter(['id' => '999'])
->get(url('/api/v1/posts', $post));
$response->assertHasError(400, [
'status' => '400',
'source' => ['parameter' => 'filter'],
]);
}
|
The `id` filter must be rejected for a read resource request as it makes
no sense to include it because the URL is already scoped by id.
|
testFilterResourceRejectsIdFilter
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/FilterTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/FilterTest.php
|
Apache-2.0
|
public function testGeneratesDefaultApi()
{
LaravelJsonApi::defaultApi('default');
$result = $this->artisan('make:json-api');
$this->assertSame(0, $result);
$this->assertFileEquals(
__DIR__ . '/../../../stubs/api.php',
"{$this->path}/config/json-api-default.php"
);
}
|
We can generate a new API configuration file in our application.
|
testGeneratesDefaultApi
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testGeneratesNamedApi()
{
$result = $this->artisan('make:json-api', ['name' => 'foo']);
$this->assertSame(0, $result);
$this->assertFileEquals(
__DIR__ . '/../../../stubs/api.php',
"{$this->path}/config/json-api-foo.php"
);
}
|
We can generate a new API configuration file in our application.
|
testGeneratesNamedApi
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testEloquentResourceAsDefault()
{
$this->withEloquent();
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
]);
$this->assertSame(0, $result);
$this->assertEloquentResource();
}
|
If Eloquent is set as the default, running the generator without specifying
Eloquent will create Eloquent classes.
|
testEloquentResourceAsDefault
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testForceEloquentResource()
{
$this->withoutEloquent();
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
'--eloquent' => true,
]);
$this->assertSame(0, $result);
$this->assertEloquentResource();
}
|
If Eloquent is not the default, running the generator with the Eloquent option
will create Eloquent classes.
|
testForceEloquentResource
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testEloquentResourceNotByResource()
{
$this->withEloquent()->notByResource();
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
]);
$this->assertSame(0, $result);
$this->assertEloquentResource();
}
|
Test generating an Eloquent resource with the `by-resource` option set to `false`.
|
testEloquentResourceNotByResource
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testGenericResourceAsDefault()
{
$this->withoutEloquent();
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
]);
$this->assertSame(0, $result);
$this->assertGenericResource();
}
|
If Eloquent is not the default, running the generator without specifying
anything will create generic classes.
|
testGenericResourceAsDefault
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testForceGenericResource()
{
$this->withEloquent();
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
'--no-eloquent' => true,
]);
$this->assertSame(0, $result);
$this->assertGenericResource();
}
|
If Eloquent is the default, running the generator with the non-eloquent option
will create generic classes.
|
testForceGenericResource
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testGenericResourceNotByResource()
{
$this->withoutEloquent()->notByResource();
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
]);
$this->assertSame(0, $result);
$this->assertGenericResource();
}
|
Test generating generic resources with the `by-resource` option set to `false`.
|
testGenericResourceNotByResource
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testReusableAuthorizer($byResource)
{
$this->byResource($byResource);
$result = $this->artisan('make:json-api:authorizer', [
'name' => 'visitor',
]);
$this->assertSame(0, $result);
$this->assertReusableAuthorizer();
}
|
Test generating a reusable authorizer.
@param bool $byResource
@dataProvider byResourceProvider
|
testReusableAuthorizer
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testResourceAuthorizer($byResource)
{
$this->byResource($byResource);
$result = $this->artisan('make:json-api:authorizer', [
'name' => 'companies',
'--resource' => true,
]);
$this->assertSame(0, $result);
$this->assertResourceAuthorizer();
}
|
Test generating a resource-specific authorizer.
@param $byResource
@dataProvider byResourceProvider
|
testResourceAuthorizer
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testResourceWithAuthorizer($byResource)
{
$this->byResource($byResource);
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
'--auth' => true,
]);
$this->assertSame(0, $result);
$this->assertResourceAuthorizer();
}
|
Test generating a resource with an authorizer.
@param $byResource
@dataProvider byResourceProvider
|
testResourceWithAuthorizer
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testReusableContentNegotiator($byResource)
{
$this->byResource($byResource);
$result = $this->artisan('make:json-api:content-negotiator', [
'name' => 'json',
]);
$this->assertSame(0, $result);
$this->assertReusableContentNegotiator();
}
|
Test generating a reusable content negotiator.
@param bool $byResource
@dataProvider byResourceProvider
|
testReusableContentNegotiator
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testResourceContentNegotiator($byResource)
{
$this->byResource($byResource);
$result = $this->artisan('make:json-api:content-negotiator', [
'name' => 'companies',
'--resource' => true,
]);
$this->assertSame(0, $result);
$this->assertResourceContentNegotiator();
}
|
Test generating a resource-specific content negotiator.
@param $byResource
@dataProvider byResourceProvider
|
testResourceContentNegotiator
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testResourceWithContentNegotiator($byResource)
{
$this->byResource($byResource);
$result = $this->artisan('make:json-api:resource', [
'resource' => 'companies',
'--auth' => true,
'--content-negotiator' => true,
]);
$this->assertSame(0, $result);
$this->assertResourceContentNegotiator();
}
|
Test generating a resource with an content negotiator.
@param $byResource
@dataProvider byResourceProvider
|
testResourceWithContentNegotiator
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
private function assertContentContains($expected, $content, $message = '')
{
if (method_exists($this, 'assertStringContainsString')) {
$this->assertStringContainsString($expected, $content, $message);
} else {
$this->assertContains($expected, $content, $message);
}
}
|
@param string $expected
@param string $content
@param string $message
|
assertContentContains
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
private function assertContentNotContains($expected, $content, $message = '')
{
if (method_exists($this, 'assertStringNotContainsString')) {
$this->assertStringNotContainsString($expected, $content, $message);
} else {
$this->assertNotContains($expected, $content, $message);
}
}
|
@param string $expected
@param string $content
@param string $message
|
assertContentNotContains
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/GeneratorsTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/GeneratorsTest.php
|
Apache-2.0
|
public function testReadBlog()
{
/** @var Blog $blog */
$blog = factory(Blog::class)->states('published')->create();
$expected = [
'type' => 'blogs',
'id' => $blog,
'attributes' => [
'title' => $blog->title,
'article' => $blog->article,
'publishedAt' => $blog->published_at->toJSON(),
],
];
$response = $this
->jsonApi()
->get(url('/api/v1/blogs', $blog));
$response->assertFetchedOne($expected);
}
|
Test that we can read a resource from the package.
|
testReadBlog
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/PackageTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/PackageTest.php
|
Apache-2.0
|
public function testReadPost(): void
{
/** @var Post $post */
$post = factory(Post::class)->create();
$response = $this
->jsonApi('posts')
->get(url('/api/v1/posts', $post));
$response->assertFetchedOne($post);
}
|
Test that we can read a resource from the application.
|
testReadPost
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/PackageTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/PackageTest.php
|
Apache-2.0
|
protected function withAppRoutes()
{
Route::middleware('web')
->namespace($namespace = 'DummyApp\Http\Controllers')
->group(__DIR__ . '/../../dummy/routes/web.php');
Route::group(compact('namespace'), function () {
require __DIR__ . '/../../dummy/routes/api.php';
});
$this->refreshRoutes();
return $this;
}
|
Use the default dummy app routes.
@return $this
@deprecated use acceptance tests to test the dummy app.
|
withAppRoutes
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/TestCase.php
|
Apache-2.0
|
protected function withRoutes(\Closure $callback, array $options = [], string $api = 'v1')
{
Route::group([
'namespace' => 'DummyApp\Http\Controllers',
], function () use ($api, $options, $callback) {
if (empty($options)) {
JsonApi::register($api, $callback);
} else {
JsonApi::register($api, $options, $callback);
}
});
return $this;
}
|
@param \Closure $callback
@param array $options
@param string $api
@return $this
|
withRoutes
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/TestCase.php
|
Apache-2.0
|
protected function refreshRoutes()
{
/** @var Router $router */
$router = app('router');
$router->getRoutes()->refreshNameLookups();
$router->getRoutes()->refreshActionLookups();
return $this;
}
|
Refresh the router.
This is required because it is the same as what a Laravel application's
route service provider does. Without it, some of the names and actions
may be missing from the maps within the router's route collection.
@return $this
@see https://github.com/laravel/framework/issues/19020#issuecomment-409873471
|
refreshRoutes
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/TestCase.php
|
Apache-2.0
|
public function testUrl($expected, $method, $resourceId = null, $relationship = null)
{
$url = json_api()->url();
$args = $this->normalizeArgs($resourceId, $relationship);
$this->assertSame("http://localhost$expected", call_user_func_array([$url, $method], $args));
}
|
@param $expected
@param $method
@param $resourceId
@param $relationship
@dataProvider urlProvider
|
testUrl
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/UrlAndLinksTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/UrlAndLinksTest.php
|
Apache-2.0
|
public function testLink($expected, $method, $resourceId = null, $relationship = null)
{
$links = json_api()->links();
$expected = new Link(false, "http://localhost$expected", false);
$args = $this->normalizeArgs($resourceId, $relationship);
$this->assertEquals($expected, call_user_func_array([$links, $method], $args));
}
|
@param $expected
@param $method
@param $resourceId
@param $relationship
@dataProvider urlProvider
|
testLink
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/UrlAndLinksTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/UrlAndLinksTest.php
|
Apache-2.0
|
public function testLinkWithMeta($expected, $method, $resourceId = null, $relationship = null)
{
$meta = (object) ['foo' => 'bar'];
$links = json_api()->links();
$expected = new Link(false, "http://localhost$expected", true, $meta);
$args = $this->normalizeArgs($resourceId, $relationship);
$args[] = $meta;
$this->assertEquals($expected, call_user_func_array([$links, $method], $args));
}
|
@param $expected
@param $method
@param $resourceId
@param $relationship
@dataProvider urlProvider
|
testLinkWithMeta
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/UrlAndLinksTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/UrlAndLinksTest.php
|
Apache-2.0
|
private function normalizeArgs($resourceId, $relationship)
{
if (!$relationship) {
$args = $resourceId ? ['posts', $resourceId] : ['posts'];
} else {
$args = ['posts', $resourceId, $relationship];
}
return $args;
}
|
@param $resourceId
@param $relationship
@return array
|
normalizeArgs
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/UrlAndLinksTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/UrlAndLinksTest.php
|
Apache-2.0
|
public function testApiAuthDisallowed()
{
$response = $this
->withApiMiddleware()
->jsonApi()
->get('/api/v1/posts');
$response->assertStatus(401)->assertJson([
'errors' => [
[
'title' => 'Unauthenticated',
'status' => '401',
],
],
]);
}
|
Test that we can use Laravel's auth middleware to protect the entire API.
|
testApiAuthDisallowed
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Auth/AuthTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Auth/AuthTest.php
|
Apache-2.0
|
public function testApiAuthAllowed()
{
$response = $this
->withApiMiddleware()
->actingAsUser()
->jsonApi()
->get('/api/v1/posts');
$response->assertSuccessful();
}
|
Test that an authenticated user can access resource in protected API.
|
testApiAuthAllowed
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Auth/AuthTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Auth/AuthTest.php
|
Apache-2.0
|
public function testResourceAuth($authenticated, $resourceType, $expected)
{
if ($authenticated) {
$this->actingAsUser();
}
$response = $this
->withResourceMiddleware()
->jsonApi()
->get('/api/v1/'. $resourceType);
$response->assertStatus($expected);
if (200 !== $expected) {
$response->assertJson([
'errors' => [
[
'title' => 'Unauthenticated',
'status' => '401',
],
],
]);
}
}
|
@param $authenticated
@param $resourceType
@param $expected
@dataProvider resourceAuthProvider
|
testResourceAuth
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Auth/AuthTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Auth/AuthTest.php
|
Apache-2.0
|
private function withApiMiddleware()
{
Auth::routes();
Route::group([
'namespace' => 'DummyApp\\Http\\Controllers',
], function () {
JsonApi::register('v1', [
'middleware' => 'auth',
], function (RouteRegistrar $api) {
$api->resource('posts');
});
});
$this->refreshRoutes();
return $this;
}
|
Set up authentication on the whole API.
@return $this
|
withApiMiddleware
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Auth/AuthTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Auth/AuthTest.php
|
Apache-2.0
|
private function withResourceMiddleware()
{
Auth::routes();
Route::group([
'namespace' => 'DummyApp\\Http\\Controllers',
], function () {
JsonApi::register('v1', [], function (RouteRegistrar $api) {
$api->resource('posts');
$api->resource('comments', [
'middleware' => 'auth',
]);
});
});
$this->refreshRoutes();
return $this;
}
|
Set up authentication on one resource.
@return $this
|
withResourceMiddleware
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Auth/AuthTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Auth/AuthTest.php
|
Apache-2.0
|
public function test()
{
Route::group([
'namespace' => '\\DummyApp\\Http\\Controllers',
'middleware' => 'auth'
], function () {
JsonApi::register('v1', [], function (RouteRegistrar $api) {
$api->resource('posts');
});
});
$response = $this
->jsonApi()
->get('/api/v1/posts');
$response->assertErrorStatus([
'status' => '401',
'title' => 'Unauthenticated',
]);
}
|
Test authorization exception *before* JSON API middleware.
|
test
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Auth/Issue284Test.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Auth/Issue284Test.php
|
Apache-2.0
|
private function doLogin($credentials)
{
return $this->postJson(
route('login'),
$credentials,
['Accept' => 'application/vnd.api+json']
);
}
|
@param $credentials
@return \Illuminate\Testing\TestResponse
|
doLogin
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Auth/LoginTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Auth/LoginTest.php
|
Apache-2.0
|
public function testRemovesLinksIfNoId()
{
$this->mock->append();
$post = factory(Post::class)->make();
$userId = (string) $post->author->getRouteKey();
$document = [
'data' => [
'type' => 'posts',
'attributes' => [
'createdAt' => null,
'updatedAt' => null,
'deletedAt' => null,
'title' => $post->title,
'slug' => $post->slug,
'content' => $post->content,
'published' => $post->published_at,
],
'relationships' => [
'author' => [
'data' => [
'type' => 'users',
'id' => $userId,
],
],
],
],
];
$params = new QueryParameters(['author', 'comments'], ['users' => ['name', 'email']]);
$expected = $this->willSeeResource($post, 201);
$actual = $this->client
->withLinks()
->withIncludePaths('author')
->createRecord($post, $params);
$this->assertSame($expected, $actual, 'http response');
$this->assertQueryParameters([
'include' => 'author,comments',
'fields[users]' => 'name,email',
]);
$this->assertSentDocument($document);
}
|
As the resource does not have an id, we expect links to be removed even if the
client is set to include links.
|
testRemovesLinksIfNoId
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/CreateTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/CreateTest.php
|
Apache-2.0
|
public function testWithoutHost()
{
$client = json_api()->client(['handler' => $this->handler]);
$post = factory(Post::class)->make();
$this->willSeeResource($post, 201);
$client->createRecord($post);
$this->assertSame(
'http://localhost/api/v1/posts',
(string) $this->mock->getLastRequest()->getUri()
);
}
|
Uses the host in the JSON API config file.
|
testWithoutHost
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/FactoryTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/FactoryTest.php
|
Apache-2.0
|
public function testWithOptionsIncludingBaseUri()
{
$client = json_api()->client([
'handler' => $this->handler,
'base_uri' => 'http://external.com/api/v1/',
]);
$post = factory(Post::class)->make();
$this->willSeeResource($post, 201);
$client->createRecord($post);
$this->assertSame(
'http://external.com/api/v1/posts',
(string) $this->mock->getLastRequest()->getUri()
);
}
|
If the options have a base URI, it should not be overridden.
|
testWithOptionsIncludingBaseUri
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/FactoryTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/FactoryTest.php
|
Apache-2.0
|
public function testWithHostAndPath()
{
$client = json_api()->client(
'http://example.com/foo',
['handler' => $this->handler]
);
$post = factory(Post::class)->make();
$this->willSeeResource($post, 201);
$client->createRecord($post);
$this->assertSame(
'http://example.com/foo/api/v1/posts',
(string) $this->mock->getLastRequest()->getUri()
);
}
|
The host that is provided can have a path as well.
|
testWithHostAndPath
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/FactoryTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/FactoryTest.php
|
Apache-2.0
|
protected function willSeeResource($resource, $status = 200, array $headers = [])
{
$json = json_api()->encoder()->serializeData($resource);
return $this->willSeeResponse($json, $status, $headers);
}
|
@param $resource
@param int $status
@param array $headers
@return Response
|
willSeeResource
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/TestCase.php
|
Apache-2.0
|
protected function willSeeIdentifiers($data, $status = 200, array $headers = [])
{
$json = json_api()->encoder()->serializeIdentifiers($data);
return $this->willSeeResponse($json, $status, $headers);
}
|
@param $data
@param int $status
@param array $headers
@return Response
|
willSeeIdentifiers
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/TestCase.php
|
Apache-2.0
|
protected function willSeeResponse(?array $json = null, $status = 200, array $headers = [])
{
if ($json) {
$body = json_encode($json);
$headers['Content-Type'] = 'application/vnd.api+json';
$headers['Content-Length'] = mb_strlen($body, '8bit');
} else {
$body = null;
}
$this->mock->append(
$response = new Response($status, $headers, $body)
);
return $response;
}
|
@param array|null $json
@param int $status
@param array $headers
@return Response
|
willSeeResponse
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/TestCase.php
|
Apache-2.0
|
protected function willSeeErrors(array $errors, $status = 400)
{
$errors = $errors ?: ['errors' => []];
return $this->willSeeResponse($errors, $status);
}
|
@param array $errors
@param int $status
@return Response
|
willSeeErrors
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/TestCase.php
|
Apache-2.0
|
protected function assertRequested($method, $path)
{
$uri = 'http://example.com/api/v1' . $path;
$request = $this->mock->getLastRequest();
$this->assertEquals($method, $request->getMethod());
$this->assertEquals($uri, (string) $request->getUri(), 'request uri');
}
|
@param $method
@param $path
@return void
|
assertRequested
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/TestCase.php
|
Apache-2.0
|
protected function assertHeader($key, $expected)
{
$request = $this->mock->getLastRequest();
$actual = $request->getHeaderLine($key);
$this->assertSame($expected, $actual);
}
|
@param $key
@param $expected
@return void
|
assertHeader
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/TestCase.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/TestCase.php
|
Apache-2.0
|
public function test()
{
$resource = [
'type' => 'posts',
'id' => (string) $this->post->getRouteKey(),
'attributes' => [
'createdAt' => $this->post->created_at->toJSON(),
'updatedAt' => $this->post->updated_at->toJSON(),
'deletedAt' => null,
'title' => $this->post->title,
'slug' => $this->post->slug,
'content' => $this->post->content,
'published' => $this->post->published_at,
],
'relationships' => [
'author' => [
'data' => [
'type' => 'users',
'id' => (string) $this->post->author_id,
],
],
],
];
$expected = $this->willSeeResource($this->post);
$actual = $this->client->withIncludePaths('author')->updateRecord($this->post);
$this->assertSame($expected, $actual, 'http response');
$this->assertRequested('PATCH', "/posts/{$this->post->getRouteKey()}");
$this->assertHeader('Accept', 'application/vnd.api+json');
$this->assertHeader('Content-Type', 'application/vnd.api+json');
$this->assertSentDocument(['data' => $resource]);
}
|
By default when updating a record we expect:
- Any relationship without a `data` key to be removed.
- Links to be removed from relationships.
- Links to be removed from the resource.
- Included resources to be removed.
This is because the JSON API spec states that all relationships that are sent
for an update request MUST contain a data key.
For links, we should not send them by default because if we use our JSON API
config for an external API, the links refer to that external API not our
server.
|
test
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/UpdateTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/UpdateTest.php
|
Apache-2.0
|
public function testWithLinksAndIncluded()
{
$self = "http://localhost/api/v1/posts/{$this->post->getRouteKey()}";
$resource = [
'type' => 'posts',
'id' => (string) $this->post->getRouteKey(),
'attributes' => [
'createdAt' => $this->post->created_at->toJSON(),
'updatedAt' => $this->post->updated_at->toJSON(),
'deletedAt' => null,
'title' => $this->post->title,
'slug' => $this->post->slug,
'content' => $this->post->content,
'published' => $this->post->published_at,
],
'relationships' => [
'author' => [
'data' => [
'type' => 'users',
'id' => (string) $this->post->author_id,
],
'links' => [
'self' => "{$self}/relationships/author",
'related' => "{$self}/author",
],
],
],
'links' => [
'self' => $self,
],
];
$self = "http://localhost/api/v1/users/{$this->post->author->getRouteKey()}";
$author = [
'type' => 'users',
'id' => (string) $this->post->author->getRouteKey(),
'attributes' => [
'createdAt' => $this->post->author->created_at->toJSON(),
'updatedAt' => $this->post->author->updated_at->toJSON(),
'name' => $this->post->author->name,
'email' => $this->post->author->email,
],
'relationships' => [
'phone' => [
'links' => [
'self' => "{$self}/relationships/phone",
'related' => "{$self}/phone",
],
],
'roles' => [
'links' => [
'self' => "{$self}/relationships/roles",
'related' => "{$self}/roles",
],
],
],
'links' => [
'self' => 'http://localhost/api/v1/users/1',
],
];
$this->willSeeResource($this->post);
$this->client
->withIncludePaths('author')
->withCompoundDocuments()
->withLinks()
->updateRecord($this->post);
$this->assertSentDocument([
'data' => $resource,
'included' => [$author],
]);
}
|
Test that we can set the client to send both links and included resources.
We still need to strip out any relationships that do not have data
because these are not allowed by the spec.
|
testWithLinksAndIncluded
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/UpdateTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/UpdateTest.php
|
Apache-2.0
|
public function testWithIncludedAndWithoutLinks()
{
$resource = [
'type' => 'posts',
'id' => (string) $this->post->getRouteKey(),
'attributes' => [
'createdAt' => $this->post->created_at->toJSON(),
'updatedAt' => $this->post->updated_at->toJSON(),
'deletedAt' => null,
'title' => $this->post->title,
'slug' => $this->post->slug,
'content' => $this->post->content,
'published' => $this->post->published_at,
],
'relationships' => [
'author' => [
'data' => [
'type' => 'users',
'id' => (string) $this->post->author_id,
],
],
],
];
$author = [
'type' => 'users',
'id' => (string) $this->post->author->getRouteKey(),
'attributes' => [
'createdAt' => $this->post->author->created_at->toJSON(),
'updatedAt' => $this->post->author->updated_at->toJSON(),
'name' => $this->post->author->name,
'email' => $this->post->author->email,
],
];
$this->willSeeResource($this->post);
$this->client
->withIncludePaths('author')
->withCompoundDocuments()
->updateRecord($this->post);
$this->assertSentDocument([
'data' => $resource,
'included' => [$author],
]);
}
|
Test that we can set the client to send both links and included resources.
We still need to strip out any relationships that do not have data
because these are not allowed by the spec.
|
testWithIncludedAndWithoutLinks
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/Client/UpdateTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/Client/UpdateTest.php
|
Apache-2.0
|
public function testDefault(): void
{
$post = factory(Post::class)->create();
$uri = url('/api/v1/posts', $post);
$this->withDefaultNegotiator()
->getJson($uri)
->assertStatus(200);
}
|
Test that a default content negotiator can be specified at the
API level.
|
testDefault
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ContentNegotiation/CustomTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ContentNegotiation/CustomTest.php
|
Apache-2.0
|
public function testApiDefaultDoesNotOverrideResourceNegotiator(): void
{
Storage::fake('local');
$path = UploadedFile::fake()->image('avatar.jpg')->store('avatars');
$avatar = factory(Avatar::class)->create(compact('path'));
$uri = url('/api/v1/avatars', $avatar);
$this
->withoutExceptionHandling()
->withDefaultNegotiator()
->get($uri, ['Accept' => 'image/*'])
->assertSuccessful()
->assertHeader('Content-Type', $avatar->media_type);
}
|
If there is a default content negotiator, the resource negotiator
should still be used if there is one.
|
testApiDefaultDoesNotOverrideResourceNegotiator
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ContentNegotiation/CustomTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ContentNegotiation/CustomTest.php
|
Apache-2.0
|
public function testEmptyContentLengthHeader()
{
$headers = $this->transformHeadersToServerVars(['Content-Length' => '']);
$this->call('GET', "/api/v1/posts", [], [], [], $headers)->assertStatus(200);
}
|
Have observed browsers sending a "Content-Length" header with an empty string on GET
requests. If no content is expected, this should be interpreted as not having
any content.
|
testEmptyContentLengthHeader
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ContentNegotiation/DefaultTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ContentNegotiation/DefaultTest.php
|
Apache-2.0
|
public function testAcceptable()
{
$this->get('/api/v1/posts', ['Accept' => 'text/plain'])
->assertStatus(200)
->assertHeader('Content-Type', 'text/plain; charset=UTF-8');
}
|
Can request an alternative media-type that is in our configuration.
Note that the Symfony response automatically appends the charset to the
content-type header if it starts with `text/`.
|
testAcceptable
|
php
|
cloudcreativity/laravel-json-api
|
tests/lib/Integration/ContentNegotiation/DefaultTest.php
|
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Integration/ContentNegotiation/DefaultTest.php
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.