Skip to content
This repository has been archived by the owner on Mar 31, 2020. It is now read-only.

Commit

Permalink
Add partial unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
duncte123 committed Dec 17, 2018
1 parent 5c7d8da commit 04a2bfb
Show file tree
Hide file tree
Showing 9 changed files with 212 additions and 10 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ APP_NAME=Straas
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://straas.local
APP_URL=https://straas.local
APP_TIMEZONE=GMT

LOG_CHANNEL=stack
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
Homestead.json
Homestead.yaml
.env
database.sqlite
9 changes: 5 additions & 4 deletions app/Http/Controllers/Api/StringController.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,20 @@

use App\Http\Controllers\Controller;
use App\Models\StringValue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Validation\UnauthorizedException;

class StringController extends Controller
{
public function fromUser(Request $request)
public function fromUser(Request $request): array
{
return [
'strings' => $request->user()->strings,
];
}

public function createString(Request $request)
public function createString(Request $request): Model
{
$validated = $this->validate($request, [
'value' => 'required|string|max:50',
Expand All @@ -53,7 +54,7 @@ public function createString(Request $request)
return $string;
}

public function updateString(Request $request, $id)
public function updateString(Request $request, $id): Model
{
$validated = $this->validate($request, [
'value' => 'required|string|max:50',
Expand All @@ -70,7 +71,7 @@ public function updateString(Request $request, $id)
return $string;
}

public function deleteString(Request $request, $id)
public function deleteString(Request $request, $id): array
{
$string = StringValue::query()->findOrFail($id);

Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"type": "project",
"require": {
"php": ">=7.1.3",
"ext-json": "*",
"laravel/lumen-framework": "5.7.*",
"vlucas/phpdotenv": "~2.2"
},
Expand Down
43 changes: 43 additions & 0 deletions database/factories/StringValueFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
/**
* MIT License
*
* Copyright (c) 2018 Duncan Sterken
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(App\Models\StringValue::class, function (Faker\Generator $faker) {
return [
'user_id' => factory(\App\Models\User::class)->create()->id,
'value' => $faker->unique()->word,
];
});
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@
|
*/

$factory->define(App\User::class, function (Faker\Generator $faker) {
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'token' => $faker->uuid,
];
});
2 changes: 2 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value="database.sqlite"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
</php>
Expand Down
133 changes: 133 additions & 0 deletions tests/StringTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php
/**
* MIT License
*
* Copyright (c) 2018 Duncan Sterken
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

use App\Models\StringValue;
use App\Models\User;
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;

class StringTest extends TestCase
{
use DatabaseMigrations, DatabaseTransactions;

/**
* @var User
*/
private $user;

public function setUp()
{
parent::setUp();

$this->user = factory(User::class)->create();
}

public function testUserCanRetrieveStrings()
{
/**
* @var \Illuminate\Database\Eloquent\Collection $stringsCollection
*/
$stringsCollection = factory(StringValue::class, 5)->create(['user_id' => $this->user->id]);

// Other users also have strings
factory(StringValue::class, 3)->create();

$strings = $stringsCollection->map(function (StringValue $s) {
return $s->toArray();
})->toArray();

$response = $this->request('GET', 'strings', $this->user)->decodeResponseJson()->strings;

$userStrings = collect($response)->map(function ($s) {
// Map the values to match the faker return
return [
'value' => $s->value,
'updated_at' => $s->updated_at,
'created_at' => $s->created_at,
'id' => $s->id,
];
})->toArray();

$this->assertCount(5, $strings);
$this->assertSameSize($strings, $userStrings);
$this->assertSame($strings, $userStrings);
}

public function testUserCanNotRetrieveStringsWhenNotLoggedIn()
{
$response = $this->request('GET', 'strings', 'bla', [], [
'Authorization' => 'Token InvalidToken',
]);

$response->assertResponseStatus(403);
}

public function testStringCreationWithValidParameters()
{
$data = [
'value' => str_random(),
];

$currentStrings = $this->user->strings()->get();

$response = $this->request('POST', 'strings', $this->user, $data);

$newStrings = $this->user->strings()->get();

$response->assertResponseStatus(200);
$this->assertCount(0, $currentStrings);
$this->assertCount(1, $newStrings);
}

public function testStringCreationFailsWhenStringIsTooLarge()
{
$data = [
'value' => str_random(51),
];

$response = $this->request('POST', 'strings', $this->user, $data);

$response->assertResponseStatus(422);
}

public function testUserCanDeleteOwnString()
{
$string = factory(StringValue::class)->create(['user_id' => $this->user->id]);

$response = $this->request('DELETE', "strings/{$string->id}", $this->user);

$response->assertResponseOk();
}

public function testUserCanNotDeleteOtherStrings()
{
$string = factory(StringValue::class)->create();

$response = $this->request('DELETE', "strings/{$string->id}", $this->user);

$response->assertResponseStatus(403);
}
}
26 changes: 24 additions & 2 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<?php

use App\Models\User;

/**
* MIT License
*
Expand All @@ -23,7 +26,6 @@
* SOFTWARE.
*
*/

abstract class TestCase extends Laravel\Lumen\Testing\TestCase
{
/**
Expand All @@ -33,6 +35,26 @@ abstract class TestCase extends Laravel\Lumen\Testing\TestCase
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
return require __DIR__ . '/../bootstrap/app.php';
}

protected function request($method, $uri, $user, array $data = [], array $headers = [])
{
$headers = array_merge(['Accept' => 'application/json'], $headers);

if ($user instanceof User) {
$headers['Authorization'] = 'Token ' . $user->token;
}

$request = $this->json($method, "api/$uri", $data, $headers);

return $request;
}

protected function decodeResponseJson($assoc = false)
{
$this->assertResponseOk();

return json_decode($this->response->getContent(), $assoc);
}
}

0 comments on commit 04a2bfb

Please sign in to comment.