Skip to content

Instantly share code, notes, and snippets.

@AustinMaddox
Created December 21, 2017 17:35
Show Gist options
  • Save AustinMaddox/f083cac499ac02597a783d9ebf49e306 to your computer and use it in GitHub Desktop.
Save AustinMaddox/f083cac499ac02597a783d9ebf49e306 to your computer and use it in GitHub Desktop.
Force the use of only one "test-tenant" in phpunit tests
<?php
namespace Tests;
use Hyn\Tenancy\Contracts\Repositories\HostnameRepository;
use Hyn\Tenancy\Contracts\Repositories\WebsiteRepository;
use Hyn\Tenancy\Environment;
use Hyn\Tenancy\Models\Hostname;
use Hyn\Tenancy\Models\Website;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
// use RefreshDatabase;
// use DatabaseTransactions;
protected static $is_tenant_created = false;
const WEBSITE_UUID = 'test-tenant';
const DOMAIN = 'example.com';
const FQDN = self::WEBSITE_UUID . '.' . self::DOMAIN;
protected function setUp()
{
parent::setUp();
if (!static::$is_tenant_created) {
if (!Hostname::where('fqdn', '=', self::FQDN)->first()) {
$this->createNewTenant();
}
static::$is_tenant_created = true;
}
$this->switchActiveTenant();
// TODO: Would be nice to be able to use the RefreshDatabase trait instead of this.
$this->truncateAllTables();
}
protected function truncateAllTables(): void
{
$table_names = Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
foreach ($table_names as $table_name) {
if ($table_name == 'migrations') {
continue;
}
DB::table($table_name)->truncate();
}
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
protected function createNewTenant(): void
{
$website = $this->createTenantWebsite();
$this->createTenantHostname($website);
}
/**
* @return Website
*/
protected function createTenantWebsite(): Website
{
$website = new Website;
$website->uuid = self::WEBSITE_UUID;
app(WebsiteRepository::class)->create($website);
return $website;
}
/**
* @param $website
*/
protected function createTenantHostname($website): void
{
$hostname = new Hostname;
$hostname->fqdn = self::FQDN;
app(HostnameRepository::class)->attach($hostname, $website);
}
protected function switchActiveTenant(): void
{
$hostname = Hostname::where('fqdn', '=', self::FQDN)->firstOrFail();
$environment = app(Environment::class);
$environment->hostname($hostname);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment