1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 11:14:04 +00:00

Refactor tests to use pest() helper

This commit is contained in:
Samuel Štancl 2022-07-23 01:16:50 +02:00
parent 05f2a828a1
commit f9c9d8615f
26 changed files with 128 additions and 127 deletions

View file

@ -62,7 +62,7 @@ test('central helper runs callbacks in the central state', function () {
test('central helper returns the value from the callback', function () {
tenancy()->initialize(Tenant::create());
$this->assertSame('foo', tenancy()->central(function () {
pest()->assertSame('foo', tenancy()->central(function () {
return 'foo';
}));
});

View file

@ -42,7 +42,7 @@ test('database data is separated', function () {
$tenant1 = Tenant::create();
$tenant2 = Tenant::create();
$this->artisan('tenants:migrate');
pest()->artisan('tenants:migrate');
tenancy()->initialize($tenant1);
@ -175,7 +175,7 @@ test('filesystem data is separated', function () {
// Check that disk prefixes respect the root_override logic
expect(getDiskPrefix('local'))->toBe($expected_storage_path . '/app/');
expect(getDiskPrefix('public'))->toBe($expected_storage_path . '/app/public/');
$this->assertSame('tenant' . tenant('id') . '/', getDiskPrefix('s3'), '/');
pest()->assertSame('tenant' . tenant('id') . '/', getDiskPrefix('s3'), '/');
// Check suffixing logic
$new_storage_path = storage_path();

View file

@ -19,7 +19,7 @@ beforeEach(function () {
test('default tag is automatically applied', function () {
tenancy()->initialize(Tenant::create());
$this->assertArrayIsSubset([config('tenancy.cache.tag_base') . tenant('id')], cache()->tags('foo')->getTags()->getNames());
pest()->assertArrayIsSubset([config('tenancy.cache.tag_base') . tenant('id')], cache()->tags('foo')->getTags()->getNames());
});
test('tags are merged when array is passed', function () {
@ -39,14 +39,14 @@ test('tags are merged when string is passed', function () {
test('exception is thrown when zero arguments are passed to tags method', function () {
tenancy()->initialize(Tenant::create());
$this->expectException(\Exception::class);
pest()->expectException(\Exception::class);
cache()->tags();
});
test('exception is thrown when more than one argument is passed to tags method', function () {
tenancy()->initialize(Tenant::create());
$this->expectException(\Exception::class);
pest()->expectException(\Exception::class);
cache()->tags(1, 2);
});
@ -60,7 +60,7 @@ test('tags separate cache well enough', function () {
$tenant2 = Tenant::create();
tenancy()->initialize($tenant2);
$this->assertNotSame('bar', cache()->get('foo'));
pest()->assertNotSame('bar', cache()->get('foo'));
cache()->put('foo', 'xyz', 1);
expect(cache()->get('foo'))->toBe('xyz');
@ -76,7 +76,7 @@ test('invoking the cache helper works', function () {
$tenant2 = Tenant::create();
tenancy()->initialize($tenant2);
$this->assertNotSame('bar', cache('foo'));
pest()->assertNotSame('bar', cache('foo'));
cache(['foo' => 'xyz'], 1);
expect(cache('foo'))->toBe('xyz');

View file

@ -32,7 +32,7 @@ test('the underlying resolver is not touched when using the cached resolver', fu
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
DB::flushQueryLog();
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty
pest()->assertNotEmpty(DB::getQueryLog()); // not empty
DomainTenantResolver::$shouldCache = true;
@ -63,7 +63,7 @@ test('cache is invalidated when the tenant is updated', function () {
DB::flushQueryLog();
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty
pest()->assertNotEmpty(DB::getQueryLog()); // not empty
});
test('cache is invalidated when a tenants domain is changed', function () {
@ -87,9 +87,9 @@ test('cache is invalidated when a tenants domain is changed', function () {
DB::flushQueryLog();
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty
pest()->assertNotEmpty(DB::getQueryLog()); // not empty
DB::flushQueryLog();
expect($tenant->is(app(DomainTenantResolver::class)->resolve('bar')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty
pest()->assertNotEmpty(DB::getQueryLog()); // not empty
});

View file

@ -32,7 +32,7 @@ test('tenant can be identified by subdomain', function () {
expect(tenancy()->initialized)->toBeFalse();
$this
pest()
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('abc + xyz');
@ -53,7 +53,7 @@ test('tenant can be identified by domain', function () {
expect(tenancy()->initialized)->toBeFalse();
$this
pest()
->get('http://foobar.localhost/foo/abc/xyz')
->assertSee('abc + xyz');

View file

@ -46,7 +46,7 @@ test('migrate command doesnt change the db connection', function () {
expect(Schema::hasTable('users'))->toBeFalse();
expect($new_connection_name)->toEqual($old_connection_name);
$this->assertNotEquals('tenant', $new_connection_name);
pest()->assertNotEquals('tenant', $new_connection_name);
});
test('migrate command works without options', function () {
@ -140,7 +140,7 @@ test('install command works', function () {
mkdir($dir, 0777, true);
}
$this->artisan('tenancy:install');
pest()->artisan('tenancy:install');
expect(base_path('routes/tenant.php'))->toBeFile();
expect(base_path('config/tenancy.php'))->toBeFile();
expect(app_path('Providers/TenancyServiceProvider.php'))->toBeFile();
@ -174,7 +174,7 @@ test('run command with array of tenants works', function () {
$tenantId2 = Tenant::create()->getTenantKey();
Artisan::call('tenants:migrate-fresh');
$this->artisan("tenants:run foo --tenants=$tenantId1 --tenants=$tenantId2 --argument='a=foo' --option='b=bar' --option='c=xyz'")
pest()->artisan("tenants:run foo --tenants=$tenantId1 --tenants=$tenantId2 --argument='a=foo' --option='b=bar' --option='c=xyz'")
->expectsOutput('Tenant: ' . $tenantId1)
->expectsOutput('Tenant: ' . $tenantId2);
});
@ -186,7 +186,7 @@ function runCommandWorks(): void
Artisan::call('tenants:migrate', ['--tenants' => [$id]]);
test()->artisan("tenants:run foo --tenants=$id --argument='a=foo' --option='b=bar' --option='c=xyz'")
pest()->artisan("tenants:run foo --tenants=$id --argument='a=foo' --option='b=bar' --option='c=xyz'")
->expectsOutput("User's name is Test command")
->expectsOutput('foo')
->expectsOutput('xyz');

View file

@ -56,7 +56,7 @@ test('a tenants database cannot be created when the user already exists', functi
expect($manager->userExists($tenant->database()->getUsername()))->toBeTrue();
expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
$this->expectException(TenantDatabaseUserAlreadyExistsException::class);
pest()->expectException(TenantDatabaseUserAlreadyExistsException::class);
Event::fake([DatabaseCreated::class]);
$tenant2 = Tenant::create([

View file

@ -47,14 +47,14 @@ test('a domain can belong to only one tenant', function () {
$tenant2 = DomainTenant::create();
$this->expectException(DomainOccupiedByOtherTenantException::class);
pest()->expectException(DomainOccupiedByOtherTenantException::class);
$tenant2->domains()->create([
'domain' => 'foo.localhost',
]);
});
test('an exception is thrown if tenant cannot be identified', function () {
$this->expectException(TenantCouldNotBeIdentifiedOnDomainException::class);
pest()->expectException(TenantCouldNotBeIdentifiedOnDomainException::class);
app(DomainTenantResolver::class)->resolve('foo.localhost');
});
@ -70,7 +70,7 @@ test('tenant can be identified by domain', function () {
expect(tenancy()->initialized)->toBeFalse();
$this
pest()
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('abc + xyz');
@ -83,7 +83,7 @@ test('onfail logic can be customized', function () {
return 'foo';
};
$this
pest()
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('foo');
});

View file

@ -81,7 +81,7 @@ test('ing events can be used to cancel db creation', function () {
$tenant = Tenant::create();
dispatch_now(new CreateDatabase($tenant));
$this->assertFalse($tenant->database()->manager()->databaseExists(
pest()->assertFalse($tenant->database()->manager()->databaseExists(
$tenant->database()->getName()
));
});
@ -149,7 +149,7 @@ test('individual job pipelines can terminate while leaving others running', func
Tenant::create();
$this->assertSame([
pest()->assertSame([
'P1J1',
'P1J2',
'P2J1', // termminated after this
@ -163,7 +163,7 @@ test('database is not migrated if creation is disabled', function () {
JobPipeline::make([
CreateDatabase::class,
function () {
$this->fail("The job pipeline didn't exit.");
pest()->fail("The job pipeline didn't exit.");
},
MigrateDatabase::class,
])->send(function (TenantCreated $event) {
@ -176,7 +176,7 @@ test('database is not migrated if creation is disabled', function () {
'tenancy_db_name' => 'already_created',
]);
expect($this->hasFailed())->toBeFalse();
expect(pest()->hasFailed())->toBeFalse();
});
class FooListener extends QueueableListener

View file

@ -22,7 +22,7 @@ test('tenant redirect macro replaces only the hostname', function () {
$tenant = Tenant::create();
tenancy()->initialize($tenant);
$this->get('/redirect')
pest()->get('/redirect')
->assertRedirect('http://abcd/foobar');
});

View file

@ -37,7 +37,7 @@ test('config is merged and removed', function () {
expect(config('services.paypal'))->toBe(['public' => 'foo', 'private' => 'bar']);
tenancy()->end();
$this->assertSame([
pest()->assertSame([
'public' => null,
'private' => null,
], config('services.paypal'));
@ -66,14 +66,14 @@ test('the value can be set to multiple config keys', function () {
]);
tenancy()->initialize($tenant);
$this->assertSame([
pest()->assertSame([
'public1' => 'foo',
'public2' => 'foo',
'private' => 'bar',
], config('services.paypal'));
tenancy()->end();
$this->assertSame([
pest()->assertSame([
'public1' => null,
'public2' => null,
'private' => null,

View file

@ -19,15 +19,15 @@ test('tenant can be in maintenance mode', function () {
'domain' => 'acme.localhost',
]);
$this->get('http://acme.localhost/foo')
pest()->get('http://acme.localhost/foo')
->assertSuccessful();
tenancy()->end(); // flush stored tenant instance
$tenant->putDownForMaintenance();
$this->expectException(HttpException::class);
$this->withoutExceptionHandling()
pest()->expectException(HttpException::class);
pest()->withoutExceptionHandling()
->get('http://acme.localhost/foo');
});

View file

@ -34,7 +34,7 @@ test('tenant can be identified by path', function () {
expect(tenancy()->initialized)->toBeFalse();
$this->get('/acme/foo/abc/xyz');
pest()->get('/acme/foo/abc/xyz');
expect(tenancy()->initialized)->toBeTrue();
expect(tenant('id'))->toBe('acme');
@ -47,7 +47,7 @@ test('route actions dont get the tenant id', function () {
expect(tenancy()->initialized)->toBeFalse();
$this
pest()
->get('/acme/foo/abc/xyz')
->assertContent('abc + xyz');
@ -56,7 +56,7 @@ test('route actions dont get the tenant id', function () {
});
test('exception is thrown when tenant cannot be identified by path', function () {
$this->expectException(TenantCouldNotBeIdentifiedByPathException::class);
pest()->expectException(TenantCouldNotBeIdentifiedByPathException::class);
$this
->withoutExceptionHandling()
@ -70,7 +70,7 @@ test('onfail logic can be customized', function () {
return 'foo';
};
$this
pest()
->get('/acme/foo/abc/xyz')
->assertContent('foo');
});
@ -89,7 +89,7 @@ test('an exception is thrown when the routes first parameter is not tenant', fun
'id' => 'acme',
]);
$this->expectException(RouteIsMissingTenantParameterException::class);
pest()->expectException(RouteIsMissingTenantParameterException::class);
$this
->withoutExceptionHandling()
@ -112,12 +112,12 @@ test('tenant parameter name can be customized', function () {
'id' => 'acme',
]);
$this
pest()
->get('/acme/bar/abc/xyz')
->assertContent('abc + xyz');
// Parameter for resolver is changed, so the /{tenant}/foo route will no longer work.
$this->expectException(RouteIsMissingTenantParameterException::class);
pest()->expectException(RouteIsMissingTenantParameterException::class);
$this
->withoutExceptionHandling()

View file

@ -1,3 +1,10 @@
<?php
uses(Stancl\Tenancy\Tests\TestCase::class)->in(__DIR__);
use Stancl\Tenancy\Tests\TestCase;
uses(TestCase::class)->in(__DIR__);
function pest(): TestCase
{
return Pest\TestSuite::getInstance()->test;
}

View file

@ -7,7 +7,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;
use Spatie\Valuestore\Valuestore;
use Illuminate\Support\Facades\DB;
use Stancl\Tenancy\Tests\Etc\User;
@ -43,7 +42,7 @@ beforeEach(function () {
});
afterEach(function () {
$this->valuestore->flush();
pest()->valuestore->flush();
});
test('tenant id is passed to tenant queues', function () {
@ -55,7 +54,7 @@ test('tenant id is passed to tenant queues', function () {
Event::fake([JobProcessing::class, JobProcessed::class]);
dispatch(new TestJob($this->valuestore));
dispatch(new TestJob(pest()->valuestore));
Event::assertDispatched(JobProcessing::class, function ($event) {
return $event->job->payload()['tenant_id'] === tenant('id');
@ -74,7 +73,7 @@ test('tenant id is not passed to central queues', function () {
'central' => true,
]]);
dispatch(new TestJob($this->valuestore))->onConnection('central');
dispatch(new TestJob(pest()->valuestore))->onConnection('central');
Event::assertDispatched(JobProcessing::class, function ($event) {
return ! isset($event->job->payload()['tenant_id']);
@ -93,21 +92,21 @@ test('tenancy is initialized inside queues', function (bool $shouldEndTenancy) {
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
$this->valuestore->put('userName', 'Bar');
pest()->valuestore->put('userName', 'Bar');
dispatch(new TestJob($this->valuestore, $user));
dispatch(new TestJob(pest()->valuestore, $user));
expect($this->valuestore->has('tenant_id'))->toBeFalse();
expect(pest()->valuestore->has('tenant_id'))->toBeFalse();
if ($shouldEndTenancy) {
tenancy()->end();
}
$this->artisan('queue:work --once');
pest()->artisan('queue:work --once');
expect(DB::connection('central')->table('failed_jobs')->count())->toBe(0);
expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id);
expect(pest()->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id);
$tenant->run(function () use ($user) {
expect($user->fresh()->name)->toBe('Bar');
@ -115,10 +114,6 @@ test('tenancy is initialized inside queues', function (bool $shouldEndTenancy) {
})->with([true, false]);;
test('tenancy is initialized when retrying jobs', function (bool $shouldEndTenancy) {
if (! Str::startsWith(app()->version(), '8')) {
$this->markTestSkipped('queue:retry tenancy is only supported in Laravel 8');
}
withFailedJobs();
withTenantDatabases();
@ -130,28 +125,28 @@ test('tenancy is initialized when retrying jobs', function (bool $shouldEndTenan
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
$this->valuestore->put('userName', 'Bar');
$this->valuestore->put('shouldFail', true);
pest()->valuestore->put('userName', 'Bar');
pest()->valuestore->put('shouldFail', true);
dispatch(new TestJob($this->valuestore, $user));
dispatch(new TestJob(pest()->valuestore, $user));
expect($this->valuestore->has('tenant_id'))->toBeFalse();
expect(pest()->valuestore->has('tenant_id'))->toBeFalse();
if ($shouldEndTenancy) {
tenancy()->end();
}
$this->artisan('queue:work --once');
pest()->artisan('queue:work --once');
expect(DB::connection('central')->table('failed_jobs')->count())->toBe(1);
expect($this->valuestore->get('tenant_id'))->toBeNull(); // job failed
expect(pest()->valuestore->get('tenant_id'))->toBeNull(); // job failed
$this->artisan('queue:retry all');
$this->artisan('queue:work --once');
pest()->artisan('queue:retry all');
pest()->artisan('queue:work --once');
expect(DB::connection('central')->table('failed_jobs')->count())->toBe(0);
expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id); // job succeeded
expect(pest()->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id); // job succeeded
$tenant->run(function () use ($user) {
expect($user->fresh()->name)->toBe('Bar');
@ -165,7 +160,7 @@ test('the tenant used by the job doesnt change when the current tenant changes',
tenancy()->initialize($tenant1);
dispatch(new TestJob($this->valuestore));
dispatch(new TestJob(pest()->valuestore));
$tenant2 = Tenant::create([
'id' => 'foobar',
@ -173,10 +168,10 @@ test('the tenant used by the job doesnt change when the current tenant changes',
tenancy()->initialize($tenant2);
expect($this->valuestore->has('tenant_id'))->toBeFalse();
$this->artisan('queue:work --once');
expect(pest()->valuestore->has('tenant_id'))->toBeFalse();
pest()->artisan('queue:work --once');
expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: acme');
expect(pest()->valuestore->get('tenant_id'))->toBe('The current tenant id is: acme');
});
function createValueStore(): void
@ -192,7 +187,7 @@ function createValueStore(): void
file_put_contents($valueStorePath, '');
}
test()->valuestore = Valuestore::make($valueStorePath)->flush();
pest()->valuestore = Valuestore::make($valueStorePath)->flush();
}
function withFailedJobs()
@ -262,4 +257,3 @@ class TestJob implements ShouldQueue
}
}
}

View file

@ -47,7 +47,7 @@ beforeEach(function () {
UpdateSyncedResource::$shouldQueue = false; // global state cleanup
Event::listen(SyncedResourceSaved::class, UpdateSyncedResource::class);
test()->artisan('migrate', [
pest()->artisan('migrate', [
'--path' => [
__DIR__ . '/Etc/synced_resource_migrations',
__DIR__ . '/Etc/synced_resource_migrations/users',
@ -104,7 +104,7 @@ test('only the synced columns are updated in the central db', function () {
]);
// Assert new values
$this->assertEquals([
pest()->assertEquals([
'id' => 1,
'global_id' => 'acme',
'name' => 'John Foo',
@ -116,7 +116,7 @@ test('only the synced columns are updated in the central db', function () {
tenancy()->end();
// Assert changes bubbled up
$this->assertEquals([
pest()->assertEquals([
'id' => 1,
'global_id' => 'acme',
'name' => 'John Foo', // synced
@ -136,7 +136,7 @@ test('trying to update synced resources from central context using tenant models
tenancy()->end();
expect(tenancy()->initialized)->toBeFalse();
$this->expectException(ModelNotSyncMasterException::class);
pest()->expectException(ModelNotSyncMasterException::class);
ResourceUser::first()->update(['role' => 'foobar']);
});
@ -338,7 +338,7 @@ test('global id is generated using id generator when its not supplied', function
'role' => 'employee',
]);
$this->assertNotNull($user->global_id);
pest()->assertNotNull($user->global_id);
});
test('when the resource doesnt exist in the tenant db non synced columns will cascade too', function () {
@ -539,7 +539,7 @@ function creatingResourceInTenantDatabaseCreatesAndMapInCentralDatabase()
function migrateTenantsResource()
{
test()->artisan('tenants:migrate', [
pest()->artisan('tenants:migrate', [
'--path' => __DIR__ . '/Etc/synced_resource_migrations/users',
'--realpath' => true,
])->assertExitCode(0);

View file

@ -35,7 +35,7 @@ test('tenant id is auto added to session if its missing', function () {
'id' => 'acme',
]);
$this->get('http://acme.localhost/foo')
pest()->get('http://acme.localhost/foo')
->assertSessionHas(ScopeSessions::$tenantIdKey, 'acme');
});
@ -44,12 +44,12 @@ test('changing tenant id in session will abort the request', function () {
'id' => 'acme',
]);
$this->get('http://acme.localhost/foo')
pest()->get('http://acme.localhost/foo')
->assertSuccessful();
session()->put(ScopeSessions::$tenantIdKey, 'foobar');
$this->get('http://acme.localhost/foo')
pest()->get('http://acme.localhost/foo')
->assertStatus(403);
});
@ -62,6 +62,6 @@ test('an exception is thrown when the middleware is executed before tenancy is i
'id' => 'acme',
]);
$this->expectException(TenancyNotInitializedException::class);
$this->withoutExceptionHandling()->get('http://acme.localhost/bar');
pest()->expectException(TenancyNotInitializedException::class);
pest()->withoutExceptionHandling()->get('http://acme.localhost/bar');
});

View file

@ -138,7 +138,7 @@ test('tenant id and relationship is auto added when creating primary resources i
});
test('tenant id is not auto added when creating primary resources in central context', function () {
$this->expectException(QueryException::class);
pest()->expectException(QueryException::class);
Post::create(['text' => 'Foo']);
});
@ -212,8 +212,8 @@ test('the model returned by the tenant helper has unique and exists validation r
])->fails();
// Assert that 'unique' and 'exists' aren't scoped by default
// $this->assertFalse($uniqueFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
// $this->assertTrue($existsFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
// pest()->assertFalse($uniqueFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
// pest()->assertTrue($existsFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
$uniqueFails = Validator::make($data, [
'slug' => tenant()->unique('posts'),

View file

@ -34,7 +34,7 @@ test('tenant can be identified by subdomain', function () {
expect(tenancy()->initialized)->toBeFalse();
$this
pest()
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('abc + xyz');
@ -47,13 +47,13 @@ test('onfail logic can be customized', function () {
return 'foo';
};
$this
pest()
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('foo');
});
test('localhost is not a valid subdomain', function () {
$this->expectException(NotASubdomainException::class);
pest()->expectException(NotASubdomainException::class);
$this
->withoutExceptionHandling()
@ -61,7 +61,7 @@ test('localhost is not a valid subdomain', function () {
});
test('ip address is not a valid subdomain', function () {
$this->expectException(NotASubdomainException::class);
pest()->expectException(NotASubdomainException::class);
$this
->withoutExceptionHandling()
@ -99,7 +99,7 @@ test('we cant use a subdomain that doesnt belong to our central domains', functi
'domain' => 'foo',
]);
$this->expectException(NotASubdomainException::class);
pest()->expectException(NotASubdomainException::class);
$this
->withoutExceptionHandling()
@ -119,7 +119,7 @@ test('central domain is not a subdomain', function () {
'domain' => 'acme',
]);
$this->expectException(NotASubdomainException::class);
pest()->expectException(NotASubdomainException::class);
$this
->withoutExceptionHandling()

View file

@ -32,14 +32,14 @@ test('asset can be accessed using the url returned by the tenant asset helper',
$tenant = Tenant::create();
tenancy()->initialize($tenant);
$filename = 'testfile' . $this->randomString(10);
$filename = 'testfile' . pest()->randomString(10);
Storage::disk('public')->put($filename, 'bar');
$path = storage_path("app/public/$filename");
// response()->file() returns BinaryFileResponse whose content is
// inaccessible via getContent, so ->assertSee() can't be used
expect($path)->toBeFile();
$response = $this->get(tenant_asset($filename), [
$response = pest()->get(tenant_asset($filename), [
'X-Tenant' => $tenant->id,
]);
@ -99,7 +99,7 @@ function getEnvironmentSetUp($app)
$app->booted(function () {
if (file_exists(base_path('routes/tenant.php'))) {
Route::middleware(['web'])
->namespace(test()->app['config']['tenancy.tenant_route_namespace'] ?? 'App\Http\Controllers')
->namespace(pest()->app['config']['tenancy.tenant_route_namespace'] ?? 'App\Http\Controllers')
->group(base_path('routes/tenant.php'));
}
});

View file

@ -13,14 +13,14 @@ test('commands run globally are tenant aware and return valid exit code', functi
'--tenants' => [$tenant1['id'], $tenant2['id']],
]);
$this->artisan('user:add')
pest()->artisan('user:add')
->assertExitCode(0);
tenancy()->initialize($tenant1);
$this->assertNotEmpty(DB::table('users')->get());
pest()->assertNotEmpty(DB::table('users')->get());
tenancy()->end();
tenancy()->initialize($tenant2);
$this->assertNotEmpty(DB::table('users')->get());
pest()->assertNotEmpty(DB::table('users')->get());
tenancy()->end();
});

View file

@ -33,7 +33,7 @@ test('databases can be created and deleted', function ($driver, $databaseManager
"tenancy.database.managers.$driver" => $databaseManager,
]);
$name = 'db' . $this->randomString();
$name = 'db' . pest()->randomString();
$manager = app($databaseManager);
$manager->setConnection($driver);
@ -57,7 +57,7 @@ test('dbs can be created when another driver is used for the central db', functi
return $event->tenant;
})->toListener());
$database = 'db' . $this->randomString();
$database = 'db' . pest()->randomString();
$mysqlmanager = app(MySQLDatabaseManager::class);
$mysqlmanager->setConnection('mysql');
@ -73,7 +73,7 @@ test('dbs can be created when another driver is used for the central db', functi
$postgresManager = app(PostgreSQLDatabaseManager::class);
$postgresManager->setConnection('pgsql');
$database = 'db' . $this->randomString();
$database = 'db' . pest()->randomString();
expect($postgresManager->databaseExists($database))->toBeFalse();
Tenant::create([
@ -101,14 +101,14 @@ test('the tenant connection is fully removed', function () {
$tenant = Tenant::create();
expect(array_keys(app('db')->getConnections()))->toBe(['central']);
$this->assertArrayNotHasKey('tenant', config('database.connections'));
pest()->assertArrayNotHasKey('tenant', config('database.connections'));
tenancy()->initialize($tenant);
createUsersTable();
expect(array_keys(app('db')->getConnections()))->toBe(['central', 'tenant']);
$this->assertArrayHasKey('tenant', config('database.connections'));
pest()->assertArrayHasKey('tenant', config('database.connections'));
tenancy()->end();
@ -175,7 +175,7 @@ test('a tenants database cannot be created when the database already exists', fu
$manager = $tenant->database()->manager();
expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
$this->expectException(TenantDatabaseAlreadyExistsException::class);
pest()->expectException(TenantDatabaseAlreadyExistsException::class);
$tenant2 = Tenant::create([
'tenancy_db_name' => $name,
]);
@ -225,7 +225,7 @@ test('tenant database can be created on a foreign server', function () {
});
test('path used by sqlite manager can be customized', function () {
$this->markTestIncomplete();
pest()->markTestIncomplete();
});
// Datasets

View file

@ -50,7 +50,7 @@ test('id is generated when no id is supplied', function () {
$tenant = Tenant::create();
$this->assertNotNull($tenant->id);
pest()->assertNotNull($tenant->id);
});
test('autoincrement ids are supported', function () {

View file

@ -25,7 +25,7 @@ use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Foundation\Auth\User as Authenticable;
beforeEach(function () {
$this->artisan('migrate', [
pest()->artisan('migrate', [
'--path' => __DIR__ . '/../assets/impersonation-migrations',
'--realpath' => true,
])->assertExitCode(0);
@ -69,16 +69,16 @@ test('tenant user can be impersonated on a tenant domain', function () {
});
// We try to visit the dashboard directly, before impersonating the user.
$this->get('http://foo.localhost/dashboard')
pest()->get('http://foo.localhost/dashboard')
->assertRedirect('http://foo.localhost/login');
// We impersonate the user
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
$this->get('http://foo.localhost/impersonate/' . $token->token)
pest()->get('http://foo.localhost/impersonate/' . $token->token)
->assertRedirect('http://foo.localhost/dashboard');
// Now we try to visit the dashboard directly, after impersonating the user.
$this->get('http://foo.localhost/dashboard')
pest()->get('http://foo.localhost/dashboard')
->assertSuccessful()
->assertSee('You are logged in as Joe');
});
@ -102,16 +102,16 @@ test('tenant user can be impersonated on a tenant path', function () {
});
// We try to visit the dashboard directly, before impersonating the user.
$this->get('/acme/dashboard')
pest()->get('/acme/dashboard')
->assertRedirect('/login');
// We impersonate the user
$token = tenancy()->impersonate($tenant, $user->id, '/acme/dashboard');
$this->get('/acme/impersonate/' . $token->token)
pest()->get('/acme/impersonate/' . $token->token)
->assertRedirect('/acme/dashboard');
// Now we try to visit the dashboard directly, after impersonating the user.
$this->get('/acme/dashboard')
pest()->get('/acme/dashboard')
->assertSuccessful()
->assertSee('You are logged in as Joe');
});
@ -138,7 +138,7 @@ test('tokens have a limited ttl', function () {
'created_at' => Carbon::now()->subtract(CarbonInterval::make('100s')),
]);
$this->followingRedirects()
pest()->followingRedirects()
->get('http://foo.localhost/impersonate/' . $token->token)
->assertStatus(403);
});
@ -162,9 +162,9 @@ test('tokens are deleted after use', function () {
// We impersonate the user
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
$this->assertNotNull(ImpersonationToken::find($token->token));
pest()->assertNotNull(ImpersonationToken::find($token->token));
$this->followingRedirects()
pest()->followingRedirects()
->get('http://foo.localhost/impersonate/' . $token->token)
->assertSuccessful()
->assertSee('You are logged in as Joe');
@ -204,16 +204,16 @@ test('impersonation works with multiple models and guards', function () {
});
// We try to visit the dashboard directly, before impersonating the user.
$this->get('http://foo.localhost/dashboard')
pest()->get('http://foo.localhost/dashboard')
->assertRedirect('http://foo.localhost/login');
// We impersonate the user
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard', 'another');
$this->get('http://foo.localhost/impersonate/' . $token->token)
pest()->get('http://foo.localhost/impersonate/' . $token->token)
->assertRedirect('http://foo.localhost/dashboard');
// Now we try to visit the dashboard directly, after impersonating the user.
$this->get('http://foo.localhost/dashboard')
pest()->get('http://foo.localhost/dashboard')
->assertSuccessful()
->assertSee('You are logged in as Joe');
@ -225,7 +225,7 @@ test('impersonation works with multiple models and guards', function () {
function migrateTenants()
{
test()->artisan('tenants:migrate')->assertExitCode(0);
pest()->artisan('tenants:migrate')->assertExitCode(0);
}
function makeLoginRoute()
@ -239,7 +239,7 @@ function getRoutes($loginRoute = true, $authGuard = 'web'): Closure
{
return function () use ($loginRoute, $authGuard) {
if ($loginRoute) {
test()->makeLoginRoute();
makeLoginRoute();
}
Route::get('/dashboard', function () use ($authGuard) {

View file

@ -23,7 +23,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
Redis::connection('cache')->flushdb();
file_put_contents(database_path('central.sqlite'), '');
$this->artisan('migrate:fresh', [
pest()->artisan('migrate:fresh', [
'--force' => true,
'--path' => __DIR__ . '/../assets/migrations',
'--realpath' => true,

View file

@ -21,7 +21,7 @@ test('a route can work in both central and tenant context', function () {
: 'Tenancy is not initialized.';
})->middleware(['universal', InitializeTenancyByDomain::class]);
$this->get('http://localhost/foo')
pest()->get('http://localhost/foo')
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
@ -32,7 +32,7 @@ test('a route can work in both central and tenant context', function () {
'domain' => 'acme.localhost',
]);
$this->get('http://acme.localhost/foo')
pest()->get('http://acme.localhost/foo')
->assertSuccessful()
->assertSee('Tenancy is initialized.');
});
@ -51,7 +51,7 @@ test('making one route universal doesnt make all routes universal', function ()
: 'Tenancy is not initialized.';
})->middleware(['universal', InitializeTenancyByDomain::class]);
$this->get('http://localhost/foo')
pest()->get('http://localhost/foo')
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
@ -62,16 +62,16 @@ test('making one route universal doesnt make all routes universal', function ()
'domain' => 'acme.localhost',
]);
$this->get('http://acme.localhost/foo')
pest()->get('http://acme.localhost/foo')
->assertSuccessful()
->assertSee('Tenancy is initialized.');
tenancy()->end();
$this->get('http://localhost/bar')
pest()->get('http://localhost/bar')
->assertStatus(500);
$this->get('http://acme.localhost/bar')
pest()->get('http://acme.localhost/bar')
->assertSuccessful()
->assertSee('acme');
});