Abstract Class luya\testsuite\cases\ServerTestCase

Inheritanceluya\testsuite\cases\ServerTestCase » luya\testsuite\cases\BaseTestSuite » Yoast\PHPUnitPolyfills\TestCases\TestCase
Available since version1.0.2

Webserver Test Case.

Generates a local Server in order to Test URLs.

An example usage:

class MyWebsite extends ServerTestCase
{
   public function getConfigArray()
   {
      return [
          'id' => 'mytestapp',
          'basePath' => dirname(__DIR__),
      ];
  }

  public function testSites()
  {
      $this->assertUrlHomepageIsOk();
      $this->assertUrlIsOk('about');
      $this->assertUrlGetResponseContains('about/me', 'Hello World');
      $this->assertUrlIsError('errorpage');
  }
}

Public Methods

Hide inherited methods

Method Description Defined By
afterSetup() Method which is executed after the setUp() method in order to trigger post setup functions. luya\testsuite\cases\ServerTestCase
assertContainsNoSpace() Assert Contains without spaces but with newlines. luya\testsuite\cases\BaseTestSuite
assertContainsTrimmed() Same as assertContains but trims the needle and haystack content in order to compare. luya\testsuite\cases\BaseTestSuite
assertSameNoSpace() This assert Same option allows you to compare two strings but removing spaces and tabes, so its more easy to work with readable contents but better comparing. luya\testsuite\cases\BaseTestSuite
assertSameTrimmed() Assert Same but trim content (remove, double spaces, tabs and newlines. luya\testsuite\cases\BaseTestSuite
assertUrlGetResponseContains() Test an url and see if the response contains. luya\testsuite\cases\ServerTestCase
assertUrlGetResponseSame() Make a GET request and see if the response is the same as. luya\testsuite\cases\ServerTestCase
assertUrlHomepageIsOk() Check whether homage is online and OK response. luya\testsuite\cases\ServerTestCase
assertUrlIsError() Test an URL whether a page has response code 400 luya\testsuite\cases\ServerTestCase
assertUrlIsOk() Test an URL whether a page has response code 200 luya\testsuite\cases\ServerTestCase
assertUrlIsRedirect() Test whether url is redirect. luya\testsuite\cases\ServerTestCase
assertUrlPostResponseContains() Make a POST request and see if the response contains in. luya\testsuite\cases\ServerTestCase
assertUrlPostResponseSame() luya\testsuite\cases\ServerTestCase
beforeSetup() Method which is executed before the setUp() method in order to inject data on before Setup. luya\testsuite\cases\BaseTestSuite
beforeTearDown() This method is triggered before the application test case tearDown() method is running. luya\testsuite\cases\ServerTestCase
bootApplication() luya\testsuite\cases\ServerTestCase
createGetCurl() luya\testsuite\cases\ServerTestCase
createPostCurl() luya\testsuite\cases\ServerTestCase
fixture() Get Fixture Object luya\testsuite\cases\BaseTestSuite
fixtures() Defines a list of fixtures classes which can be loaded. luya\testsuite\cases\BaseTestSuite
getConfigArray() Provide Configurtion Array. luya\testsuite\cases\BaseTestSuite
invokeMethod() Call a private or protected method from an object and return the value. luya\testsuite\cases\BaseTestSuite
setupFixtures() Create all fixtures from fixtures() list. luya\testsuite\cases\BaseTestSuite
tearDownFixtures() Run cleanup() on all loaded fixtures. luya\testsuite\cases\BaseTestSuite

Property Details

Hide inherited properties

$debug public property
public boolean $debug false
$documentRoot public property
public string $documentRoot '@app/public_html'
$host public property
public string $host 'localhost'
$port public property
public integer $port 1549

Method Details

Hide inherited methods

afterSetup() public method (available since version 1.0.2)

Method which is executed after the setUp() method in order to trigger post setup functions.

Make sure to call the parent afterSetup() method when overwriting this method.

See also luya\testsuite\cases\BaseTestSuite::afterSetup().

public void afterSetup ( )

                public function afterSetup()
{
    $this->_pid = $this->bootstrapServer($this->host, $this->port, $this->documentRoot);
}

            
assertContainsNoSpace() public method (available since version 1.0.8)

Defined in: luya\testsuite\cases\BaseTestSuite::assertContainsNoSpace()

Assert Contains without spaces but with newlines.

public boolean assertContainsNoSpace ( $needle, $haystack )
$needle string
$haystack string

                public function assertContainsNoSpace($needle, $haystack)
{
    return $this->assertStringContainsString($this->trimSpaces($needle), $this->trimSpaces($haystack));
}

            
assertContainsTrimmed() public method

Defined in: luya\testsuite\cases\BaseTestSuite::assertContainsTrimmed()

Same as assertContains but trims the needle and haystack content in order to compare.

This will also remove newlines.

public boolean assertContainsTrimmed ( $needle, $haystack )
$needle string
$haystack string

                public function assertContainsTrimmed($needle, $haystack)
{
    return self::assertStringContainsString($this->trimContent($needle), $this->trimContent($haystack));
}

            
assertSameNoSpace() public method (available since version 1.0.8)

Defined in: luya\testsuite\cases\BaseTestSuite::assertSameNoSpace()

This assert Same option allows you to compare two strings but removing spaces and tabes, so its more easy to work with readable contents but better comparing.

This wont remove new lines.

public boolean assertSameNoSpace ( $needle, $haystack )
$needle string
$haystack string

                public function assertSameNoSpace($needle, $haystack)
{
    return $this->assertSame($this->trimSpaces($needle), $this->trimSpaces($haystack));
}

            
assertSameTrimmed() public method (available since version 1.0.8)

Defined in: luya\testsuite\cases\BaseTestSuite::assertSameTrimmed()

Assert Same but trim content (remove, double spaces, tabs and newlines.

public boolean assertSameTrimmed ( $needle, $haystack )
$needle string
$haystack string

                public function assertSameTrimmed($needle, $haystack)
{
    return $this->assertSame($this->trimContent($needle), $this->trimContent($haystack));
}

            
assertUrlGetResponseContains() public method (available since version 1.0.3)

Test an url and see if the response contains.

public void assertUrlGetResponseContains ( $url, $contains, array $params = [] )
$url string|array

The base path on the current server. If array provided the first key is used as path and other values are merged with $params attribte.

$contains string|array

If its an array it will be json encoded by default and the first and last char (wrapping) brackets are cute off, so you can easy search for a key value parining inside the json response.

$params array

Optional parameters to bind url with

                public function assertUrlGetResponseContains($url, $contains, array $params = [])
{
    $curl = $this->createGetCurl($url, $params);
    $this->assertContains($this->buildPartialJson($contains, true), $curl->response);
}

            
assertUrlGetResponseSame() public method (available since version 1.0.3)

Make a GET request and see if the response is the same as.

public void assertUrlGetResponseSame ( $url, $same, array $params = [] )
$url string|array

The base path on the current server. If array provided the first key is used as path and other values are merged with $params attribte.

$same
$params array

Optional parameters to bind url with.

                public function assertUrlGetResponseSame($url, $same, array $params = [])
{
    $curl = $this->createGetCurl($url, $params);
    $this->assertSame($this->buildPartialJson($same), $curl->response);
}

            
assertUrlHomepageIsOk() public method (available since version 1.0.3)

Check whether homage is online and OK response.

public void assertUrlHomepageIsOk ( )

                public function assertUrlHomepageIsOk()
{
    $this->assertUrlIsOk(null);
}

            
assertUrlIsError() public method (available since version 1.0.3)

Test an URL whether a page has response code 400

public void assertUrlIsError ( $url, array $params = [] )
$url string|array

The base path on the current server. If array provided the first key is used as path and other values are merged with $params attribte.

$params array

Optional parameters to bind url with.

                public function assertUrlIsError($url, array $params = [])
{
    $curl = $this->createGetCurl($url, $params);
    $printUrl = $this->buildCallUrl($url, $params);
    $this->assertTrue($curl->isError(), "GET URL '{$printUrl}' return {$curl->http_status_code} instead of 400 (Error).");
}

            
assertUrlIsOk() public method (available since version 1.0.3)

Test an URL whether a page has response code 200

public void assertUrlIsOk ( $url, array $params = [] )
$url string|array

The base path on the current server. If array provided the first key is used as path and other values are merged with $params attribte.

$params array

Optional parameters to bind url with.

                public function assertUrlIsOk($url, array $params = [])
{
    $curl = $this->createGetCurl($url, $params);
    $printUrl = $this->buildCallUrl($url, $params);
    $this->assertTrue($curl->isSuccess(), "GET URL '{$printUrl}' return {$curl->http_status_code} instead of 200 (OK).");
}

            
assertUrlIsRedirect() public method (available since version 1.0.3)

Test whether url is redirect.

public void assertUrlIsRedirect ( $url, array $params = [] )
$url string|array

The base path on the current server. If array provided the first key is used as path and other values are merged with $params attribte.

$params array

Optional parameters to bind url with.

                public function assertUrlIsRedirect($url, array $params = [])
{
    $curl = $this->createGetCurl($url, $params);
    $printUrl = $this->buildCallUrl($url, $params);
    $this->assertTrue($curl->isRedirect(), "GET URL '{$printUrl}' return {$curl->http_status_code} instead of 300 (Error).");
}

            
assertUrlPostResponseContains() public method (available since version 1.0.3)

Make a POST request and see if the response contains in.

public void assertUrlPostResponseContains ( $url, $contains, array $data = [], array $params = [] )
$url string|array

The base path on the current server. If array provided the first key is used as path and other values are merged with $params attribte.

$contains string|array

If its an array it will be json encoded by default and the first and last char (wrapping) brackets are cute off, so you can easy search for a key value parining inside the json response.

$data array

The data to post on the $url ($_POST data)

$params array

Optional parameters to bind url with

                public function assertUrlPostResponseContains($url, $contains, array $data = [], array $params = [])
{
    $curl = $this->createPostCurl($url, $data, $params);
    $this->assertContains($this->buildPartialJson($contains, true), $curl->response);
}

            
assertUrlPostResponseSame() public method (available since version 1.0.3)

public void assertUrlPostResponseSame ( $url, $same, array $data = [], array $params = [] )
$url string|array
$same string|array
$data array
$params

                public function assertUrlPostResponseSame($url, $same, array $data = [], array $params = [])
{
    $curl = $this->createPostCurl($url, $data, $params);
    $this->assertSame($this->buildPartialJson($same), $curl->response);
}

            
beforeSetup() public method

Defined in: luya\testsuite\cases\BaseTestSuite::beforeSetup()

Method which is executed before the setUp() method in order to inject data on before Setup.

Make sure to call the parent beforeSetup() method when overwriting this method.

public void beforeSetup ( )

                public function beforeSetup()
{
}

            
beforeTearDown() public method (available since version 1.0.2)

This method is triggered before the application test case tearDown() method is running.

See also luya\testsuite\cases\BaseTestSuite::beforeTearDown().

public void beforeTearDown ( )

                public function beforeTearDown()
{
    $this->killServer($this->_pid);
    $this->waitForServerShutdown($this->host, $this->port);
}

            
bootApplication() public method (available since version 1.0.2)
public void bootApplication ( luya\base\Boot $boot )
$boot luya\base\Boot

                public function bootApplication(Boot $boot)
{
    $boot->applicationConsole();
}

            
bootstrapServer() protected method (available since version 1.0.2)

protected \luya\testsuite\cases\number bootstrapServer ( $host, $port, $documentRoot )
$host string
$port string
$documentRoot string
throws Exception

                protected function bootstrapServer($host, $port, $documentRoot)
{
    $documentRoot = Yii::getAlias($documentRoot);
    if ($this->connectToServer($host, $port)) {
        throw new Exception("The $host:$port is already taken, choose another host and/or port.");
    }
    
    $pid = $this->createServer($host, $port, $documentRoot);
    
    $this->waitForServer($host, $port);
    
    return $pid;
}

            
buildCallUrl() protected method (available since version 1.0.3)

Build the url to call with current local host and port.

If the url is an array the key is the path and the later key value paired are used for params.

buildCallUrl(['path/to/api', 'access-token' => 123]);

is equals to:

buildCallUrl('path/to/api', ['access-tokne' => 123]);
protected string buildCallUrl ( $url, array $params = [] )
$url string|array

The local base path to build the url from. If an array the first key is used for the path defintion.

$params array

Optional key value paired arguments to build the url from.

                protected function buildCallUrl($url, array $params = [])
{
    if (is_array($url)) {
        $path = $url[0];
        unset($url[0]);
        $params = array_merge($url, $params);
    } else {
        $path = $url;
    }
    
    $url = "{$this->host}:{$this->port}/" . ltrim($path, '/');
    
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }
    
    return $url;
}

            
buildPartialJson() protected method (available since version 1.0.3)

protected string buildPartialJson ( $contains, $removeBrackets false )
$contains string|array
$removeBrackets string

                protected function buildPartialJson($contains, $removeBrackets = false)
{
    if (is_array($contains)) {
        $contains = Json::encode($contains);
        if ($removeBrackets) {
            $contains = substr(substr($contains, 1), 0, -1);
        }
    }
    
    return $contains;
}

            
connectToServer() protected method (available since version 1.0.2)

protected boolean connectToServer ( $host, $port )
$host string
$port string

                protected function connectToServer($host, $port)
{
    $fp = @fsockopen($host, $port, $errno, $errstr, 3);
    if ($fp === false) {
        return false;
    }
    fclose($fp);
    return true;
}

            
createGetCurl() public method (available since version 1.0.3)

public \Curl\Curl createGetCurl ( $url, array $params = [] )
$url string
$params

                public function createGetCurl($url, array $params = [])
{
    $callUrl = $this->buildCallUrl($url, $params);
    $curl = (new Curl())->get($callUrl);
    
    if ($this->debug) {
        $this->debugMessage($callUrl, $curl);
    }
    
    return $curl;
}

            
createPostCurl() public method (available since version 1.0.3)

public \Curl\Curl createPostCurl ( $url, array $data = [], array $params = [] )
$url string
$data array
$params

                public function createPostCurl($url, array $data = [], array $params = [])
{
    $callUrl = $this->buildCallUrl($url, $params);
    $curl = (new Curl())->post($callUrl, $data);
    
    if ($this->debug) {
        $this->debugMessage($callUrl, $curl);
    }
    
    return $curl;
}

            
createServer() protected method (available since version 1.0.2)

protected void createServer ( $host, $port, $documentRoot )
$host string
$port string
$documentRoot string

                protected function createServer($host, $port, $documentRoot)
{
    $command = sprintf(PHP_BINARY . ' -S %s:%d -t %s >/dev/null 2>&1 & echo $!', $host, $port, $documentRoot);
    
    // Execute the command and store the process ID
    $output = [];
    exec($command, $output);
    
    return (int) $output[0];
}

            
debugMessage() protected method (available since version 1.0.24)

Print a echoing debug message for a curl request.

protected void debugMessage ( $url, \Curl\Curl $curl )
$url string
$curl \Curl\Curl

                protected function debugMessage($url, Curl $curl)
{
    echo PHP_EOL;
    echo "======================================================" . PHP_EOL;
    echo "REQUEST URL: " . $url . PHP_EOL;
    echo "------------------------------------------------------" . PHP_EOL;
    echo "REQUEST HEADERS:" . PHP_EOL;
    print_r($curl->request_headers) . PHP_EOL;
    echo "------------------------------------------------------" . PHP_EOL;
    echo "RESPONSE:" . PHP_EOL;
    echo $curl->response;
    echo "------------------------------------------------------" . PHP_EOL;
    echo "RESPONSE HEADERS:" . PHP_EOL;
    print_r($curl->response_headers) . PHP_EOL;
    echo "======================================================" . PHP_EOL;
    echo PHP_EOL;
}

            
fixture() public method

Defined in: luya\testsuite\cases\BaseTestSuite::fixture()

Get Fixture Object

public luya\testsuite\fixtures\ActiveRecordFixture fixture ( $fixtureClass )
$fixtureClass string

                public function fixture($fixtureClass)
{
    if (is_array($this->_fixtures)) {
        return array_key_exists($fixtureClass, $this->_fixtures) ? $this->_fixtures[$fixtureClass] : false;
    }
    return false;
}

            
fixtures() public method (available since version 1.1.0)

Defined in: luya\testsuite\cases\BaseTestSuite::fixtures()

Defines a list of fixtures classes which can be loaded.

Example fixtures list:

public function fixtures()
{
   return [
       'app\fixtures\MyTestFixture',
       MySuperFixture::class,
   ];
}
public array fixtures ( )

                public function fixtures()
{
    return [];
}

            
getConfigArray() public abstract method

Defined in: luya\testsuite\cases\BaseTestSuite::getConfigArray()

Provide Configurtion Array.

public abstract void getConfigArray ( )

                abstract public function getConfigArray();

            
invokeMethod() public method (available since version 1.0.8)

Defined in: luya\testsuite\cases\BaseTestSuite::invokeMethod()

Call a private or protected method from an object and return the value.

public function testProtectedMethod()
{
    // assuming MyObject has a protected method like:
    // protected function hello($title)
    // {
    //     return $title;
    // }
    $object = new MyObject();

    $this->assertSame('Hello World', $this->invokeMethod($object, 'hello', ['Hello World']));
}
public mixed invokeMethod ( &$object, $methodName, array $parameters = [] )
$object object

The object the method exists from.

$methodName string

The name of the method which should be called.

$parameters array

An array of paremters which should be passed to the method.

                public function invokeMethod(&$object, $methodName, array $parameters = [])
{
    $reflection = new \ReflectionClass(get_class($object));
    $method = $reflection->getMethod($methodName);
    $method->setAccessible(true);
    return $method->invokeArgs($object, $parameters);
}

            
killServer() protected method (available since version 1.0.2)

protected void killServer ( $pid )
$pid string

                protected function killServer($pid)
{
    exec('kill -9 ' . (int) $pid);
}

            
set_up() protected method

Defined in: luya\testsuite\cases\BaseTestSuite::set_up()

See also \PHPUnit\Framework\TestCase::setUp().

protected void set_up ( )

                protected function set_up() {
    parent::set_up();
    $this->beforeSetup();
    
    $boot = new Boot();
    $boot->setConfigArray($this->getConfigArray());
    $boot->mockOnly = true;
    $boot->setBaseYiiFile('vendor/yiisoft/yii2/Yii.php');
    $this->bootApplication($boot);
    $this->boot = $boot;
    $this->app = $boot->app;
    
    $this->afterSetup();
    $this->setupFixtures();
}

            
setupFixtures() public method (available since version 1.1.0)

Defined in: luya\testsuite\cases\BaseTestSuite::setupFixtures()

Create all fixtures from fixtures() list.

public void setupFixtures ( )

                public function setupFixtures()
{
    if ($this->_fixtures === null) {
        $loadedFixtures = [];
        foreach ($this->fixtures() as $fixtureClass) {
            $loadedFixtures[$fixtureClass] = Yii::createObject($fixtureClass);
        }
        $this->_fixtures = $loadedFixtures;
    }
}

            
tearDownFixtures() public method (available since version 1.1.0)

Defined in: luya\testsuite\cases\BaseTestSuite::tearDownFixtures()

Run cleanup() on all loaded fixtures.

public void tearDownFixtures ( )

                public function tearDownFixtures()
{
    if (is_array($this->_fixtures)) {
        /** @var ActiveRecordFixture $object */
        foreach ($this->_fixtures as $object) {
            $object->cleanup();
        }
    }
}

            
tear_down() protected method

Defined in: luya\testsuite\cases\BaseTestSuite::tear_down()

See also \PHPUnit\Framework\TestCase::tearDown().

protected void tear_down ( )

                protected function tear_down() {
    // Any clean up needed related to `set_up()`.
    parent::tear_down();
    $this->beforeTearDown();
    $this->tearDownFixtures();
    unset($this->app, $this->boot);
}

            
trimContent() protected method

Defined in: luya\testsuite\cases\BaseTestSuite::trimContent()

No Spaces and No Newline Trims the given text. Remove whitespaces, tabs and other chars in order to compare readable formated texts.

protected string trimContent ( $text )
$text string
return string

The trimmed text.

                protected function trimContent($text)
{
    return str_replace(['> ', ' <'], ['>', '<'], trim(preg_replace('/\s+/', ' ', $text)));
}

            
trimSpaces() protected method

Defined in: luya\testsuite\cases\BaseTestSuite::trimSpaces()

No Spaces with Newline

Removes tabs and spaces from a string. But keeps newlines.

protected string trimSpaces ( $text )
$text string

                protected function trimSpaces($text)
{
    $lines = null;
    foreach (preg_split("/((\r?\n)|(\r\n?))/", $text) as $line) {
        if (!empty($line)) {
            $lines .= $this->trimContent($line) . PHP_EOL;
        }
    }
    return $lines;
}

            
waitForServer() protected method (available since version 1.0.2)

protected boolean waitForServer ( $host, $port )
$host string
$port string

                protected function waitForServer($host, $port)
{
    $start = microtime(true);
    while (microtime(true) - $start <= (int) 200) {
        if ($this->connectToServer($host, $port)) {
            break;
        }
    }
    
    return true;
}

            
waitForServerShutdown() protected method (available since version 1.0.3)

protected boolean waitForServerShutdown ( $host, $port )
$host string
$port string

                protected function waitForServerShutdown($host, $port)
{
    $start = microtime(true);
    while (microtime(true) - $start <= (int) 200) {
        if (!$this->connectToServer($host, $port)) {
            break;
        }
    }
    
    return true;
}