Skip to content

Commit

Permalink
Wrap the socket creation in a function
Browse files Browse the repository at this point in the history
  • Loading branch information
tonysm committed Dec 18, 2024
1 parent b314256 commit f82efcc
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions tests/Feature/EnvironmentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,23 @@ public function it_detects_a_port_conflict()
$environment = app(Environment::class);
$this->assertTrue($environment->portIsAvailable($port));

$this->withFakeProcess($port, fn() => (
$this->assertFalse($environment->portIsAvailable($port))
));
}

private function withFakeProcess(int $port, $callback)
{
$socket = socket_create(domain: AF_INET, type: SOCK_STREAM, protocol: SOL_TCP);
assert($socket !== false, 'Was not able to create a socket.');
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
assert(socket_bind($socket, 'localhost', $port) !== false, "Was not able to bind socket to port {$port}");
assert(socket_listen($socket, backlog: 5));

$this->assertFalse($environment->portIsAvailable($port));
socket_close($socket);
try {
$callback();
} finally {
socket_close($socket);
}
}
}

0 comments on commit f82efcc

Please sign in to comment.