Skip to content

Commit 10f05be

Browse files
format
1 parent 384c6d5 commit 10f05be

File tree

1 file changed

+44
-7
lines changed

1 file changed

+44
-7
lines changed

tests/TestServer.php

+44-7
Original file line numberDiff line numberDiff line change
@@ -76,18 +76,41 @@ public function startTestServer($code)
7676
throw new \Exception("Error starting test server on pid {$pid}, command failed: {$command}");
7777
}
7878

79-
while ($r = \fgets($this->serverStderr)) {
80-
if (\str_contains($r, 'started')) {
79+
while (true) {
80+
$conn = @\fsockopen('localhost', $this->serverPort);
81+
if (\is_resource($conn)) {
82+
\fclose($conn);
83+
8184
break;
8285
}
83-
if (\str_contains($r, 'Failed')) {
84-
throw new \Exception("Error starting test server on pid {$pid}: " . $r . ' Was the port ' . $this->serverPort . ' already taken?');
85-
}
86+
\fclose($conn);
8687
}
8788

8889
return 'localhost:' . $this->serverPort;
8990
}
9091

92+
/**
93+
* Dirty way to parse the stderr of `php -S` to see how many
94+
* requests were sent. Not robust -- and the format of the
95+
* output changes from PHP version to PHP version, so beware.
96+
*
97+
* @param mixed $s
98+
*/
99+
private static function isPHPTestServerRequestLogLine($s)
100+
{
101+
if (\str_contains($s, 'Accepted')) {
102+
return false;
103+
}
104+
if (\str_contains($s, 'Closing')) {
105+
return false;
106+
}
107+
108+
// Lines start with a left square bracket, and contain
109+
// a status code in brackets followed by a colon, like [200]:
110+
// or [404]:
111+
return \preg_match('/^\[.*\[[0-9]{3}\]:/', $s);
112+
}
113+
91114
/**
92115
* Stops the test server and returns the number of requests
93116
* as indicated the logs in its stderr.
@@ -102,19 +125,33 @@ public function stopTestServer()
102125
\stream_set_blocking($this->serverStderr, false);
103126
$lines = \explode(\PHP_EOL, \stream_get_contents($this->serverStderr));
104127
foreach ($lines as $line) {
105-
if (\str_contains($line, 'Accepted')) {
128+
if (self::isPHPTestServerRequestLogLine($line)) {
106129
++$n;
130+
} else {
131+
\flush();
132+
\ob_flush();
107133
}
108134
}
109-
while (true) {
135+
136+
for ($i = 0; $i < 20; ++$i) {
110137
$status = \proc_get_status($this->serverProc);
111138
if (!$status['running']) {
112139
break;
113140
}
114141
$pid = $status['pid'];
142+
// Kills any child processes -- the php test server
143+
// appears to start up a child.
115144
\exec("pkill -P {$pid}");
145+
146+
// Kill the parent process.
147+
\exec("kill {$pid}");
116148
\usleep(100000);
117149
}
150+
151+
if ($status['running']) {
152+
throw new Exception('Could not kill test server');
153+
}
154+
118155
// echo "Terminated test server on pid $pid\n";
119156
\fclose($this->serverStderr);
120157
\proc_close($this->serverProc);

0 commit comments

Comments
 (0)