Skip to content

Commit 78ca647

Browse files
committed
Stop internal http server on test case tear down
Leaving server running consumes one thread from Dispatch global thread pool per one started LoopbackServerTest. There are 5 such test cases at the moment. On non-Darwin platforms thread pool size is extremely small (equals to the number of CPU cores), and TestFoundation test case quickly becomes unstable on some machines (e.g. cloud VMs with 2-core CPUs).
1 parent 9966689 commit 78ca647

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

Tests/Foundation/HTTPServer.swift

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ class _TCPSocket {
239239
}
240240
}
241241

242-
deinit {
242+
func closeSocket() throws {
243243
guard _socket != nil else { return }
244244
#if os(Windows)
245245
if listening { shutdown(_socket, SD_BOTH) }
@@ -248,6 +248,11 @@ class _TCPSocket {
248248
if listening { shutdown(_socket, CInt(SHUT_RDWR)) }
249249
close(_socket)
250250
#endif
251+
_socket = nil
252+
}
253+
254+
deinit {
255+
try? closeSocket()
251256
}
252257
}
253258

@@ -311,6 +316,10 @@ class _HTTPServer {
311316
return _HTTPServer(socket: connection)
312317
}
313318

319+
public func stop() throws {
320+
try tcpSocket.closeSocket()
321+
}
322+
314323
public func request() throws -> _HTTPRequest {
315324

316325
var reader = _SocketDataReader(socket: tcpSocket)
@@ -960,7 +969,9 @@ class LoopbackServerTest : XCTestCase {
960969
try? subServer.readAndRespond()
961970
}
962971
} catch {
963-
NSLog("httpServer: \(error)")
972+
if (serverActive) { // Ignore errors thrown on shutdown
973+
NSLog("httpServer: \(error)")
974+
}
964975
}
965976
}
966977
serverPort = -2
@@ -984,6 +995,7 @@ class LoopbackServerTest : XCTestCase {
984995

985996
override class func tearDown() {
986997
serverActive = false
998+
try? testServer?.stop()
987999
super.tearDown()
9881000
}
9891001
}

0 commit comments

Comments
 (0)