Skip to content

Slow execution for tests involving database #653

@vpratfr

Description

@vpratfr

I currently have a basic implementation working on a very simple use case. My current concern is performance of testing.

A very simple test suite regarding user creation takes around 10 seconds to run for 2 tests. That takes less than a second on a standard project using in memory sqlite database.

I feel that using MySQL as server is the main culprit. Would you have any guidelines to achieve a descent test execution time? Our MVP has almost 1000 tests...

I had to setup a base class for all tests dealing with database in the context of a Tenant. Here is the base class:

abstract class TenantAwareTestCase extends TestCase
{
    use RefreshDatabase;

    protected $tenant;

    public function refreshDatabase()
    {
        $this->artisan('migrate:fresh');
        $this->tenant = $this->createTenant();
        $this->artisan('tenancy:migrate:fresh');
        app(Environment::class)->tenant($this->tenant);
    }

    protected function tearDown()
    {
        $hostname = $this->tenant->hostnames->first();
        app(HostnameRepository::class)->delete($hostname, true);
        app(WebsiteRepository::class)->delete($this->tenant, true);
        parent::tearDown();
    }

    protected function createTenant(string $subdomain = 'acme'): Website
    {        
        [$website, $owner] = app(CreateAccount::class)->execute(new CreateAccountData(
            $subdomain,
            new CreateUserData('John Doe', "john@$subdomain.com", 'secret'),
            false));
        
        return $website;
    }

    protected function deleteTenant(Website $website)
    {
        app(HostnameRepository::class)->delete($website->hostname, true);
        app(WebsiteRepository::class)->delete($website, true);
    }
}

The CreateAccount command basically does that:

    $website = new Website();
    $this->websites->create($website);

    $hostname = new Hostname();
    $hostname->fqdn = $this->getFqdn($name);
    $this->hostnames->attach($hostname, $website);

    $this->environment->tenant($website);

    User::create([
        'name'     => $data->name,
        'email'    => $data->email,
        'password' => Hash::make($data->password),
    ]);

    $this->environment->tenant(null);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions