Skip to content
Merged
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
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
},
"minimum-stability": "dev",
"require": {
"phpunit/phpunit": "^12.5"
"phpunit/phpunit": "^12.5",
"antecedent/patchwork": "2.2.3"
},
"autoload": {
"psr-4": {
Expand Down
52 changes: 50 additions & 2 deletions src/Visit.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class Visit
private string $redir_location = '';
private int $status_code = 0;
private array $cookies = [];
private array $mocks = [];

public function __construct(array $options = []) {
if (!empty($options))
Expand Down Expand Up @@ -76,6 +77,20 @@ public function assertRedirect(string $expected_path):Visit {
return $this;
}

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");
}

$this->mocks[$subject] = $callable;
return $this;
}

public function unmock($subject):Visit {
unset($this->mocks[$subject]);
return $this;
}

// Useful when followRedirect=false, so we have a function to go the
// redirected location. When followRedirect=true the redirection is
// automatic.
Expand All @@ -93,14 +108,17 @@ private function simulateRequest(string $method, string $path, ?string $data = n
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);

$old_redir_location = $this->redir_location;
$this->status_code = 0;
$this->redir_location = '';

$env = array_merge(getenv(),
['REQUEST_METHOD' => $method,
'REQUEST_URI' => $path,
'SCRIPT_NAME' => '/index.php',
'SCRIPT_NAME' => basename($script),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll merge this PR as it is, the SCRIPT_NAME includes the slash in our case (as it comes from nginx in this way), but it doesn't make any difference for us

Image

'SCRIPT_FILENAME' => $script,
'CONTENT_LENGTH' => ($data ? strlen($data): 0),
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
Expand Down Expand Up @@ -135,6 +153,9 @@ private function simulateRequest(string $method, string $path, ?string $data = n
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);

[$headers, $this->body] = explode("\r\n\r\n", $this->stdout, 2);
foreach (explode("\r\n", $headers) as $header) {
if (str_starts_with($header, 'Status: ')) {
Expand All @@ -151,7 +172,7 @@ private function simulateRequest(string $method, string $path, ?string $data = n
if (isset($status_line)) {
$this->status_code = intval($status_line);
if ($this->status_code == 302 && $old_redir_location == $this->redir_location) {
throw new Exception("Infinite redirection to $this->redir_location");
throw new \Exception("Infinite redirection to $this->redir_location");
}
}

Expand All @@ -166,4 +187,31 @@ private function simulateRequest(string $method, string $path, ?string $data = n
return $this;
}

private function generateMockedScript($script):string {
$mocksCode = "";
foreach ($this->mocks as $subject => $callableStr) {
$mocksCode .= "redefine('$subject', $callableStr);" . PHP_EOL;
}

$pathToPatchwork = $this->options['patchwork'];
$mockedScript = pathinfo($script, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . "_mocked_" . basename($script);
file_put_contents($mockedScript, <<<EOD
<?php
require_once "$pathToPatchwork";

use function Patchwork\{redefine};

$mocksCode

include "$script";
?>
EOD);

return $mockedScript;
}

private function removeMockedScript($script) {
unlink($script);
}

}
15 changes: 14 additions & 1 deletion tests/VisitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
use function IgaraStudio\visit;

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

final class VisitTest extends TestCase
{
Expand All @@ -37,4 +38,16 @@ public function test404(): void
{
visit('/not-found')->assertStatusCode(404);
}

public function testMocking(): void
{
visit('/bye')
->assertSee('Bye World')
->mock('bye_world', 'function() { return "I\'m a mock!"; }')
->get('/bye')
->assertSee("I'm a mock!")
->unmock('bye_world')
->get('/bye')
->assertSee('Bye World');
}
}
8 changes: 8 additions & 0 deletions tests/public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,15 @@
echo 'Final';
break;

case '/bye':
echo bye_world();
break;

default:
http_response_code(404);
break;
}

function bye_world() {
return "Bye World";
}