PHP code example of cspray / labrador-async-unit

1. Go to this page and download the library: Download cspray/labrador-async-unit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cspray / labrador-async-unit example snippets




namespace Acme\MyApp;

use Cspray\Labrador\AsyncUnit\Attribute\AfterAll;
use Cspray\Labrador\AsyncUnit\Attribute\BeforeAll;
use Cspray\Labrador\AsyncUnit\Attribute\BeforeEachTest;
use Cspray\Labrador\AsyncUnit\Attribute\AfterEachTest;
use Cspray\Labrador\AsyncUnit\Attribute\BeforeEach;
use Cspray\Labrador\AsyncUnit\Attribute\Test;
use Cspray\Labrador\AsyncUnit\Attribute\AttachToTestSuite as UseTestSuite;
use Cspray\Labrador\AsyncUnit\TestCase;
use Cspray\Labrador\AsyncUnit\TestSuite;
use Amp\Success;
use Amp\Delayed;
use function Amp\Postgres\pool;

class DatabaseTestSuite extends TestSuite {

    #[BeforeAll]
    public function connectToDatabase() {
        // In test situations we want to make sure we're dealing with the same connection so we can properly clean up data
        $pool = pool(connectionConfig(), maxConnections: 1, resetConnections: false);
        $this->set('pool', $pool);
    }
    
    #[BeforeEachTest]
    public function startTransaction() {
        yield $this->get('pool')->query('START TRANSACTION');
    }
    
    #[AfterEachTest]
    public function rollback() {
        yield $this->get('pool')->query('ROLLBACK');
    }
    
    #[AfterAll]
    public function closeDatabase() {
        $this->get('pool')->close();
    }
    
}

// The name of this class doesn't matter... you only need to ensure you extend TestCase
#[UseTestSuite(DatabaseTestSuite::class)]
class MyDatabaseTestCase extends TestCase {

    // Again, none of the method names matter... just make sure you're annotating with the correct Attribute
    #[BeforeEach]
    public function loadFixture() {
        yield someMethodThatLoadsData($this->testSuite()->get('pool'));
    }
    
    #[Test]
    public function ensureSomethingHappens() {
        yield new Delayed(100); // just to show you we're on the loop
        // These values could be retrieved from the database
        $this->assert()->stringEquals('foo', 'foo');
    }
    
    #[Test]
    public function ensureSomethingAsyncHappens() {
        yield new Delayed(100);
        yield $this->asyncAssert()->stringEquals('foo', new Success('foo'));
    }
    
    #[Test]
    public function makeSureYouAssertSomething() {
        // a failed test because you didn't assert anything!
    }
    
}
    
class MyNormalTestCase extends TestCase {
    
    #[Test]
    public function ensurePoolNotAvailable() {
        $this->assert()->isNull($this->testSuite()->get('pool'));
    }
    
}