Finish re-working tests to run on test database

This commit is contained in:
Jonny Barnes 2021-08-31 12:28:00 +01:00
parent 09fc211623
commit 1abca77bdc
50 changed files with 535 additions and 265 deletions

View file

@ -7,7 +7,7 @@ APP_LOG_LEVEL=warning
DB_CONNECTION=pgsql DB_CONNECTION=pgsql
DB_HOST=127.0.0.1 DB_HOST=127.0.0.1
DB_PORT=5432 DB_PORT=5432
DB_DATABASE=jbuktest DB_DATABASE=jbukdev_testing
DB_USERNAME=postgres DB_USERNAME=postgres
DB_PASSWORD=postgres DB_PASSWORD=postgres

View file

@ -1,17 +0,0 @@
APP_ENV=testing
APP_DEBUG=true
APP_KEY=base64:6DJhvZLVjE6dD4Cqrteh+6Z5vZlG+v/soCKcDHLOAH0=
APP_URL=http://jonnybarnes.localhost
APP_LONGURL=jonnybarnes.localhost
APP_SHORTURL=jmb.localhost
DB_CONNECTION=travis
CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync
SCOUT_DRIVER=pgsql
DISPLAY_NAME='Travis Test'
USER_NAME=travis

View file

@ -11,11 +11,11 @@ jobs:
services: services:
postgres: postgres:
image: postgres:13.1 image: postgres:13.2
env: env:
POSTGRES_USER: postgres POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres POSTGRES_PASSWORD: postgres
POSTGRES_DB: jbuktest POSTGRES_DB: jbukdev_testing
ports: ports:
- 5432:5432 - 5432:5432

View file

@ -24,16 +24,6 @@ class ParseCachedWebMentions extends Command
*/ */
protected $description = 'Re-parse the webmentions cached HTML'; protected $description = 'Re-parse the webmentions cached HTML';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/** /**
* Execute the console command. * Execute the console command.
* *
@ -41,15 +31,15 @@ class ParseCachedWebMentions extends Command
*/ */
public function handle(FileSystem $filesystem) public function handle(FileSystem $filesystem)
{ {
$HTMLfiles = $filesystem->allFiles(storage_path() . '/HTML'); $htmlFiles = $filesystem->allFiles(storage_path() . '/HTML');
foreach ($HTMLfiles as $file) { foreach ($htmlFiles as $file) {
if ($file->getExtension() != 'backup') { //we dont want to parse.backup files if ($file->getExtension() !== 'backup') { //we dont want to parse `.backup` files
$filepath = $file->getPathname(); $filepath = $file->getPathname();
$this->info('Loading HTML from: ' . $filepath); $this->info('Loading HTML from: ' . $filepath);
$html = $filesystem->get($filepath); $html = $filesystem->get($filepath);
$url = $this->URLFromFilename($filepath); $url = $this->urlFromFilename($filepath);
$microformats = \Mf2\parse($html, $url);
$webmention = WebMention::where('source', $url)->firstOrFail(); $webmention = WebMention::where('source', $url)->firstOrFail();
$microformats = \Mf2\parse($html, $url);
$webmention->mf2 = json_encode($microformats); $webmention->mf2 = json_encode($microformats);
$webmention->save(); $webmention->save();
$this->info('Saved the microformats to the database.'); $this->info('Saved the microformats to the database.');
@ -63,12 +53,12 @@ class ParseCachedWebMentions extends Command
* @param string * @param string
* @return string * @return string
*/ */
private function URLFromFilename(string $filepath): string private function urlFromFilename(string $filepath): string
{ {
$dir = mb_substr($filepath, mb_strlen(storage_path() . '/HTML/')); $dir = mb_substr($filepath, mb_strlen(storage_path() . '/HTML/'));
$url = str_replace(['http/', 'https/'], ['http://', 'https://'], $dir); $url = str_replace(['http/', 'https/'], ['http://', 'https://'], $dir);
if (mb_substr($url, -10) == 'index.html') { if (mb_substr($url, -10) === 'index.html') {
$url = mb_substr($url, 0, mb_strlen($url) - 10); $url = mb_substr($url, 0, -10);
} }
return $url; return $url;

View file

@ -7,16 +7,10 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\Article; use App\Models\Article;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View; use Illuminate\View\View;
class ArticlesController extends Controller class ArticlesController extends Controller
{ {
/**
* List the articles that can be edited.
*
* @return \Illuminate\View\View
*/
public function index(): View public function index(): View
{ {
$posts = Article::select('id', 'title', 'published')->orderBy('id', 'desc')->get(); $posts = Article::select('id', 'title', 'published')->orderBy('id', 'desc')->get();
@ -24,11 +18,6 @@ class ArticlesController extends Controller
return view('admin.articles.index', ['posts' => $posts]); return view('admin.articles.index', ['posts' => $posts]);
} }
/**
* Show the new article form.
*
* @return \Illuminate\View\View
*/
public function create(): View public function create(): View
{ {
$message = session('message'); $message = session('message');
@ -36,11 +25,6 @@ class ArticlesController extends Controller
return view('admin.articles.create', ['message' => $message]); return view('admin.articles.create', ['message' => $message]);
} }
/**
* Process an incoming request for a new article and save it.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(): RedirectResponse public function store(): RedirectResponse
{ {
//if a `.md` is attached use that for the main content. //if a `.md` is attached use that for the main content.
@ -49,42 +33,21 @@ class ArticlesController extends Controller
$content = $file->fread($file->getSize()); $content = $file->fread($file->getSize());
} }
$main = $content ?? request()->input('main'); $main = $content ?? request()->input('main');
$article = Article::create( Article::create([
[
'url' => request()->input('url'), 'url' => request()->input('url'),
'title' => request()->input('title'), 'title' => request()->input('title'),
'main' => $main, 'main' => $main,
'published' => request()->input('published') ?? 0, 'published' => request()->input('published') ?? 0,
] ]);
);
return redirect('/admin/blog'); return redirect('/admin/blog');
} }
/** public function edit(Article $article): View
* Show the edit form for an existing article.
*
* @param int $articleId
* @return \Illuminate\View\View
*/
public function edit(int $articleId): View
{ {
$post = Article::select( return view('admin.articles.edit', ['article' => $article]);
'title',
'main',
'url',
'published'
)->where('id', $articleId)->get();
return view('admin.articles.edit', ['id' => $articleId, 'post' => $post]);
} }
/**
* Process an incoming request to edit an article.
*
* @param int $articleId
* @return \Illuminate\Http\RedirectResponse
*/
public function update(int $articleId): RedirectResponse public function update(int $articleId): RedirectResponse
{ {
$article = Article::find($articleId); $article = Article::find($articleId);
@ -97,12 +60,6 @@ class ArticlesController extends Controller
return redirect('/admin/blog'); return redirect('/admin/blog');
} }
/**
* Process a request to delete an aricle.
*
* @param int $articleId
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(int $articleId): RedirectResponse public function destroy(int $articleId): RedirectResponse
{ {
Article::where('id', $articleId)->delete(); Article::where('id', $articleId)->delete();

View file

@ -59,18 +59,14 @@ class ArticlesController extends Controller
* We only have the ID, work out post title, year and month * We only have the ID, work out post title, year and month
* and redirect to it. * and redirect to it.
* *
* @param int $idFromUrl * @param string $idFromUrl
* @return RedirectResponse * @return RedirectResponse
*/ */
public function onlyIdInUrl(int $idFromUrl): RedirectResponse public function onlyIdInUrl(string $idFromUrl): RedirectResponse
{ {
$realId = resolve(Numbers::class)->b60tonum((string) $idFromUrl); $realId = resolve(Numbers::class)->b60tonum($idFromUrl);
try {
$article = Article::findOrFail($realId); $article = Article::findOrFail($realId);
} catch (ModelNotFoundException $exception) {
abort(404);
}
return redirect($article->link); return redirect($article->link);
} }

View file

@ -7,6 +7,7 @@ namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable; use Cviebrock\EloquentSluggable\Sluggable;
use Eloquent; use Eloquent;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
@ -58,6 +59,7 @@ use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
*/ */
class Article extends Model class Article extends Model
{ {
use HasFactory;
use Sluggable; use Sluggable;
use SoftDeletes; use SoftDeletes;

View file

@ -6,6 +6,7 @@ namespace App\Models;
use Eloquent; use Eloquent;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
@ -35,6 +36,8 @@ use Illuminate\Support\Carbon;
*/ */
class Contact extends Model class Contact extends Model
{ {
use HasFactory;
/** /**
* The database table used by the model. * The database table used by the model.
* *

View file

@ -6,6 +6,7 @@ namespace App\Models;
use Eloquent; use Eloquent;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
@ -41,6 +42,8 @@ use Illuminate\Support\Str;
*/ */
class Media extends Model class Media extends Model
{ {
use HasFactory;
/** /**
* The table associated with the model. * The table associated with the model.
* *
@ -62,7 +65,7 @@ class Media extends Model
*/ */
public function note(): BelongsTo public function note(): BelongsTo
{ {
return $this->belongsTo('App\Models\Note'); return $this->belongsTo(Note::class);
} }
/** /**
@ -118,7 +121,7 @@ class Media extends Model
$filenameParts = explode('.', $path); $filenameParts = explode('.', $path);
array_pop($filenameParts); array_pop($filenameParts);
return ltrim(array_reduce($filenameParts, function ($carry, $item) { return ltrim(array_reduce($filenameParts, static function ($carry, $item) {
return $carry . '.' . $item; return $carry . '.' . $item;
}, ''), '.'); }, ''), '.');
} }

View file

@ -51,7 +51,7 @@ class Tag extends Model
*/ */
public function notes() public function notes()
{ {
return $this->belongsToMany('App\Models\Note'); return $this->belongsToMany(Note::class);
} }
/** /**

View file

@ -8,6 +8,7 @@ use App\Traits\FilterHtml;
use Codebird\Codebird; use Codebird\Codebird;
use Eloquent; use Eloquent;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Filesystem\Filesystem; use Illuminate\Filesystem\Filesystem;
@ -55,6 +56,7 @@ use Jonnybarnes\WebmentionsParser\Exceptions\AuthorshipParserException;
class WebMention extends Model class WebMention extends Model
{ {
use FilterHtml; use FilterHtml;
use HasFactory;
/** /**
* The database table used by the model. * The database table used by the model.

View file

@ -0,0 +1,34 @@
<?php
namespace Database\Factories;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
class ArticleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Article::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'titleurl' => $this->faker->slug(3),
'title' => $this->faker->words(3, true),
'main' => $this->faker->paragraphs(4, true),
'published' => 1,
'created_at' => Carbon::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString(),
];
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Database\Factories;
use App\Models\Contact;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
class ContactFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Contact::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'nick' => mb_strtolower($this->faker->firstName),
'name' => $this->faker->name(),
'homepage' => $this->faker->url,
'twitter' => mb_strtolower($this->faker->firstName),
'facebook' => $this->faker->randomNumber(5),
'created_at' => Carbon::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString(),
];
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Database\Factories;
use App\Models\Media;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
class MediaFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Media::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'path' => 'media/' . $this->faker->uuid . '.jpg',
'type' => 'image',
'created_at' => Carbon::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString(),
];
}
}

View file

@ -3,6 +3,7 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Note; use App\Models\Note;
use Exception;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
@ -19,10 +20,11 @@ class NoteFactory extends Factory
* Define the model's default state. * Define the model's default state.
* *
* @return array * @return array
* @throws Exception
*/ */
public function definition() public function definition()
{ {
$now = Carbon::now()->subDays(rand(5, 15)); $now = Carbon::now()->subDays(random_int(5, 15));
return [ return [
'note' => $this->faker->paragraph, 'note' => $this->faker->paragraph,

View file

@ -0,0 +1,31 @@
<?php
namespace Database\Factories;
use App\Models\WebMention;
use Illuminate\Database\Eloquent\Factories\Factory;
class WebMentionFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = WebMention::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'source' => $this->faker->url,
'target' => url('notes/1'),
'type' => 'reply',
'content' => $this->faker->paragraph,
];
}
}

View file

@ -16,6 +16,7 @@
</testsuites> </testsuites>
<php> <php>
<env name="APP_ENV" value="testing"/> <env name="APP_ENV" value="testing"/>
<env name="DB_DATABASE" value="jbukdev_testing"/>
<env name="BCRYPT_ROUNDS" value="4"/> <env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/> <env name="CACHE_DRIVER" value="array"/>
<env name="MAIL_DRIVER" value="array"/> <env name="MAIL_DRIVER" value="array"/>

View file

@ -3,28 +3,28 @@
@section('title')Edit Article « Admin CP « @stop @section('title')Edit Article « Admin CP « @stop
@section('content') @section('content')
<form action="/admin/blog/{{ $id }}" method="post" accept-charset="utf-8" class="admin-form form"> <form action="/admin/blog/{{ $article->id }}" method="post" accept-charset="utf-8" class="admin-form form">
{{ csrf_field() }} {{ csrf_field() }}
{{ method_field('PUT') }} {{ method_field('PUT') }}
<div> <div>
<label for="title">Title (URL):</label> <label for="title">Title (URL):</label>
<input type="text" name="title" id="title" value="{!! $post['0']['title'] !!}"> <input type="text" name="title" id="title" value="{!! $article->title !!}">
<input type="url" name="url" id="url" value="{!! $post['0']['url'] !!}"> <input type="url" name="url" id="url" value="{!! $article->url !!}">
</div> </div>
<div> <div>
<label for="main">Main:</label> <label for="main">Main:</label>
<textarea name="main" id="main">{{ $post['0']['main'] }}</textarea> <textarea name="main" id="main">{!! $article->main !!}</textarea>
</div> </div>
<div class="form-row"> <div class="form-row">
<label for="published">Published:</label> <label for="published">Published:</label>
<input type="checkbox" name="published" value="1"@if($post['0']['published'] == '1') checked="checked"@endif> <input type="checkbox" name="published" value="1"@if($article->published == '1') checked="checked"@endif>
</div> </div>
<div> <div>
<button type="submit" name="save">Save</button> <button type="submit" name="save">Save</button>
</div> </div>
</form> </form>
<hr> <hr>
<form action="/admin/blog/{{ $id }}" method="post" class="admin-form form"> <form action="/admin/blog/{{ $article->id }}" method="post" class="admin-form form">
{{ csrf_field() }} {{ csrf_field() }}
{{ method_field('DELETE') }} {{ method_field('DELETE') }}
<div> <div>

View file

@ -65,7 +65,7 @@ Route::group(['domain' => config('url.longurl')], function () {
Route::get('/', [AdminArticlesController::class, 'index']); Route::get('/', [AdminArticlesController::class, 'index']);
Route::get('/create', [AdminArticlesController::class, 'create']); Route::get('/create', [AdminArticlesController::class, 'create']);
Route::post('/', [AdminArticlesController::class, 'store']); Route::post('/', [AdminArticlesController::class, 'store']);
Route::get('/{id}/edit', [AdminArticlesController::class, 'edit']); Route::get('/{article}/edit', [AdminArticlesController::class, 'edit']);
Route::put('/{id}', [AdminArticlesController::class, 'update']); Route::put('/{id}', [AdminArticlesController::class, 'update']);
Route::delete('/{id}', [AdminArticlesController::class, 'destroy']); Route::delete('/{id}', [AdminArticlesController::class, 'destroy']);
}); });

View file

@ -25,8 +25,8 @@ class ActivityStreamTest extends TestCase
/** @test */ /** @test */
public function requestForNoteIncludesActivityStreamData(): void public function requestForNoteIncludesActivityStreamData(): void
{ {
$note = Note::find(11); $note = Note::factory()->create();
$response = $this->get('/notes/B', ['Accept' => 'application/activity+json']); $response = $this->get($note->longurl, ['Accept' => 'application/activity+json']);
$response->assertHeader('Content-Type', 'application/activity+json'); $response->assertHeader('Content-Type', 'application/activity+json');
$response->assertJson([ $response->assertJson([
'@context' => 'https://www.w3.org/ns/activitystreams', '@context' => 'https://www.w3.org/ns/activitystreams',

View file

@ -4,15 +4,16 @@ declare(strict_types=1);
namespace Tests\Feature\Admin; namespace Tests\Feature\Admin;
use App\Models\Article;
use App\Models\User; use App\Models\User;
use Faker\Factory; use Faker\Factory;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase; use Tests\TestCase;
class ArticlesTest extends TestCase class ArticlesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function adminArticlesPageLoads(): void public function adminArticlesPageLoads(): void
@ -76,9 +77,12 @@ class ArticlesTest extends TestCase
public function articleCanLoadFormToEditArticle(): void public function articleCanLoadFormToEditArticle(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$article = Article::factory()->create([
'main' => 'This is *my* new blog. It uses `Markdown`.',
]);
$response = $this->actingAs($user) $response = $this->actingAs($user)
->get('/admin/blog/1/edit'); ->get('/admin/blog/' . $article->id . '/edit');
$response->assertSeeText('This is *my* new blog. It uses `Markdown`.'); $response->assertSeeText('This is *my* new blog. It uses `Markdown`.');
} }
@ -86,9 +90,10 @@ class ArticlesTest extends TestCase
public function adminCanEditArticle(): void public function adminCanEditArticle(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$article = Article::factory()->create();
$this->actingAs($user) $this->actingAs($user)
->post('/admin/blog/1', [ ->post('/admin/blog/' . $article->id, [
'_method' => 'PUT', '_method' => 'PUT',
'title' => 'My New Blog', 'title' => 'My New Blog',
'main' => 'This article has been edited', 'main' => 'This article has been edited',
@ -103,13 +108,14 @@ class ArticlesTest extends TestCase
public function adminCanDeleteArticle(): void public function adminCanDeleteArticle(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$article = Article::factory()->create();
$this->actingAs($user) $this->actingAs($user)
->post('/admin/blog/1', [ ->post('/admin/blog/' . $article->id, [
'_method' => 'DELETE', '_method' => 'DELETE',
]); ]);
$this->assertSoftDeleted('articles', [ $this->assertSoftDeleted('articles', [
'title' => 'My New Blog', 'title' => $article->title,
]); ]);
} }
} }

View file

@ -4,13 +4,14 @@ declare(strict_types=1);
namespace Tests\Feature\Admin; namespace Tests\Feature\Admin;
use App\Models\MicropubClient;
use App\Models\User; use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class ClientsTest extends TestCase class ClientsTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function clientsPageLoads(): void public function clientsPageLoads(): void
@ -52,9 +53,12 @@ class ClientsTest extends TestCase
public function adminCanLoadEditFormForClient(): void public function adminCanLoadEditFormForClient(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$client = MicropubClient::factory()->create([
'client_url' => 'https://jbl5.dev/notes/new',
]);
$response = $this->actingAs($user) $response = $this->actingAs($user)
->get('/admin/clients/1/edit'); ->get('/admin/clients/' . $client->id . '/edit');
$response->assertSee('https://jbl5.dev/notes/new'); $response->assertSee('https://jbl5.dev/notes/new');
} }
@ -62,9 +66,10 @@ class ClientsTest extends TestCase
public function adminCanEditClient(): void public function adminCanEditClient(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$client = MicropubClient::factory()->create();
$this->actingAs($user) $this->actingAs($user)
->post('/admin/clients/1', [ ->post('/admin/clients/' . $client->id, [
'_method' => 'PUT', '_method' => 'PUT',
'client_url' => 'https://jbl5.dev/notes/new', 'client_url' => 'https://jbl5.dev/notes/new',
'client_name' => 'JBL5dev', 'client_name' => 'JBL5dev',
@ -79,9 +84,12 @@ class ClientsTest extends TestCase
public function adminCanDeleteClient(): void public function adminCanDeleteClient(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$client = MicropubClient::factory()->create([
'client_url' => 'https://jbl5.dev/notes/new',
]);
$this->actingAs($user) $this->actingAs($user)
->post('/admin/clients/1', [ ->post('/admin/clients/' . $client->id, [
'_method' => 'DELETE', '_method' => 'DELETE',
]); ]);
$this->assertDatabaseMissing('clients', [ $this->assertDatabaseMissing('clients', [

View file

@ -10,13 +10,13 @@ use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Tests\TestCase; use Tests\TestCase;
class ContactsTest extends TestCase class ContactsTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
protected function tearDown(): void protected function tearDown(): void
{ {
@ -66,8 +66,9 @@ class ContactsTest extends TestCase
public function adminCanSeeFormToEditContact(): void public function adminCanSeeFormToEditContact(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$contact = Contact::factory()->create();
$response = $this->actingAs($user)->get('/admin/contacts/1/edit'); $response = $this->actingAs($user)->get('/admin/contacts/' . $contact->id . '/edit');
$response->assertViewIs('admin.contacts.edit'); $response->assertViewIs('admin.contacts.edit');
} }
@ -75,8 +76,9 @@ class ContactsTest extends TestCase
public function adminCanUpdateContact(): void public function adminCanUpdateContact(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$contact = Contact::factory()->create();
$this->actingAs($user)->post('/admin/contacts/1', [ $this->actingAs($user)->post('/admin/contacts/' . $contact->id, [
'_method' => 'PUT', '_method' => 'PUT',
'name' => 'Tantek Celik', 'name' => 'Tantek Celik',
'nick' => 'tantek', 'nick' => 'tantek',
@ -96,8 +98,9 @@ class ContactsTest extends TestCase
$path = sys_get_temp_dir() . '/tantek.png'; $path = sys_get_temp_dir() . '/tantek.png';
$file = new UploadedFile($path, 'tantek.png', 'image/png', null, true); $file = new UploadedFile($path, 'tantek.png', 'image/png', null, true);
$user = User::factory()->make(); $user = User::factory()->make();
$contact = Contact::factory()->create();
$this->actingAs($user)->post('/admin/contacts/1', [ $this->actingAs($user)->post('/admin/contacts/' . $contact->id, [
'_method' => 'PUT', '_method' => 'PUT',
'name' => 'Tantek Celik', 'name' => 'Tantek Celik',
'nick' => 'tantek', 'nick' => 'tantek',
@ -115,8 +118,13 @@ class ContactsTest extends TestCase
public function adminCanDeleteContact(): void public function adminCanDeleteContact(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$contact = Contact::factory()->create(['nick' => 'tantek']);
$this->actingAs($user)->post('/admin/contacts/1', [ $this->assertDatabaseHas('contacts', [
'nick' => 'tantek',
]);
$this->actingAs($user)->post('/admin/contacts/' . $contact->id, [
'_method' => 'DELETE', '_method' => 'DELETE',
]); ]);
$this->assertDatabaseMissing('contacts', [ $this->assertDatabaseMissing('contacts', [
@ -132,7 +140,7 @@ class ContactsTest extends TestCase
<img class="u-photo" alt="" src="http://tantek.com/tantek.png"> <img class="u-photo" alt="" src="http://tantek.com/tantek.png">
</div> </div>
HTML; HTML;
$file = fopen(__DIR__ . '/../../aaron.png', 'r'); $file = fopen(__DIR__ . '/../../aaron.png', 'rb');
$mock = new MockHandler([ $mock = new MockHandler([
new Response(200, ['Content-Type' => 'text/html'], $html), new Response(200, ['Content-Type' => 'text/html'], $html),
new Response(200, ['Content-Type' => 'iamge/png'], $file), new Response(200, ['Content-Type' => 'iamge/png'], $file),
@ -141,8 +149,11 @@ class ContactsTest extends TestCase
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$this->app->instance(Client::class, $client); $this->app->instance(Client::class, $client);
$user = User::factory()->make(); $user = User::factory()->make();
$contact = Contact::factory()->create([
'homepage' => 'https://tantek.com',
]);
$this->actingAs($user)->get('/admin/contacts/1/getavatar'); $this->actingAs($user)->get('/admin/contacts/' . $contact->id . '/getavatar');
$this->assertFileEquals( $this->assertFileEquals(
__DIR__ . '/../../aaron.png', __DIR__ . '/../../aaron.png',
@ -160,10 +171,11 @@ class ContactsTest extends TestCase
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$this->app->instance(Client::class, $client); $this->app->instance(Client::class, $client);
$user = User::factory()->make(); $user = User::factory()->make();
$contact = Contact::factory()->create();
$response = $this->actingAs($user)->get('/admin/contacts/1/getavatar'); $response = $this->actingAs($user)->get('/admin/contacts/' . $contact->id . '/getavatar');
$response->assertRedirect('/admin/contacts/1/edit'); $response->assertRedirect('/admin/contacts/' . $contact->id . '/edit');
} }
/** @test */ /** @test */
@ -182,10 +194,11 @@ class ContactsTest extends TestCase
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$this->app->instance(Client::class, $client); $this->app->instance(Client::class, $client);
$user = User::factory()->make(); $user = User::factory()->make();
$contact = Contact::factory()->create();
$response = $this->actingAs($user)->get('/admin/contacts/1/getavatar'); $response = $this->actingAs($user)->get('/admin/contacts/' . $contact->id . '/getavatar');
$response->assertRedirect('/admin/contacts/1/edit'); $response->assertRedirect('/admin/contacts/' . $contact->id . '/edit');
} }
/** @test */ /** @test */

View file

@ -7,13 +7,13 @@ namespace Tests\Feature\Admin;
use App\Jobs\ProcessLike; use App\Jobs\ProcessLike;
use App\Models\Like; use App\Models\Like;
use App\Models\User; use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase; use Tests\TestCase;
class LikesTest extends TestCase class LikesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function likesPageLoads(): void public function likesPageLoads(): void
@ -55,9 +55,10 @@ class LikesTest extends TestCase
public function likeEditFormLoads(): void public function likeEditFormLoads(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$like = Like::factory()->create();
$response = $this->actingAs($user) $response = $this->actingAs($user)
->get('/admin/likes/1/edit'); ->get('/admin/likes/' . $like->id . '/edit');
$response->assertSee('Edit Like'); $response->assertSee('Edit Like');
} }
@ -66,9 +67,10 @@ class LikesTest extends TestCase
{ {
Queue::fake(); Queue::fake();
$user = User::factory()->make(); $user = User::factory()->make();
$like = Like::factory()->create();
$this->actingAs($user) $this->actingAs($user)
->post('/admin/likes/1', [ ->post('/admin/likes/' . $like->id, [
'_method' => 'PUT', '_method' => 'PUT',
'like_url' => 'https://example.com', 'like_url' => 'https://example.com',
]); ]);
@ -81,12 +83,12 @@ class LikesTest extends TestCase
/** @test */ /** @test */
public function adminCanDeleteLike(): void public function adminCanDeleteLike(): void
{ {
$like = Like::find(1); $like = Like::factory()->create();
$url = $like->url; $url = $like->url;
$user = User::factory()->make(); $user = User::factory()->make();
$this->actingAs($user) $this->actingAs($user)
->post('/admin/likes/1', [ ->post('/admin/likes/' . $like->id, [
'_method' => 'DELETE', '_method' => 'DELETE',
]); ]);
$this->assertDatabaseMissing('likes', [ $this->assertDatabaseMissing('likes', [

View file

@ -5,14 +5,15 @@ declare(strict_types=1);
namespace Tests\Feature\Admin; namespace Tests\Feature\Admin;
use App\Jobs\SendWebMentions; use App\Jobs\SendWebMentions;
use App\Models\Note;
use App\Models\User; use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
use Tests\TestCase; use Tests\TestCase;
class NotesTest extends TestCase class NotesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function notesPageLoads(): void public function notesPageLoads(): void
@ -49,8 +50,9 @@ class NotesTest extends TestCase
public function noteEditFormLoads(): void public function noteEditFormLoads(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$note = Note::factory()->create();
$response = $this->actingAs($user)->get('/admin/notes/1/edit'); $response = $this->actingAs($user)->get('/admin/notes/' . $note->id . '/edit');
$response->assertViewIs('admin.notes.edit'); $response->assertViewIs('admin.notes.edit');
} }
@ -59,8 +61,9 @@ class NotesTest extends TestCase
{ {
Queue::fake(); Queue::fake();
$user = User::factory()->make(); $user = User::factory()->make();
$note = Note::factory()->create();
$this->actingAs($user)->post('/admin/notes/1', [ $this->actingAs($user)->post('/admin/notes/' . $note->id, [
'_method' => 'PUT', '_method' => 'PUT',
'content' => 'An edited note', 'content' => 'An edited note',
'webmentions' => true, 'webmentions' => true,
@ -76,12 +79,13 @@ class NotesTest extends TestCase
public function adminCanDeleteNote(): void public function adminCanDeleteNote(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$note = Note::factory()->create();
$this->actingAs($user)->post('/admin/notes/1', [ $this->actingAs($user)->post('/admin/notes/' . $note->id, [
'_method' => 'DELETE', '_method' => 'DELETE',
]); ]);
$this->assertSoftDeleted('notes', [ $this->assertSoftDeleted('notes', [
'id' => '1', 'id' => $note->id,
]); ]);
} }
} }

View file

@ -4,13 +4,14 @@ declare(strict_types=1);
namespace Tests\Feature\Admin; namespace Tests\Feature\Admin;
use App\Models\Place;
use App\Models\User; use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class PlacesTest extends TestCase class PlacesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function placesPageLoads(): void public function placesPageLoads(): void
@ -51,8 +52,9 @@ class PlacesTest extends TestCase
public function editPlacePageLoads(): void public function editPlacePageLoads(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$place = Place::factory()->create();
$response = $this->actingAs($user)->get('/admin/places/1/edit'); $response = $this->actingAs($user)->get('/admin/places/' . $place->id . '/edit');
$response->assertViewIs('admin.places.edit'); $response->assertViewIs('admin.places.edit');
} }
@ -60,8 +62,11 @@ class PlacesTest extends TestCase
public function adminCanUpdatePlace(): void public function adminCanUpdatePlace(): void
{ {
$user = User::factory()->make(); $user = User::factory()->make();
$place = Place::factory()->create([
'name' => 'The Bridgewater Pub',
]);
$this->actingAs($user)->post('/admin/places/1', [ $this->actingAs($user)->post('/admin/places/' . $place->id, [
'_method' => 'PUT', '_method' => 'PUT',
'name' => 'The Bridgewater', 'name' => 'The Bridgewater',
'description' => 'Who uses “Pub” anyway', 'description' => 'Who uses “Pub” anyway',

View file

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\Article;
use Jonnybarnes\IndieWeb\Numbers;
use Tests\TestCase; use Tests\TestCase;
class ArticlesTest extends TestCase class ArticlesTest extends TestCase
@ -18,22 +20,26 @@ class ArticlesTest extends TestCase
/** @test */ /** @test */
public function singleArticlePageLoads() public function singleArticlePageLoads()
{ {
$response = $this->get('/blog/' . date('Y') . '/' . date('m') . '/some-code-i-did'); $article = Article::factory()->create();
$response = $this->get($article->link);
$response->assertViewIs('articles.show'); $response->assertViewIs('articles.show');
} }
/** @test */ /** @test */
public function wrongDateInUrlRedirectsToCorrectDate() public function wrongDateInUrlRedirectsToCorrectDate()
{ {
$response = $this->get('/blog/1900/01/some-code-i-did'); $article = Article::factory()->create();
$response->assertRedirect('/blog/' . date('Y') . '/' . date('m') . '/some-code-i-did'); $response = $this->get('/blog/1900/01/' . $article->titleurl);
$response->assertRedirect('/blog/' . date('Y') . '/' . date('m') . '/' . $article->titleurl);
} }
/** @test */ /** @test */
public function oldUrlsWithIdAreRedirected() public function oldUrlsWithIdAreRedirected()
{ {
$response = $this->get('/blog/s/2'); $article = Article::factory()->create();
$response->assertRedirect('/blog/' . date('Y') . '/' . date('m') . '/some-code-i-did'); $num60Id = resolve(Numbers::class)->numto60($article->id);
$response = $this->get('/blog/s/' . $num60Id);
$response->assertRedirect($article->link);
} }
/** @test */ /** @test */

View file

@ -6,14 +6,15 @@ namespace Tests\Feature;
use App\Jobs\ProcessBookmark; use App\Jobs\ProcessBookmark;
use App\Jobs\SyndicateBookmarkToTwitter; use App\Jobs\SyndicateBookmarkToTwitter;
use Illuminate\Foundation\Testing\DatabaseTransactions; use App\Models\Bookmark;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
use Tests\TestCase; use Tests\TestCase;
use Tests\TestToken; use Tests\TestToken;
class BookmarksTest extends TestCase class BookmarksTest extends TestCase
{ {
use DatabaseTransactions, TestToken; use RefreshDatabase, TestToken;
/** @test */ /** @test */
public function bookmarksPageLoadsWithoutError(): void public function bookmarksPageLoadsWithoutError(): void
@ -25,7 +26,8 @@ class BookmarksTest extends TestCase
/** @test */ /** @test */
public function singleBookmarkPageLoadsWithoutError(): void public function singleBookmarkPageLoadsWithoutError(): void
{ {
$response = $this->get('/bookmarks/1'); $bookmark = Bookmark::factory()->create();
$response = $this->get('/bookmarks/' . $bookmark->id);
$response->assertViewIs('bookmarks.show'); $response->assertViewIs('bookmarks.show');
} }

View file

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\Contact;
use App\Models\Note;
use Tests\TestCase; use Tests\TestCase;
class BridgyPosseTest extends TestCase class BridgyPosseTest extends TestCase
@ -11,9 +13,15 @@ class BridgyPosseTest extends TestCase
/** @test */ /** @test */
public function notesWeWantCopiedToTwitterShouldHaveNecessaryMarkup(): void public function notesWeWantCopiedToTwitterShouldHaveNecessaryMarkup(): void
{ {
$response = $this->get('/notes/4'); Contact::factory()->create([
'nick' => 'joe',
'twitter' => 'joe__',
]);
$note = Note::factory()->create(['note' => 'Hi @joe']);
$response = $this->get($note->longurl);
$html = $response->content(); $html = $response->content();
$this->assertTrue(is_string(mb_stristr($html, 'p-bridgy-twitter-content'))); $this->assertStringContainsString('p-bridgy-twitter-content', $html);
} }
} }

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\Contact;
use Tests\TestCase; use Tests\TestCase;
class ContactsTest extends TestCase class ContactsTest extends TestCase
@ -26,6 +27,9 @@ class ContactsTest extends TestCase
*/ */
public function contactPageShouldFallbackToDefaultProfilePic(): void public function contactPageShouldFallbackToDefaultProfilePic(): void
{ {
Contact::factory()->create([
'nick' => 'tantek',
]);
$response = $this->get('/contacts/tantek'); $response = $this->get('/contacts/tantek');
$response->assertViewHas('image', '/assets/profile-images/default-image'); $response->assertViewHas('image', '/assets/profile-images/default-image');
} }
@ -37,6 +41,10 @@ class ContactsTest extends TestCase
*/ */
public function contactPageShouldUseSpecificProfilePicIfPresent(): void public function contactPageShouldUseSpecificProfilePicIfPresent(): void
{ {
Contact::factory()->create([
'nick' => 'aaron',
'homepage' => 'https://aaronparecki.com',
]);
$response = $this->get('/contacts/aaron'); $response = $this->get('/contacts/aaron');
$response->assertViewHas('image', '/assets/profile-images/aaronparecki.com/image'); $response->assertViewHas('image', '/assets/profile-images/aaronparecki.com/image');
} }

View file

@ -11,7 +11,7 @@ use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
use Jonnybarnes\WebmentionsParser\Authorship; use Jonnybarnes\WebmentionsParser\Authorship;
use Tests\TestCase; use Tests\TestCase;
@ -19,7 +19,7 @@ use Tests\TestToken;
class LikesTest extends TestCase class LikesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
use TestToken; use TestToken;
/** @test */ /** @test */
@ -32,7 +32,8 @@ class LikesTest extends TestCase
/** @test */ /** @test */
public function singleLikePageHasCorrectView(): void public function singleLikePageHasCorrectView(): void
{ {
$response = $this->get('/likes/1'); $like = Like::factory()->create();
$response = $this->get('/likes/' . $like->id);
$response->assertViewIs('likes.show'); $response->assertViewIs('likes.show');
} }

View file

@ -5,17 +5,16 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use Faker\Factory; use Faker\Factory;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Jobs\{SendWebMentions, SyndicateNoteToTwitter}; use App\Jobs\{SendWebMentions, SyndicateNoteToTwitter};
use App\Models\{Media, Place}; use App\Models\{Media, Note, Place};
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
use Tests\TestCase; use Tests\{TestCase, TestToken};
use Tests\TestToken;
class MicropubControllerTest extends TestCase class MicropubControllerTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
use TestToken; use TestToken;
/** @test */ /** @test */
@ -57,6 +56,11 @@ class MicropubControllerTest extends TestCase
/** @test */ /** @test */
public function micropubClientsCanRequestKnownNearbyPlaces(): void public function micropubClientsCanRequestKnownNearbyPlaces(): void
{ {
Place::factory()->create([
'name' => 'The Bridgewater Pub',
'latitude' => '53.5',
'longitude' => '-2.38',
]);
$response = $this->get('/api/post?q=geo:53.5,-2.38', ['HTTP_Authorization' => 'Bearer ' . $this->getToken()]); $response = $this->get('/api/post?q=geo:53.5,-2.38', ['HTTP_Authorization' => 'Bearer ' . $this->getToken()]);
$response->assertJson(['places' => [['slug' => 'the-bridgewater-pub']]]); $response->assertJson(['places' => [['slug' => 'the-bridgewater-pub']]]);
} }
@ -64,12 +68,12 @@ class MicropubControllerTest extends TestCase
/** /**
* @test * @test
* @todo Add uncertainty parameter * @todo Add uncertainty parameter
*/ *
public function micropubClientsCanRequestKnownNearbyPlacesWithUncertaintyParameter(): void public function micropubClientsCanRequestKnownNearbyPlacesWithUncertaintyParameter(): void
{ {
$response = $this->get('/api/post?q=geo:53.5,-2.38', ['HTTP_Authorization' => 'Bearer ' . $this->getToken()]); $response = $this->get('/api/post?q=geo:53.5,-2.38', ['HTTP_Authorization' => 'Bearer ' . $this->getToken()]);
$response->assertJson(['places' => [['slug' => 'the-bridgewater-pub']]]); $response->assertJson(['places' => [['slug' => 'the-bridgewater-pub']]]);
} }*/
/** @test */ /** @test */
public function returnEmptyResultWhenMicropubClientRequestsKnownNearbyPlaces(): void public function returnEmptyResultWhenMicropubClientRequestsKnownNearbyPlaces(): void
@ -459,11 +463,12 @@ class MicropubControllerTest extends TestCase
/** @test */ /** @test */
public function micropubClientApiRequestUpdatesExistingNote(): void public function micropubClientApiRequestUpdatesExistingNote(): void
{ {
$note = Note::factory()->create();
$response = $this->postJson( $response = $this->postJson(
'/api/post', '/api/post',
[ [
'action' => 'update', 'action' => 'update',
'url' => config('app.url') . '/notes/A', 'url' => $note->longurl,
'replace' => [ 'replace' => [
'content' => ['replaced content'], 'content' => ['replaced content'],
], ],
@ -478,11 +483,12 @@ class MicropubControllerTest extends TestCase
/** @test */ /** @test */
public function micropubClientApiRequestUpdatesNoteSyndicationLinks(): void public function micropubClientApiRequestUpdatesNoteSyndicationLinks(): void
{ {
$note = Note::factory()->create();
$response = $this->postJson( $response = $this->postJson(
'/api/post', '/api/post',
[ [
'action' => 'update', 'action' => 'update',
'url' => config('app.url') . '/notes/A', 'url' => $note->longurl,
'add' => [ 'add' => [
'syndication' => [ 'syndication' => [
'https://www.swarmapp.com/checkin/123', 'https://www.swarmapp.com/checkin/123',
@ -504,11 +510,12 @@ class MicropubControllerTest extends TestCase
/** @test */ /** @test */
public function micropubClientApiRequestAddsImageToNote(): void public function micropubClientApiRequestAddsImageToNote(): void
{ {
$note = Note::factory()->create();
$response = $this->postJson( $response = $this->postJson(
'/api/post', '/api/post',
[ [
'action' => 'update', 'action' => 'update',
'url' => config('app.url') . '/notes/A', 'url' => $note->longurl,
'add' => [ 'add' => [
'photo' => ['https://example.org/photo.jpg'], 'photo' => ['https://example.org/photo.jpg'],
], ],
@ -564,11 +571,12 @@ class MicropubControllerTest extends TestCase
/** @test */ /** @test */
public function micropubClientApiRequestReturnsErrorWhenTryingToUpdateUnsupportedProperty(): void public function micropubClientApiRequestReturnsErrorWhenTryingToUpdateUnsupportedProperty(): void
{ {
$note = Note::factory()->create();
$response = $this->postJson( $response = $this->postJson(
'/api/post', '/api/post',
[ [
'action' => 'update', 'action' => 'update',
'url' => config('app.url') . '/notes/A', 'url' => $note->longurl,
'morph' => [ // or any other unsupported update type 'morph' => [ // or any other unsupported update type
'syndication' => ['https://www.swarmapp.com/checkin/123'], 'syndication' => ['https://www.swarmapp.com/checkin/123'],
], ],
@ -602,11 +610,12 @@ class MicropubControllerTest extends TestCase
/** @test */ /** @test */
public function micropubClientApiRequestCanReplaceNoteSyndicationTargets(): void public function micropubClientApiRequestCanReplaceNoteSyndicationTargets(): void
{ {
$note = Note::factory()->create();
$response = $this->postJson( $response = $this->postJson(
'/api/post', '/api/post',
[ [
'action' => 'update', 'action' => 'update',
'url' => config('app.url') . '/notes/B', 'url' => $note->longurl,
'replace' => [ 'replace' => [
'syndication' => [ 'syndication' => [
'https://www.swarmapp.com/checkin/the-id', 'https://www.swarmapp.com/checkin/the-id',

View file

@ -4,21 +4,22 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\Note;
use Tests\TestCase; use Tests\TestCase;
class NotesControllerTest extends TestCase class NotesControllerTest extends TestCase
{ {
/* /**
* Test the `/notes` page returns 200, this should * Test the `/notes` page returns 200, this should
* mean the database is being hit. * mean the database is being hit.
* *
* @test * @test
* */
public function notesPageLoads(): void public function notesPageLoads(): void
{ {
$response = $this->get('/notes'); $response = $this->get('/notes');
$response->assertStatus(200); $response->assertStatus(200);
}*/ }
/** /**
* Test a specific note. * Test a specific note.
@ -27,10 +28,12 @@ class NotesControllerTest extends TestCase
*/ */
public function specificNotePageLoads(): void public function specificNotePageLoads(): void
{ {
$response = $this->get('/notes/D'); $note = Note::factory()->create();
$response = $this->get($note->longurl);
$response->assertViewHas('note'); $response->assertViewHas('note');
} }
/** @todo */
/* @test * /* @test *
public function noteReplyingToTweet(): void public function noteReplyingToTweet(): void
{ {
@ -45,8 +48,9 @@ class NotesControllerTest extends TestCase
*/ */
public function oldNoteUrlsRedirect(): void public function oldNoteUrlsRedirect(): void
{ {
$response = $this->get('/note/11'); $note = Note::factory()->create();
$response->assertRedirect(config('app.url') . '/notes/B'); $response = $this->get('/note/' . $note->id);
$response->assertRedirect($note->longurl);
} }
/** /**

View file

@ -6,13 +6,14 @@ namespace Tests\Feature;
use App\Models\WebMention; use App\Models\WebMention;
use Illuminate\FileSystem\FileSystem; use Illuminate\FileSystem\FileSystem;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Artisan;
use Tests\TestCase; use Tests\TestCase;
class ParseCachedWebMentionsTest extends TestCase class ParseCachedWebMentionsTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
protected function setUp(): void protected function setUp(): void
{ {
@ -27,6 +28,16 @@ class ParseCachedWebMentionsTest extends TestCase
/** @test */ /** @test */
public function parseWebmentionHtml(): void public function parseWebmentionHtml(): void
{ {
$webmentionAaron = WebMention::factory()->create([
'source' => 'https://aaronpk.localhost/reply/1',
'created_at' => Carbon::now()->subDays(5),
'updated_at' => Carbon::now()->subDays(5),
]);
$webmentionTantek = WebMention::factory()->create([
'source' => 'http://tantek.com/',
'created_at' => Carbon::now()->subDays(5),
'updated_at' => Carbon::now()->subDays(5),
]);
$this->assertFileExists(storage_path('HTML') . '/https/aaronpk.localhost/reply/1'); $this->assertFileExists(storage_path('HTML') . '/https/aaronpk.localhost/reply/1');
$this->assertFileExists(storage_path('HTML') . '/http/tantek.com/index.html'); $this->assertFileExists(storage_path('HTML') . '/http/tantek.com/index.html');
$htmlAaron = file_get_contents(storage_path('HTML') . '/https/aaronpk.localhost/reply/1'); $htmlAaron = file_get_contents(storage_path('HTML') . '/https/aaronpk.localhost/reply/1');
@ -40,8 +51,9 @@ class ParseCachedWebMentionsTest extends TestCase
Artisan::call('webmentions:parsecached'); Artisan::call('webmentions:parsecached');
$webmentionAaron = WebMention::find(1); $webmentionAaron = WebMention::find($webmentionAaron->id);
$webmentionTantek = WebMention::find(2); $webmentionTantek = WebMention::find($webmentionTantek->id);
$this->assertTrue($webmentionAaron->updated_at->gt($webmentionAaron->created_at)); $this->assertTrue($webmentionAaron->updated_at->gt($webmentionAaron->created_at));
$this->assertTrue($webmentionTantek->updated_at->gt($webmentionTantek->created_at)); $this->assertTrue($webmentionTantek->updated_at->gt($webmentionTantek->created_at));
} }

View file

@ -27,8 +27,8 @@ class PlacesTest extends TestCase
*/ */
public function singlePlacePageLoads(): void public function singlePlacePageLoads(): void
{ {
$place = Place::where('slug', 'the-bridgewater-pub')->first(); $place = Place::factory()->create();
$response = $this->get('/places/the-bridgewater-pub'); $response = $this->get($place->longurl);
$response->assertViewHas('place', $place); $response->assertViewHas('place', $place);
} }

View file

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Jobs\DownloadWebMention; use App\Jobs\DownloadWebMention;
use App\Models\WebMention;
use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
use Tests\TestCase; use Tests\TestCase;
@ -16,6 +17,8 @@ class ReDownloadWebMentionsTest extends TestCase
{ {
Queue::fake(); Queue::fake();
WebMention::factory()->create();
Artisan::call('webmentions:redownload'); Artisan::call('webmentions:redownload');
Queue::assertPushed(DownloadWebMention::class); Queue::assertPushed(DownloadWebMention::class);

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\Note;
use Tests\TestCase; use Tests\TestCase;
class SearchControllerTest extends TestCase class SearchControllerTest extends TestCase
@ -11,6 +12,9 @@ class SearchControllerTest extends TestCase
/** @test */ /** @test */
public function searchPageReturnsResult(): void public function searchPageReturnsResult(): void
{ {
Note::factory()->create([
'note' => 'I love [duckduckgo.com](https://duckduckgo.com)',
]);
$response = $this->get('/search?terms=love'); $response = $this->get('/search?terms=love');
$response->assertSee('duckduckgo.com'); $response->assertSee('duckduckgo.com');
} }

View file

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Jobs\ProcessWebMention; use App\Jobs\ProcessWebMention;
use App\Models\Note;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
use Tests\TestCase; use Tests\TestCase;
@ -73,13 +74,15 @@ class WebMentionsControllerTest extends TestCase
} }
/** @test */ /** @test */
public function legitimateWebmentionTriggersProcesswebmentionJob(): void public function legitimateWebmentionTriggersProcessWebmentionJob(): void
{ {
Queue::fake(); Queue::fake();
$note = Note::factory()->create();
$response = $this->call('POST', '/webmention', [ $response = $this->call('POST', '/webmention', [
'source' => 'https://example.org/post/123', 'source' => 'https://example.org/post/123',
'target' => config('app.url') . '/notes/B' 'target' => $note->longurl,
]); ]);
$response->assertStatus(202); $response->assertStatus(202);

View file

@ -5,12 +5,13 @@ declare(strict_types=1);
namespace Tests\Unit; namespace Tests\Unit;
use App\Models\Article; use App\Models\Article;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Tests\TestCase; use Tests\TestCase;
class ArticlesTest extends TestCase class ArticlesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function titleSlugIsGeneratedAutomatically(): void public function titleSlugIsGeneratedAutomatically(): void
@ -64,6 +65,12 @@ class ArticlesTest extends TestCase
/** @test */ /** @test */
public function dateScopeReturnsExpectedArticles(): void public function dateScopeReturnsExpectedArticles(): void
{ {
Article::factory()->create([
'created_at' => Carbon::now()->subYear()->toDateTimeString(),
'updated_at' => Carbon::now()->subYear()->toDateTimeString(),
]);
Article::factory()->create();
$yearAndMonth = Article::date(date('Y'), date('m'))->get(); $yearAndMonth = Article::date(date('Y'), date('m'))->get();
$this->assertTrue(count($yearAndMonth) === 1); $this->assertTrue(count($yearAndMonth) === 1);

View file

@ -19,7 +19,7 @@ class ProcessBookmarkJobTest extends TestCase
/** @test */ /** @test */
public function screenshotAndArchiveLinkAreSavedByJob(): void public function screenshotAndArchiveLinkAreSavedByJob(): void
{ {
$bookmark = Bookmark::find(1); $bookmark = Bookmark::factory()->create();
$uuid = Uuid::uuid4(); $uuid = Uuid::uuid4();
$service = $this->createMock(BookmarkService::class); $service = $this->createMock(BookmarkService::class);
$service->method('saveScreenshot') $service->method('saveScreenshot')
@ -40,7 +40,7 @@ class ProcessBookmarkJobTest extends TestCase
/** @test */ /** @test */
public function archiveLinkSavedAsNullWhenExceptionThrown(): void public function archiveLinkSavedAsNullWhenExceptionThrown(): void
{ {
$bookmark = Bookmark::find(1); $bookmark = Bookmark::factory()->create();
$uuid = Uuid::uuid4(); $uuid = Uuid::uuid4();
$service = $this->createMock(BookmarkService::class); $service = $this->createMock(BookmarkService::class);
$service->method('saveScreenshot') $service->method('saveScreenshot')

View file

@ -44,7 +44,7 @@ class ProcessWebMentionJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$note = Note::find(1); $note = Note::factory()->create();
$source = 'https://example.org/mention/1/'; $source = 'https://example.org/mention/1/';
$job = new ProcessWebMention($note, $source); $job = new ProcessWebMention($note, $source);
@ -70,7 +70,7 @@ class ProcessWebMentionJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$note = Note::find(1); $note = Note::factory()->create();
$source = 'https://example.org/mention/1/'; $source = 'https://example.org/mention/1/';
$job = new ProcessWebMention($note, $source); $job = new ProcessWebMention($note, $source);
@ -103,7 +103,7 @@ class ProcessWebMentionJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$note = Note::find(14); $note = Note::factory()->create();
$source = 'https://aaronpk.localhost/reply/1'; $source = 'https://aaronpk.localhost/reply/1';
$job = new ProcessWebMention($note, $source); $job = new ProcessWebMention($note, $source);
@ -135,7 +135,7 @@ class ProcessWebMentionJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$note = Note::find(14); $note = Note::factory()->create();
$source = 'https://example.org/reply/1'; $source = 'https://example.org/reply/1';
$webmention = new WebMention(); $webmention = new WebMention();
$webmention->source = $source; $webmention->source = $source;
@ -172,7 +172,7 @@ class ProcessWebMentionJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$note = Note::find(14); $note = Note::factory()->create();
$source = 'https://example.org/reply/1'; $source = 'https://example.org/reply/1';
$webmention = new WebMention(); $webmention = new WebMention();
$webmention->source = $source; $webmention->source = $source;
@ -209,7 +209,7 @@ class ProcessWebMentionJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$note = Note::find(14); $note = Note::factory()->create();
$source = 'https://example.org/reply/1'; $source = 'https://example.org/reply/1';
$webmention = new WebMention(); $webmention = new WebMention();
$webmention->source = $source; $webmention->source = $source;

View file

@ -10,18 +10,20 @@ use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class SyndicateBookmarkToTwitterJobTest extends TestCase class SyndicateBookmarkToTwitterJobTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function weSendBookmarksToTwitter(): void public function weSendBookmarksToTwitter(): void
{ {
$faker = \Faker\Factory::create();
$randomNumber = $faker->randomNumber();
$json = json_encode([ $json = json_encode([
'url' => 'https://twitter.com/123' 'url' => 'https://twitter.com/' . $randomNumber
]); ]);
$mock = new MockHandler([ $mock = new MockHandler([
new Response(201, ['Content-Type' => 'application/json'], $json), new Response(201, ['Content-Type' => 'application/json'], $json),
@ -29,13 +31,12 @@ class SyndicateBookmarkToTwitterJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$bookmark = Bookmark::find(1); $bookmark = Bookmark::factory()->create();
$job = new SyndicateBookmarkToTwitter($bookmark); $job = new SyndicateBookmarkToTwitter($bookmark);
$job->handle($client); $job->handle($client);
$this->assertDatabaseHas('bookmarks', [ $this->assertDatabaseHas('bookmarks', [
'id' => 1, 'syndicates' => '{"twitter": "https://twitter.com/' . $randomNumber . '"}',
'syndicates' => '{"twitter": "https://twitter.com/123"}',
]); ]);
} }
} }

View file

@ -8,18 +8,20 @@ use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class SyndicateNoteToTwitterJobTest extends TestCase class SyndicateNoteToTwitterJobTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function weSyndicateNotesToTwitter(): void public function weSyndicateNotesToTwitter(): void
{ {
$faker = \Faker\Factory::create();
$randomNumber = $faker->randomNumber();
$json = json_encode([ $json = json_encode([
'url' => 'https://twitter.com/i/web/status/123' 'url' => 'https://twitter.com/i/web/status/' . $randomNumber,
]); ]);
$mock = new MockHandler([ $mock = new MockHandler([
new Response(201, ['Content-Type' => 'application/json'], $json), new Response(201, ['Content-Type' => 'application/json'], $json),
@ -27,13 +29,12 @@ class SyndicateNoteToTwitterJobTest extends TestCase
$handler = HandlerStack::create($mock); $handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]); $client = new Client(['handler' => $handler]);
$note = Note::find(1); $note = Note::factory()->create();
$job = new SyndicateNoteToTwitter($note); $job = new SyndicateNoteToTwitter($note);
$job->handle($client); $job->handle($client);
$this->assertDatabaseHas('notes', [ $this->assertDatabaseHas('notes', [
'id' => 1, 'tweet_id' => $randomNumber,
'tweet_id' => '123',
]); ]);
} }
} }

View file

@ -5,16 +5,20 @@ declare(strict_types=1);
namespace Tests\Unit; namespace Tests\Unit;
use App\Models\Media; use App\Models\Media;
use App\Models\Note;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class MediaTest extends TestCase class MediaTest extends TestCase
{ {
use RefreshDatabase;
/** @test */ /** @test */
public function getTheNoteThatMediaInstanceBelongsTo(): void public function getTheNoteThatMediaInstanceBelongsTo(): void
{ {
$media = Media::find(1); $media = Media::factory()->for(Note::factory())->create();
$note = $media->note;
$this->assertInstanceOf('App\Models\Note', $note); $this->assertInstanceOf(Note::class, $media->note);
} }
/** @test */ /** @test */

View file

@ -6,14 +6,18 @@ namespace Tests\Unit;
use App\Models\MicropubClient; use App\Models\MicropubClient;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class MicropubClientsTest extends TestCase class MicropubClientsTest extends TestCase
{ {
use RefreshDatabase;
/** @test */ /** @test */
public function weCanGetNotesRelatingToClient(): void public function weCanGetNotesRelatingToClient(): void
{ {
$client = MicropubClient::find(1); $client = MicropubClient::factory()->make();
$this->assertInstanceOf(Collection::class, $client->notes); $this->assertInstanceOf(Collection::class, $client->notes);
} }
} }

View file

@ -4,18 +4,18 @@ declare(strict_types=1);
namespace Tests\Unit; namespace Tests\Unit;
use App\Models\{Contact, Media, Note, Place, Tag};
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use App\Models\{Media, Note, Tag};
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase; use Tests\TestCase;
class NotesTest extends TestCase class NotesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** /**
* Test the getNoteAttribute method. This will then also call the * Test the getNoteAttribute method. This will then also call the
@ -28,7 +28,9 @@ class NotesTest extends TestCase
{ {
// phpcs:ignore // phpcs:ignore
$expected = '<p>Having a <a rel="tag" class="p-category" href="/notes/tagged/beer">#beer</a> at the local. 🍺</p>' . PHP_EOL; $expected = '<p>Having a <a rel="tag" class="p-category" href="/notes/tagged/beer">#beer</a> at the local. 🍺</p>' . PHP_EOL;
$note = Note::find(2); $note = Note::factory([
'note' => 'Having a #beer at the local. 🍺',
])->create();
$this->assertEquals($expected, $note->note); $this->assertEquals($expected, $note->note);
} }
@ -42,7 +44,16 @@ class NotesTest extends TestCase
{ {
// phpcs:ignore // phpcs:ignore
$expected = '<p>Hi <span class="u-category h-card mini-h-card"><a class="u-url p-name" href="http://tantek.com">Tantek Çelik</a><span class="hovercard"> <a class="u-url" href="https://twitter.com/t"><img class="social-icon" src="/assets/img/social-icons/twitter.svg"> t</a><img class="u-photo" alt="" src="/assets/profile-images/default-image"></span></span></p>' . PHP_EOL; $expected = '<p>Hi <span class="u-category h-card mini-h-card"><a class="u-url p-name" href="http://tantek.com">Tantek Çelik</a><span class="hovercard"> <a class="u-url" href="https://twitter.com/t"><img class="social-icon" src="/assets/img/social-icons/twitter.svg"> t</a><img class="u-photo" alt="" src="/assets/profile-images/default-image"></span></span></p>' . PHP_EOL;
$note = Note::find(4); Contact::factory()->create([
'nick' => 'tantek',
'name' => 'Tantek Çelik',
'homepage' => 'http://tantek.com',
'twitter' => 't',
'facebook' => null,
]);
$note = Note::factory()->create([
'note' => 'Hi @tantek',
]);
$this->assertEquals($expected, $note->note); $this->assertEquals($expected, $note->note);
} }
@ -56,7 +67,16 @@ class NotesTest extends TestCase
{ {
// phpcs:ignore // phpcs:ignore
$expected = '<p>Hi <span class="u-category h-card mini-h-card"><a class="u-url p-name" href="https://aaronparecki.com">Aaron Parecki</a><span class="hovercard"><a class="u-url" href="https://www.facebook.com/123456"><img class="social-icon" src="/assets/img/social-icons/facebook.svg"> Facebook</a> <img class="u-photo" alt="" src="/assets/profile-images/aaronparecki.com/image"></span></span></p>' . PHP_EOL; $expected = '<p>Hi <span class="u-category h-card mini-h-card"><a class="u-url p-name" href="https://aaronparecki.com">Aaron Parecki</a><span class="hovercard"><a class="u-url" href="https://www.facebook.com/123456"><img class="social-icon" src="/assets/img/social-icons/facebook.svg"> Facebook</a> <img class="u-photo" alt="" src="/assets/profile-images/aaronparecki.com/image"></span></span></p>' . PHP_EOL;
$note = Note::find(5); Contact::factory()->create([
'nick' => 'aaron',
'name' => 'Aaron Parecki',
'homepage' => 'https://aaronparecki.com',
'twitter' => null,
'facebook' => 123456,
]);
$note = Note::factory()->create([
'note' => 'Hi @aaron',
]);
$this->assertEquals($expected, $note->note); $this->assertEquals($expected, $note->note);
} }
@ -69,13 +89,16 @@ class NotesTest extends TestCase
public function twitterLinkIsCreatedWhenNoContactFound(): void public function twitterLinkIsCreatedWhenNoContactFound(): void
{ {
$expected = '<p>Hi <a href="https://twitter.com/bob">@bob</a></p>' . PHP_EOL; $expected = '<p>Hi <a href="https://twitter.com/bob">@bob</a></p>' . PHP_EOL;
$note = Note::find(6); $note = Note::factory()->create([
'note' => 'Hi @bob',
]);
$this->assertEquals($expected, $note->note); $this->assertEquals($expected, $note->note);
} }
/** @test */ /** @test */
public function shorturlMethodReturnsExpectedValue(): void public function shorturlMethodReturnsExpectedValue(): void
{ {
Note::factory(14)->create();
$note = Note::find(14); $note = Note::find(14);
$this->assertEquals(config('app.shorturl') . '/notes/E', $note->shorturl); $this->assertEquals(config('app.shorturl') . '/notes/E', $note->shorturl);
} }
@ -83,7 +106,13 @@ class NotesTest extends TestCase
/** @test */ /** @test */
public function weGetLatitudeLongitudeValuesOfAssociatedPlaceOfNote(): void public function weGetLatitudeLongitudeValuesOfAssociatedPlaceOfNote(): void
{ {
$note = Note::find(2); // should be having beer at bridgewater note $place = Place::factory()->create([
'latitude' => '53.4983',
'longitude' => '-2.3805',
]);
$note = Note::factory()->create([
'place_id' => $place->id,
]);
$this->assertEquals('53.4983', $note->latitude); $this->assertEquals('53.4983', $note->latitude);
$this->assertEquals('-2.3805', $note->longitude); $this->assertEquals('-2.3805', $note->longitude);
} }
@ -91,7 +120,7 @@ class NotesTest extends TestCase
/** @test */ /** @test */
public function whenNoAssociatedPlaceWeGetNullForLatitudeLongitudeValues(): void public function whenNoAssociatedPlaceWeGetNullForLatitudeLongitudeValues(): void
{ {
$note = Note::find(5); $note = Note::factory()->create();
$this->assertNull($note->latitude); $this->assertNull($note->latitude);
$this->assertNull($note->longitude); $this->assertNull($note->longitude);
} }
@ -99,7 +128,14 @@ class NotesTest extends TestCase
/** @test */ /** @test */
public function weCanGetAddressAttributeForAssociatedPlace(): void public function weCanGetAddressAttributeForAssociatedPlace(): void
{ {
$note = Note::find(2); $place = Place::factory()->create([
'name' => 'The Bridgewater Pub',
'latitude' => '53.4983',
'longitude' => '-2.3805',
]);
$note = Note::factory()->create([
'place_id' => $place->id,
]);
$this->assertEquals('The Bridgewater Pub', $note->address); $this->assertEquals('The Bridgewater Pub', $note->address);
} }
@ -254,13 +290,13 @@ class NotesTest extends TestCase
/** @test */ /** @test */
public function addImageElementToNoteContentWhenMediaAssociated(): void public function addImageElementToNoteContentWhenMediaAssociated(): void
{ {
$media = new Media([ $media = Media::factory()->create([
'type' => 'image', 'type' => 'image',
'path' => 'test.png', 'path' => 'test.png',
]); ]);
$media->save(); $note = Note::factory()->create([
$note = new Note(['note' => 'A nice image']); 'note' => 'A nice image',
$note->save(); ]);
$note->media()->save($media); $note->media()->save($media);
$expected = "<p>A nice image</p> $expected = "<p>A nice image</p>
@ -271,13 +307,13 @@ class NotesTest extends TestCase
/** @test */ /** @test */
public function addVideoElementToNoteContentWhenMediaAssociated(): void public function addVideoElementToNoteContentWhenMediaAssociated(): void
{ {
$media = new Media([ $media = Media::factory()->create([
'type' => 'video', 'type' => 'video',
'path' => 'test.mkv', 'path' => 'test.mkv',
]); ]);
$media->save(); $note = Note::factory()->create([
$note = new Note(['note' => 'A nice video']); 'note' => 'A nice video',
$note->save(); ]);
$note->media()->save($media); $note->media()->save($media);
$expected = "<p>A nice video</p> $expected = "<p>A nice video</p>
@ -288,13 +324,13 @@ class NotesTest extends TestCase
/** @test */ /** @test */
public function addAudioElementToNoteContentWhenMediaAssociated(): void public function addAudioElementToNoteContentWhenMediaAssociated(): void
{ {
$media = new Media([ $media = Media::factory()->create([
'type' => 'audio', 'type' => 'audio',
'path' => 'test.flac', 'path' => 'test.flac',
]); ]);
$media->save(); $note = Note::factory()->create([
$note = new Note(['note' => 'Some nice audio']); 'note' => 'Some nice audio',
$note->save(); ]);
$note->media()->save($media); $note->media()->save($media);
$expected = "<p>Some nice audio</p> $expected = "<p>Some nice audio</p>
@ -326,7 +362,7 @@ class NotesTest extends TestCase
/** @test */ /** @test */
public function markdownContentGetsConverted(): void public function markdownContentGetsConverted(): void
{ {
$note = Note::create([ $note = Note::factory()->create([
'note' => 'The best search engine? https://duckduckgo.com', 'note' => 'The best search engine? https://duckduckgo.com',
]); ]);
@ -348,24 +384,21 @@ class NotesTest extends TestCase
]; ];
Cache::put('933662564587855877', $tempContent); Cache::put('933662564587855877', $tempContent);
$note = Note::find(1); $note = Note::factory()->create([
'in_reply_to' => 'https://twitter.com/someRando/status/933662564587855877'
]);
$this->assertSame($tempContent, $note->twitter); $this->assertSame($tempContent, $note->twitter);
} }
/** @test */ /** @test */
public function latitudeCanBeParsedFromPlainLocation(): void public function latitudeAndLongitudeCanBeParsedFromPlainLocation(): void
{ {
$note = Note::find(18); $note = Note::factory()->create([
'location' => '1.23,4.56',
]);
$this->assertSame(1.23, $note->latitude); $this->assertSame(1.23, $note->latitude);
}
/** @test */
public function longitudeCanBeParsedFromPlainLocation(): void
{
$note = Note::find(18);
$this->assertSame(4.56, $note->longitude); $this->assertSame(4.56, $note->longitude);
} }
@ -374,7 +407,9 @@ class NotesTest extends TestCase
{ {
Cache::put('1.23,4.56', '<span class="p-country-name">Antarctica</span>'); Cache::put('1.23,4.56', '<span class="p-country-name">Antarctica</span>');
$note = Note::find(18); $note = Note::factory()->create([
'location' => '1.23,4.56',
]);
$this->assertSame('<span class="p-country-name">Antarctica</span>', $note->address); $this->assertSame('<span class="p-country-name">Antarctica</span>', $note->address);
} }

View file

@ -4,55 +4,74 @@ declare(strict_types=1);
namespace Tests\Unit; namespace Tests\Unit;
use App\Models\Note;
use App\Models\Place; use App\Models\Place;
use App\Services\PlaceService; use App\Services\PlaceService;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException; use InvalidArgumentException;
use Tests\TestCase; use Tests\TestCase;
class PlacesTest extends TestCase class PlacesTest extends TestCase
{ {
use DatabaseTransactions; use RefreshDatabase;
/** @test */ /** @test */
public function canRetrieveAssociatedNotes(): void public function canRetrieveAssociatedNotes(): void
{ {
$place = Place::find(1); $place = Place::factory()->create();
Note::factory(5)->create([
'place_id' => $place->id,
]);
$this->assertInstanceOf(Collection::class, $place->notes); $this->assertInstanceOf(Collection::class, $place->notes);
$this->assertCount(5, $place->notes);
} }
/** @test */ /** @test */
public function nearMethodReturnsCollection(): void public function nearMethodReturnsCollection(): void
{ {
$nearby = Place::near((object) ['latitude' => 53.5, 'longitude' => -2.38], 1000)->get(); Place::factory()->create([
'name' => 'The Bridgewater Pub',
'latitude' => 53.4983,
'longitude' => -2.3805,
]);
$nearby = Place::near((object) ['latitude' => 53.5, 'longitude' => -2.38])->get();
$this->assertEquals('the-bridgewater-pub', $nearby[0]->slug); $this->assertEquals('the-bridgewater-pub', $nearby[0]->slug);
} }
/** @test */ /** @test */
public function getLongurl(): void public function getLongurl(): void
{ {
$place = Place::find(1); $place = Place::factory()->create([
'name' => 'The Bridgewater Pub',
]);
$this->assertEquals(config('app.url') . '/places/the-bridgewater-pub', $place->longurl); $this->assertEquals(config('app.url') . '/places/the-bridgewater-pub', $place->longurl);
} }
/** @test */ /** @test */
public function getShorturl() public function getShorturl()
{ {
$place = Place::find(1); $place = Place::factory()->create([
'name' => 'The Bridgewater Pub',
]);
$this->assertEquals(config('app.shorturl') . '/places/the-bridgewater-pub', $place->shorturl); $this->assertEquals(config('app.shorturl') . '/places/the-bridgewater-pub', $place->shorturl);
} }
/** @test */ /** @test */
public function getUri(): void public function getUri(): void
{ {
$place = Place::find(1); $place = Place::factory()->create([
'name' => 'The Bridgewater Pub',
]);
$this->assertEquals(config('app.url') . '/places/the-bridgewater-pub', $place->uri); $this->assertEquals(config('app.url') . '/places/the-bridgewater-pub', $place->uri);
} }
/** @test */ /** @test */
public function placeServiceReturnsExistingPlaceBasedOnExternalUrlsSearch(): void public function placeServiceReturnsExistingPlaceBasedOnExternalUrlsSearch(): void
{ {
Place::factory(10)->create();
$place = new Place(); $place = new Place();
$place->name = 'Temp Place'; $place->name = 'Temp Place';
$place->latitude = 37.422009; $place->latitude = 37.422009;
@ -65,8 +84,8 @@ class PlacesTest extends TestCase
'url' => ['https://www.openstreetmap.org/way/1234'], 'url' => ['https://www.openstreetmap.org/way/1234'],
] ]
]); ]);
$this->assertInstanceOf('App\Models\Place', $ret); // a place was returned $this->assertInstanceOf('App\Models\Place', $ret);
$this->assertCount(12, Place::all()); // still 12 places $this->assertCount(11, Place::all());
} }
/** @test */ /** @test */
@ -90,10 +109,23 @@ class PlacesTest extends TestCase
} }
/** @test */ /** @test */
public function placeServcieCanupdateExternalUrls(): void public function placeServiceCanUpdateExternalUrls(): void
{ {
$place = Place::find(1); $place = Place::factory()->create([
'name' => 'The Bridgewater Pub',
'latitude' => 53.4983,
'longitude' => -2.3805,
'external_urls' => '',
]);
$place->external_urls = 'https://www.openstreetmap.org/way/987654';
$place->external_urls = 'https://foursquare.com/v/123435/the-bridgewater-pub';
$place->save();
$place->external_urls = 'https://bridgewater.pub'; $place->external_urls = 'https://bridgewater.pub';
$this->assertEquals('{"osm":"https:\/\/www.openstreetmap.org\/way\/987654","foursquare":"https:\/\/foursquare.com\/v\/123435\/the-bridgewater-pub","default":"https:\/\/bridgewater.pub"}', $place->external_urls); $this->assertEquals(json_encode([
'default' => 'https://bridgewater.pub',
'osm' => 'https://www.openstreetmap.org/way/987654',
'foursquare' => 'https://foursquare.com/v/123435/the-bridgewater-pub',
]), $place->external_urls);
} }
} }

View file

@ -4,22 +4,31 @@ declare(strict_types=1);
namespace Tests\Unit; namespace Tests\Unit;
use App\Models\Bookmark;
use App\Models\Note;
use App\Models\Tag; use App\Models\Tag;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class TagsTest extends TestCase class TagsTest extends TestCase
{ {
use RefreshDatabase;
/** @test */ /** @test */
public function canGetAssociatedNotes(): void public function canGetAssociatedNotes(): void
{ {
$tag = Tag::find(1); // should be beer tag $note = Note::factory()->create();
$tag = Tag::factory()->create();
$note->tags()->save($tag);
$this->assertCount(1, $tag->notes); $this->assertCount(1, $tag->notes);
} }
/** @test */ /** @test */
public function canGetAssociatedBookmarks(): void public function canGetAssociatedBookmarks(): void
{ {
$tag = Tag::find(5); //should be first random tag for bookmarks $bookmark = Bookmark::factory()->create();
$tag = Tag::factory()->create();
$bookmark->tags()->save($tag);
$this->assertCount(1, $tag->bookmarks); $this->assertCount(1, $tag->bookmarks);
} }

View file

@ -4,19 +4,27 @@ declare(strict_types=1);
namespace Tests\Unit; namespace Tests\Unit;
use App\Models\Note;
use App\Models\WebMention; use App\Models\WebMention;
use Codebird\Codebird; use Codebird\Codebird;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Tests\TestCase; use Tests\TestCase;
class WebMentionTest extends TestCase class WebMentionTest extends TestCase
{ {
use RefreshDatabase;
/** @test */ /** @test */
public function commentableMethodLinksToNotes(): void public function commentableMethodLinksToNotes(): void
{ {
$webmention = WebMention::find(1); $note = Note::factory()->create();
$this->assertInstanceOf('App\Models\Note', $webmention->commentable); $webmention = WebMention::factory()->make([
'commentable_id' => $note->id,
'commentable_type' => Note::class,
]);
$this->assertInstanceOf(Note::class, $webmention->commentable);
} }
/** @test */ /** @test */

View file

@ -6,5 +6,5 @@
</div> </div>
<p>Posted by:</p> <p>Posted by:</p>
<div class="h-card"> <div class="h-card">
<a class="u-url" href="http://tantek.com"><span class="p-name">Tantek Celik</span></a> <a class="u-url" href="http://tantek.com"><span class="p-name">Tantek Çelik</span></a>
</div> </div>