1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 19:04:02 +00:00
tenancy/tests/TestCase.php
Abrar Ahmad bd9bbe8b41
Cache prefix mode for separating tenant caches (#1014)
* cache prefix

* prefix cache bootstrapper and tests

* remove comment

* DI app

* cache prefix base from config

* Create PrefixCacheBootstrapperTest.php

* remove `null` check

* fix phpstan error

* Update PrefixCacheTenancyBootstrapper.php

* Update PrefixCacheBootstrapperTest.php

* add comments

* Update PrefixCacheTenancyBootstrapper.php

* Update PrefixCacheBootstrapperTest.php

* Update config.php

* test names grammar

* user `getTenantKey` method

* assert tenants' data is accessible using the prefix from the central context

* remove unused line

* use proper DI

* build prefix using original prefix

* fix prefix test according to prefix changes

* fix test

* CacheManager dependency injection test

* CacheService class as singleton

* introduce second tenant in test

* use Repository in service class DI

* Update CacheAction.php

* Rename CacheAction to CacheService

* Update prefix bootstrapper and test (`setStore()` in CacheManager and Repository needed)

* Add macro

* Fix code style (php-cs-fixer)

* Simplify cache store refreshing

* Make Tenancy override CacheManager

* Update CacheManager, add refreshStore()

* Fix code style (php-cs-fixer)

* Uncomment cache tagging

* Revert condition in CacheManager to avoid excessive nesting

* Move `Cache::macro()` to a slightly more appropriate place

* Fix code style (php-cs-fixer)

* Use better class for the macro

* Toggle cache tags

* Make CacheManager::$addTags default to `true`

* Add changes to PR to Laravel

* Fix code style (php-cs-fixer)

* Revert changes, add comment

* Add test

* Make `$cache` non-nullable

Co-authored-by: Samuel Štancl <samuel@archte.ch>

* Add and test `nonTenantCacheDrivers`

* Add nonTenantCacheDrivers check

* Test that the prefix stays the same

* Change nonTenantCacheDrivers to tenantCacheStores

* Remove redundant CacheManager extend() call

* Make 'redis' the only tenant cache store in beforeEach, test that tenantCacheStores works

* Remove unused import, change word

* Make CacheService a singleton in a test

* Update test name

* Remove group('prefix')

* Rename CacheManagerService

* Improve specific cache store in a service test

* Improve comment

* Improve tests

* Use my Laravel fork

* Fix code style (php-cs-fixer)

* Downgrade Laravel

* Upgrade Laravel

* Hint Repository implementation instead of contract

* Fix types

* Fix code style (php-cs-fixer)

* Fix test

* Use Laravel fork in ci.yml

* use dev-master before our changes are released in L10

* remove laravel fork from repositories

* use 10.x-dev instead of master

* remove L9 support

* 10.x-dev (fix conflict resolution)

* use the laravel version from the ci matrix for the phpstan job as well

* Revert "use the laravel version from the ci matrix for the phpstan job as well"

This reverts commit 5f3079d2ff.

* Test that non-default stores get prefixed too

* Use new Laravel release, remove L9 support

* Complete L9 support removal

* Specify 10.1.1 as the minimal Laravel version in ci.yml

* Use 10.x-dev

* Prefix all cache stores specified in `$tenantCacheStores`

* Update Laravel

* Use tmpfs in docker-compose

* Add customizing cache store prefixes

* Test cache prefixing customization

* Fix code style (php-cs-fixer)

* Update ci.yml

* Delete tmpfs from docker-compose.yml (there were no benefits)

* Use default prefix generator inline, delete the 'default' key logic

* Fix original prefix logic

* Update tests

* Delete CacheTenancyBootstrapper

* Reset static properties in afterEach

* Use `$this->config` instead of `config()`

* Disable cache tagging by default, add CacheTagBootstrapper

* Fix code style (php-cs-fixer)

* Rename bootstrapper

* Improve CacheManager

* Move logic from separate method to __call

* Make original prefixes customizable

* Add info in comment

* Add defaultPrefix property

* Use `$this->app` instead of `app()`

* Rename bootstrapper

* Fix code style (php-cs-fixer)

* Use a single original prefix

* Update prefix generator logic + tests

* Correct `$addTags` reset in a test

* Update cache tests so that both prefixing and tagging is covered

* Simplify cache tests

* Delete afterEach

* Small testing improvements

* Set `cache.default` in beforeEach

* Update cache prefixing and tests

* Add assertion

* Refactor assertion

* Refactor assertions

* Delete TTL from cache put calls

* Add re-initialization cache assertion

* Assert that cache is null from the beginning

* Merge the tenantCacheStores tests

* Fix formatting

* Improve test name

* Improve tests

* Add cache manager config key

* Fix code style (php-cs-fixer)

* Update defaulting test

* Add todo

* Update comments

* Extract duplicate assertions into a closure

* Update comment

* Add assertions + comment

* Delete redundant config put calls

* Use `tenancy.cache.manager` config instead of `Stancl\Tenancy\CacheManager`

* Change setting to assertion, add comment

* Inline variable & config key assignment

* Delete `cache.default` assertion

* Override cache manager only in CacheTagsBootstrapper

* Fix code style (php-cs-fixer)

* Prefix both drivers by default, add assertions for the second driver where missing

* Clean up global state (static properties) in before/afterEach

* Add docblock to tags bootstrapper

* Delete extra dependency

* Add `illuminate/support` dependency back

* Use `$addTags` approach again

* Fix code style (php-cs-fixer)

* Revert "Fix code style (php-cs-fixer)"

This reverts commit ea805fa231.

* Revert "Use `$addTags` approach again"

This reverts commit 8f5a4e4eb6.

* Add commented CacheTagsBootstrapper with info to the bootstrappers config

* Delete legacy bootstrapper from the bootstrappers config, add info to the bootstrapper's docblock

* Delete "?" from `tenant()?->getTenantKey()

* call generatePrefix() on $bootstrapper

* misc improvements

---------

Co-authored-by: lukinovec <lukinovec@gmail.com>
Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
Co-authored-by: Samuel Štancl <samuel@archte.ch>
Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>
2023-04-24 16:25:51 +02:00

174 lines
6.7 KiB
PHP

<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use PDO;
use Dotenv\Dotenv;
use Stancl\Tenancy\Facades\Tenancy;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Support\Facades\Redis;
use Stancl\Tenancy\Bootstrappers\PrefixCacheTenancyBootstrapper;
use Illuminate\Foundation\Application;
use Stancl\Tenancy\Facades\GlobalCache;
use Stancl\Tenancy\TenancyServiceProvider;
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\BroadcastTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\UrlTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\MailTenancyBootstrapper;
abstract class TestCase extends \Orchestra\Testbench\TestCase
{
/**
* Setup the test environment.
*
* @return void
*/
protected function setUp(): void
{
parent::setUp();
Redis::connection('default')->flushdb();
Redis::connection('cache')->flushdb();
file_put_contents(database_path('central.sqlite'), '');
pest()->artisan('migrate:fresh', [
'--force' => true,
'--path' => __DIR__ . '/../assets/migrations',
'--realpath' => true,
]);
// Laravel 6.x support
$testResponse = class_exists('Illuminate\Testing\TestResponse') ? 'Illuminate\Testing\TestResponse' : 'Illuminate\Foundation\Testing\TestResponse';
$testResponse::macro('assertContent', function ($content) {
$assertClass = class_exists('Illuminate\Testing\Assert') ? 'Illuminate\Testing\Assert' : 'Illuminate\Foundation\Testing\Assert';
$assertClass::assertSame($content, $this->baseResponse->getContent());
return $this;
});
}
/**
* Define environment setup.
*
* @param Application $app
* @return void
*/
protected function getEnvironmentSetUp($app)
{
if (file_exists(__DIR__ . '/../.env')) {
Dotenv::createImmutable(__DIR__ . '/..')->load();
}
$app['config']->set([
'database.default' => 'central',
'database.redis.cache.host' => env('TENANCY_TEST_REDIS_HOST', '127.0.0.1'),
'database.redis.default.host' => env('TENANCY_TEST_REDIS_HOST', '127.0.0.1'),
'database.redis.options.prefix' => 'foo',
'database.connections.central' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => 'mysql',
'port' => env('DB_PORT', '3306'),
'database' => 'main',
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'database.connections.sqlite.database' => ':memory:',
'database.connections.mysql.host' => env('TENANCY_TEST_MYSQL_HOST', '127.0.0.1'),
'database.connections.sqlsrv.username' => env('TENANCY_TEST_SQLSRV_USERNAME', 'sa'),
'database.connections.sqlsrv.password' => env('TENANCY_TEST_SQLSRV_PASSWORD', 'P@ssword'),
'database.connections.sqlsrv.host' => env('TENANCY_TEST_SQLSRV_HOST', '127.0.0.1'),
'database.connections.sqlsrv.database' => null,
'database.connections.pgsql.host' => env('TENANCY_TEST_PGSQL_HOST', '127.0.0.1'),
'tenancy.filesystem.disks' => [
'local',
'public',
's3',
],
'filesystems.disks.s3.bucket' => 'foo',
'tenancy.redis.tenancy' => env('TENANCY_TEST_REDIS_TENANCY', true),
'database.redis.client' => env('TENANCY_TEST_REDIS_CLIENT', 'phpredis'),
'tenancy.redis.prefixed_connections' => ['default'],
'tenancy.migration_parameters' => [
'--path' => [database_path('../migrations')],
'--realpath' => true,
'--force' => true,
],
'tenancy.bootstrappers.redis' => RedisTenancyBootstrapper::class, // todo1 change this to []? two tests in TenantDatabaseManagerTest are failing with that
'tenancy.bootstrappers.broadcast' => BroadcastTenancyBootstrapper::class, // todo1 change this to []? two tests in TenantDatabaseManagerTest are failing with that
'tenancy.bootstrappers.mail' => MailTenancyBootstrapper::class,
'tenancy.bootstrappers.url' => UrlTenancyBootstrapper::class,
'queue.connections.central' => [
'driver' => 'sync',
'central' => true,
],
'tenancy.seeder_parameters' => [],
'tenancy.models.tenant' => Tenant::class, // Use test tenant w/ DBs & domains
]);
$app->singleton(RedisTenancyBootstrapper::class); // todo (Samuel) use proper approach eg config for singleton registration
$app->singleton(PrefixCacheTenancyBootstrapper::class); // todo (Samuel) use proper approach eg config for singleton registration
$app->singleton(BroadcastTenancyBootstrapper::class);
$app->singleton(MailTenancyBootstrapper::class);
$app->singleton(UrlTenancyBootstrapper::class);
}
protected function getPackageProviders($app)
{
return [
TenancyServiceProvider::class,
];
}
protected function getPackageAliases($app)
{
return [
'Tenancy' => Tenancy::class,
'GlobalCache' => GlobalCache::class,
];
}
/**
* Resolve application HTTP Kernel implementation.
*
* @param Application $app
* @return void
*/
protected function resolveApplicationHttpKernel($app)
{
$app->singleton('Illuminate\Contracts\Http\Kernel', Etc\HttpKernel::class);
}
/**
* Resolve application Console Kernel implementation.
*
* @param Application $app
* @return void
*/
protected function resolveApplicationConsoleKernel($app)
{
$app->singleton('Illuminate\Contracts\Console\Kernel', Etc\Console\ConsoleKernel::class);
}
public function randomString(int $length = 10)
{
return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', (int) (ceil($length / strlen($x))))), 1, $length);
}
public function assertArrayIsSubset($subset, $array, string $message = ''): void
{
parent::assertTrue(array_intersect($subset, $array) == $subset, $message);
}
}