From a586041b84f402d8d5e4c71ad18a4fca32fdabb2 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Sat, 7 Apr 2018 09:26:47 +0100 Subject: [PATCH] Don't race waiting for a nil reference. (#289) Motivation: Unfortunately we cannot guarantee that a weak ref is going to be nil in a timely fashion if a strong reference to the object exists in another thread. This makes us fail tests on slow machines, which is bad. Modifications: Wait for up to a second for the other thread to get its house in order before we give up. Result: Hopefully I'll never have to "fix" this test again. --- Tests/NIOTests/ChannelTests.swift | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/Tests/NIOTests/ChannelTests.swift b/Tests/NIOTests/ChannelTests.swift index 86e99b0dc..dd1c340e7 100644 --- a/Tests/NIOTests/ChannelTests.swift +++ b/Tests/NIOTests/ChannelTests.swift @@ -17,6 +17,20 @@ import XCTest import NIOConcurrencyHelpers import Dispatch +func assert(_ condition: @autoclosure () -> Bool, within time: TimeAmount, testInterval: TimeAmount? = nil, _ message: String, file: StaticString = #file, line: UInt = #line) { + let testInterval = testInterval ?? TimeAmount.nanoseconds(time.nanoseconds / 5) + let endTime = DispatchTime.now().uptimeNanoseconds + UInt64(time.nanoseconds) + + repeat { + if condition() { return } + usleep(UInt32(testInterval.nanoseconds / 1000)) + } while (DispatchTime.now().uptimeNanoseconds < endTime) + + if !condition() { + XCTFail(message) + } +} + class ChannelLifecycleHandler: ChannelInboundHandler { public typealias InboundIn = Any @@ -1394,9 +1408,14 @@ public class ChannelTests: XCTestCase { } catch { XCTFail("wrong error \(error) received") } - XCTAssertNil(weakClientChannel, "weakClientChannel not nil, looks like we leaked it!") - XCTAssertNil(weakServerChannel, "weakServerChannel not nil, looks like we leaked it!") - XCTAssertNil(weakServerChildChannel, "weakServerChildChannel not nil, looks like we leaked it!") + + // Annoyingly it's totally possible to get to this stage and have the channels + // not yet be entirely freed on the background thread. There is no way we can guarantee + // that this hasn't happened, so we wait for up to a second to let this happen. If it hasn't + // happened in one second, we assume it never will. + assert(weakClientChannel == nil, within: .seconds(1), "weakClientChannel not nil, looks like we leaked it!") + assert(weakServerChannel == nil, within: .seconds(1), "weakServerChannel not nil, looks like we leaked it!") + assert(weakServerChildChannel == nil, within: .seconds(1), "weakServerChildChannel not nil, looks like we leaked it!") } func testAskForLocalAndRemoteAddressesAfterChannelIsClosed() throws {