Skip to content

Commit

Permalink
Started writing Unit tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
rotimi committed May 7, 2024
1 parent e4560db commit 6efa847
Show file tree
Hide file tree
Showing 5 changed files with 176 additions and 20 deletions.
21 changes: 20 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,37 @@
},
"require-dev": {
"phpunit/phpunit": "^10.0",
"rector/rector": "^1.0"
"rector/rector": "^1.0",
"guzzlehttp/guzzle": "^7.8"
},
"autoload": {
"classmap": [ "src/", "tests/", "vendor/slim/" ]
},
"scripts": {
"test": [
"Composer\\Config::disableProcessTimeout",
"vendor/bin/phpunit --coverage-text"
],
"post-create-project-cmd": [
"SMVC_PostComposerCreateHandler::exec",
"php -r \" unlink('./src/smvc-tools/post-composer-create-project.php'); \" ",
"php -r \" unlink('./src/smvc-tools/.gitkeep'); \" ",
"php -r \" rmdir('./src/smvc-tools'); \" ",
"@composer update -o --no-dev"
],
"post-install-cmd": [
"@php -r \"file_exists('./config/env.php') || copy('./config/env-dist.php', './config/env.php');\"",
"@php -r \"file_exists('./config/routes-and-middlewares.php') || copy('./config/routes-and-middlewares-dist.php', './config/routes-and-middlewares.php');\"",
"@php -r \"file_exists('./config/ini-settings.php') || copy('./config/ini-settings-dist.php', './config/ini-settings.php');\"",
"@php -r \"file_exists('./config/dependencies.php') || copy('./config/dependencies-dist.php', './config/dependencies.php');\"",
"@php -r \"file_exists('./config/app-settings.php') || copy('./config/app-settings-dist.php', './config/app-settings.php');\""
],
"post-update-cmd": [
"@php -r \"file_exists('./config/env.php') || copy('./config/env-dist.php', './config/env.php');\"",
"@php -r \"file_exists('./config/routes-and-middlewares.php') || copy('./config/routes-and-middlewares-dist.php', './config/routes-and-middlewares.php');\"",
"@php -r \"file_exists('./config/ini-settings.php') || copy('./config/ini-settings-dist.php', './config/ini-settings.php');\"",
"@php -r \"file_exists('./config/dependencies.php') || copy('./config/dependencies-dist.php', './config/dependencies.php');\"",
"@php -r \"file_exists('./config/app-settings.php') || copy('./config/app-settings-dist.php', './config/app-settings.php');\""
]
},
"suggest": {
Expand Down
39 changes: 20 additions & 19 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./tests/bootstrap.php" colors="true">
<testsuites>
<testsuite>
<directory>./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="build/coverage" title="slim-skeleton-mvc-app"
charset="UTF-8" yui="true" highlight="true"
lowUpperBound="35" highLowerBound="70"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="junit" target="build/logs/junit.xml"
logIncompleteSkipped="false"/>
</logging>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="./tests/bootstrap.php" colors="true" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd">
<coverage>
<report>
<clover outputFile="build/logs/clover.xml"/>
<html outputDirectory="build/coverage" lowUpperBound="35" highLowerBound="70"/>
</report>
</coverage>
<testsuites>
<testsuite name="all-tests">
<directory>./tests</directory>
</testsuite>
</testsuites>
<logging>
<junit outputFile="build/logs/junit.xml"/>
</logging>
<source>
<include>
<directory suffix=".php">./src</directory>
</include>
</source>
</phpunit>
14 changes: 14 additions & 0 deletions src/controllers/Hello.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,18 @@ public function actionThere($first_name, $last_name): string {

return $this->renderLayout($this->layout_template_file_name, ['content'=>$view_str] );
}

public function actionForceHttp4xxOr5xx($http_code=400) {

$allowed_codes = [400, 401, 403, 404, 405, 410, 500, 501];

if(\in_array($http_code, $allowed_codes)) {

$method = "forceHttp{$http_code}";
$message = "Forced HTTP {$http_code}";
$this->$method($message);
}

return $this->renderLayout($this->layout_template_file_name, ['content'=> "Could not force http response with code: `{$http_code}`"] );
}
}
118 changes: 118 additions & 0 deletions tests/AllRoutesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);

namespace SlimSkeletonMvcApp\Tests;

use \GuzzleHttp\Client;

/**
* Description of AllRoutesTest
*
* @author rotimi
*/
#[CoversClass(\SlimSkeletonMvcApp\Controllers\Hello::class)]
class AllRoutesTest extends \PHPUnit\Framework\TestCase {

protected static string $process_id;
protected static int $web_server_port = 8080;
protected static string $web_server_host = 'localhost';
protected static string $web_server_docroot = "./public";

public static function setUpBeforeClass():void {

static::$web_server_host = (getenv('WEBSERVER_HOST') !== false) ? getenv('WEBSERVER_HOST') : static::$web_server_host;
static::$web_server_port = (getenv('WEBSERVER_PORT') !== false) ? ((int)getenv('WEBSERVER_PORT')) : static::$web_server_port;
static::$web_server_docroot = (getenv('WEBSERVER_DOCROOT') !== false) ? getenv('WEBSERVER_DOCROOT') : static::$web_server_docroot;

// Command that starts the built-in web server
$command = sprintf(
'php -S %s:%d -t %s >/dev/null 2>&1 & echo $!',
static::$web_server_host,
static::$web_server_port,
static::$web_server_docroot
);

// Execute the command and store the process ID
$output = [];
exec($command, $output);
self::$process_id = ''. $output[0];


echo sprintf(
'%s - Web server started on %s:%d with PID %d',
date('r'),
static::$web_server_host,
static::$web_server_port,
self::$process_id
) . PHP_EOL . PHP_EOL;

sleep(5); //wait for server to get going
}

public static function tearDownAfterClass():void {

echo PHP_EOL . PHP_EOL . sprintf('%s - Killing builtin PHP webserver process with ID %s', \date('r'), static::$process_id) . PHP_EOL;
exec('kill ' . static::$process_id);
}

public function test404() {

$client = new Client(['http_errors' => false]);

$web_server_host = static::$web_server_host;
$web_server_port = static::$web_server_port;
$response = $client->request("GET", "http://{$web_server_host}:{$web_server_port}/non-existent-path");

self::assertEquals(404, $response->getStatusCode());

// The html page returned
$reponse_body = ((string)$response->getBody());

self::assertStringContainsString("<div><strong>Type:</strong> Slim\Exception\HttpNotFoundException</div><div><strong>", $reponse_body);
self::assertStringContainsString("Class `NonExistentPath` does not exist.", $reponse_body);
self::assertStringContainsString('<a href="#" onclick="window.history.go(-1)">Go Back</a>', $reponse_body);
}

public function testHttp4xxAnd5xx() {

$client = new Client(['http_errors' => false]);

$web_server_host = static::$web_server_host;
$web_server_port = static::$web_server_port;
$http_codes = [400, 401, 403, 405, 410, 500, 501];

foreach($http_codes as $http_code) {

$response = $client->request("GET", "http://{$web_server_host}:{$web_server_port}/hello/action-force-http-4xx-or-5xx/{$http_code}");

self::assertEquals($http_code, $response->getStatusCode());

// The html page returned
$reponse_body = ((string)$response->getBody());

self::assertStringContainsString("Forced HTTP {$http_code}", $reponse_body);
self::assertStringContainsString('<a href="#" onclick="window.history.go(-1)">Go Back</a>', $reponse_body);

} // foreach($http_codes as $http_code)
}

public function testBaseControllerActionIndex() {

$client = new Client(['http_errors' => false]);

$web_server_host = static::$web_server_host;
$web_server_port = static::$web_server_port;
$response = $client->request("GET", "http://{$web_server_host}:{$web_server_port}/base-controller/action-index");

self::assertEquals(200, $response->getStatusCode());

// The html page returned
$reponse_body = ((string)$response->getBody());

self::assertStringContainsString("<h1>Welcome to Your New Site</h1>", $reponse_body);
self::assertStringContainsString("SlimPHP 4 Skeleton MVC App.", $reponse_body);
self::assertStringContainsString('<h4><strong>Below are the default links that are available in your application:</strong></h4>', $reponse_body);
self::assertStringContainsString('<h4><strong>A little bit about Controllers and MVC:</strong></h4>', $reponse_body);
self::assertStringContainsString('Copyright no one at all. Go to town. </p>', $reponse_body);
}
}
4 changes: 4 additions & 0 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
error_reporting(E_ALL);

require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'vendor/autoload.php';

0 comments on commit 6efa847

Please sign in to comment.