Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 82 additions & 16 deletions src/Visit.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ class Visit
{
public static array $shared_options = [ 'docroot' => './public',
'script' => './public/index.php',
'followRedirect' => true ];
'followRedirect' => true,
// When true enables access to server
// data, like the $_SESSION superglobal.
'enableServerData' => false ];

private array $options;
private string $method;
Expand All @@ -31,12 +34,18 @@ class Visit
private int $status_code = 0;
private array $cookies = [];
private array $mocks = [];
private array $mockCodes = [];
private string $tmpdir;
private string $tmpfile = '';
private array $data = [];

public function __construct(array $options = []) {
if (!empty($options))
$this->options = array_merge(self::$shared_options, $options);
else
$this->options = self::$shared_options;

$this->tmpdir = '_test_output_' . base64_encode(random_bytes(5));
}

public function setOptions(array $options):Visit {
Expand Down Expand Up @@ -97,6 +106,10 @@ public function assertStderrContains(string $expected_str):Visit {
return $this;
}

public function assertSession(string $key, $expected) {
assertEquals($expected, $this->data('_SESSION')[$key] ?? null);
}

public function mock($subject, string $callable):Visit {
if (empty($this->options['patchwork'])) {
throw new \Exception("Cannot use mocks, option 'patchwork' (path to Patchwork.php) was not provided");
Expand All @@ -111,6 +124,25 @@ public function unmock($subject):Visit {
return $this;
}

public function mockCode(string $phpCode):Visit {
array_push($this->mockCodes, $phpCode);
return $this;
}

public function clearMockCodes():Visit {
$this->mockCodes = [];
return $this;
}

/**
* Returns state of data at the server.
* Valid keys:
* '_SESSION' => returns $_SESSION superglobal
*/
public function data($key) {
return $this->data[$key] ?? null;
}

// Useful when followRedirect=false, so we have a function to go the
// redirected location. When followRedirect=true the redirection is
// automatic.
Expand All @@ -131,8 +163,8 @@ public function request(string $method,
if (!file_exists($script))
die("File $script doesn't exist to be called with php-cgi\n");

if (count($this->mocks))
$script = $this->generateMockedScript($script);
if ($this->mustWrapScript())
$script = $this->wrapScript($script);

$old_redir_location = $this->redir_location;
$this->status_code = 0;
Expand Down Expand Up @@ -180,8 +212,8 @@ public function request(string $method,
assertEquals(0, $status,
"$this->method $this->path : Procedure to handle request failed with status $status.\nOutput: $this->stdout\nError: $this->stderr");

if (count($this->mocks))
$this->removeMockedScript($script);
if ($this->mustWrapScript())
$this->removeWrappedScript($script);

[$headers, $this->body] = explode("\r\n\r\n", $this->stdout, 2);
foreach (explode("\r\n", $headers) as $header) {
Expand Down Expand Up @@ -210,21 +242,50 @@ public function request(string $method,
return $this;
}

private function generateMockedScript($script):string {
$mocksCode = "";
foreach ($this->mocks as $subject => $callableStr) {
$mocksCode .= "redefine('$subject', $callableStr);" . PHP_EOL;
private function mustWrapScript():bool {
return !empty($this->mocks) ||
!empty($this->mockCodes) ||
($this->options['enableServerData'] ?? false);
}

private function wrapScript($script):string {
$code = "";

if ($this->options['enableServerData'] ?? false) {
$this->tmpfile = tempnam($this->tmpdir, 'DATA');
$code .= <<<EOD
register_shutdown_function(function() {
file_put_contents('{$this->tmpfile}',
serialize(['_SESSION' => \$_SESSION]));
});
EOD.PHP_EOL;
}

$pathToPatchwork = $this->options['patchwork'] ?? '';
$generateMocks = !empty($pathToPatchwork) && !empty($this->mocks);
if ($generateMocks) {
$code .= <<<EOD
require_once "$pathToPatchwork";

use function Patchwork\{redefine};
EOD.PHP_EOL;
}

$pathToPatchwork = $this->options['patchwork'];
$mockedScript = pathinfo($script, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . "_mocked_" . basename($script);
foreach ($this->mockCodes as $mockCode) {
$code .= $mockCode . PHP_EOL;
}

if ($generateMocks) {
foreach ($this->mocks as $subject => $callableStr) {
$code .= "redefine('$subject', $callableStr);" . PHP_EOL;
}
}

$mockedScript = pathinfo($script, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . "_wrapped_" . basename($script);
file_put_contents($mockedScript, <<<EOD
<?php
require_once "$pathToPatchwork";

use function Patchwork\{redefine};

$mocksCode
$code

include "$script";
?>
Expand All @@ -233,8 +294,13 @@ private function generateMockedScript($script):string {
return $mockedScript;
}

private function removeMockedScript($script) {
private function removeWrappedScript($script) {
unlink($script);
if (!empty($this->tmpfile)) {
$content = file_get_contents($this->tmpfile);
$this->data = unserialize($content);
unlink($this->tmpfile);
}
}

}
36 changes: 35 additions & 1 deletion tests/VisitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@

Visit::$shared_options = [ 'docroot' => __DIR__ . '/public',
'script' => __DIR__ . '/public/index.php',
'patchwork' => __DIR__ . '/../vendor/antecedent/patchwork/Patchwork.php'];
'patchwork' => __DIR__ . '/../vendor/antecedent/patchwork/Patchwork.php',
'enableServerData' => false ];

final class VisitTest extends TestCase
{
Expand Down Expand Up @@ -63,6 +64,26 @@ public function testMocking(): void
->assertSee('Bye World');
}

public function testMockingCode(): void
{
visit('/bye')
->assertSee('Bye World')
->mockCode(<<<PHP
class Message {
public function __toString() {
return "I'm a message from a mocked object!";
}
}
PHP)
->mock('bye_world', 'function() { return new Message(); }')
->get('/bye')
->assertSee("I'm a message from a mocked object!")
->clearMockCodes()
->unmock('bye_world')
->get('/bye')
->assertSee('Bye World');
}

public function testPostJson(): void
{
visit()->postJson("/json",
Expand All @@ -75,4 +96,17 @@ public function testPostWithQueryString(): void
visit()->post('/query?v1=abcd&v2=300', ["v3" => "45.6"])
->assertSee("v1: abcd; v2: 300; v3: 45.6");
}

public function testSession(): void
{
// Without enableServerData
visit()
->post('/session', ["id" => 1234])
->assertSession('id', null);

// With enableServerData
visit(options: ['enableServerData' => true])
->post('/session', ["id" => 1234])
->assertSession('id', 1234);
}
}
4 changes: 4 additions & 0 deletions tests/public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
echo "v1: {$_GET['v1']}; v2: {$_GET['v2']}; v3: {$_POST['v3']}";
break;

case '/session':
$_SESSION['id'] = $_POST['id'];
echo "Id stored in session";
break;
default:
http_response_code(404);
break;
Expand Down