How to use testWaitUntilTimesOutWhenExceedingItsTime method of ClassUnderTest class

Best Nimble code snippet using ClassUnderTest.testWaitUntilTimesOutWhenExceedingItsTime

Run Nimble automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

AsynchronousTest.swift

Source: AsynchronousTest.swift Github

copy
1import Dispatch
2import Foundation
3import XCTest
4import Nimble
5
6final class AsyncTest: XCTestCase, XCTestCaseProvider {
7    static var allTests: [(String, (AsyncTest) -> () throws -> Void)] {
8        return [
9            ("testToEventuallyPositiveMatches", testToEventuallyPositiveMatches),
10            ("testToEventuallyNegativeMatches", testToEventuallyNegativeMatches),
11            ("testWaitUntilPositiveMatches", testWaitUntilPositiveMatches),
12            ("testToEventuallyWithCustomDefaultTimeout", testToEventuallyWithCustomDefaultTimeout),
13            ("testWaitUntilTimesOutIfNotCalled", testWaitUntilTimesOutIfNotCalled),
14            ("testWaitUntilTimesOutWhenExceedingItsTime", testWaitUntilTimesOutWhenExceedingItsTime),
15            ("testWaitUntilNegativeMatches", testWaitUntilNegativeMatches),
16            ("testWaitUntilDetectsStalledMainThreadActivity", testWaitUntilDetectsStalledMainThreadActivity),
17            ("testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed", testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed),
18            ("testWaitUntilErrorsIfDoneIsCalledMultipleTimes", testWaitUntilErrorsIfDoneIsCalledMultipleTimes),
19            ("testWaitUntilMustBeInMainThread", testWaitUntilMustBeInMainThread),
20            ("testToEventuallyMustBeInMainThread", testToEventuallyMustBeInMainThread),
21            ("testSubjectUnderTestIsReleasedFromMemory", testSubjectUnderTestIsReleasedFromMemory),
22        ]
23    }
24
25    class Error: Swift.Error {}
26    let errorToThrow = Error()
27
28    private func doThrowError() throws -> Int {
29        throw errorToThrow
30    }
31
32    func testToEventuallyPositiveMatches() {
33        var value = 0
34        deferToMainQueue { value = 1 }
35        expect { value }.toEventually(equal(1))
36
37        deferToMainQueue { value = 0 }
38        expect { value }.toEventuallyNot(equal(1))
39    }
40
41    func testToEventuallyNegativeMatches() {
42        let value = 0
43        failsWithErrorMessage("expected to eventually not equal <0>, got <0>") {
44            expect { value }.toEventuallyNot(equal(0))
45        }
46        failsWithErrorMessage("expected to eventually equal <1>, got <0>") {
47            expect { value }.toEventually(equal(1))
48        }
49        failsWithErrorMessage("unexpected error thrown: <\(errorToThrow)>") {
50            expect { try self.doThrowError() }.toEventually(equal(1))
51        }
52        failsWithErrorMessage("unexpected error thrown: <\(errorToThrow)>") {
53            expect { try self.doThrowError() }.toEventuallyNot(equal(0))
54        }
55    }
56
57    func testToEventuallyWithCustomDefaultTimeout() {
58        AsyncDefaults.Timeout = 2
59        defer {
60            AsyncDefaults.Timeout = 1
61        }
62
63        var value = 0
64
65        let sleepThenSetValueTo: (Int) -> Void = { newValue in
66            Thread.sleep(forTimeInterval: 1.1)
67            value = newValue
68        }
69
70        var asyncOperation: () -> Void = { sleepThenSetValueTo(1) }
71
72        if #available(OSX 10.10, *) {
73            DispatchQueue.global().async(execute: asyncOperation)
74        } else {
75            DispatchQueue.global(priority: .default).async(execute: asyncOperation)
76        }
77        expect { value }.toEventually(equal(1))
78
79        asyncOperation = { sleepThenSetValueTo(0) }
80
81        if #available(OSX 10.10, *) {
82            DispatchQueue.global().async(execute: asyncOperation)
83        } else {
84            DispatchQueue.global(priority: .default).async(execute: asyncOperation)
85        }
86        expect { value }.toEventuallyNot(equal(1))
87    }
88
89    func testWaitUntilPositiveMatches() {
90        waitUntil { done in
91            done()
92        }
93        waitUntil { done in
94            deferToMainQueue {
95                done()
96            }
97        }
98    }
99
100    func testWaitUntilTimesOutIfNotCalled() {
101        failsWithErrorMessage("Waited more than 1.0 second") {
102            waitUntil(timeout: 1) { _ in return }
103        }
104    }
105
106    func testWaitUntilTimesOutWhenExceedingItsTime() {
107        var waiting = true
108        failsWithErrorMessage("Waited more than 0.01 seconds") {
109            waitUntil(timeout: 0.01) { done in
110                let asyncOperation: () -> Void = {
111                    Thread.sleep(forTimeInterval: 0.1)
112                    done()
113                    waiting = false
114                }
115                if #available(OSX 10.10, *) {
116                    DispatchQueue.global().async(execute: asyncOperation)
117                } else {
118                    DispatchQueue.global(priority: .default).async(execute: asyncOperation)
119                }
120            }
121        }
122
123        // "clear" runloop to ensure this test doesn't poison other tests
124        repeat {
125            RunLoop.main.run(until: Date().addingTimeInterval(0.2))
126        } while(waiting)
127    }
128
129    func testWaitUntilNegativeMatches() {
130        failsWithErrorMessage("expected to equal <2>, got <1>") {
131            waitUntil { done in
132                Thread.sleep(forTimeInterval: 0.1)
133                expect(1).to(equal(2))
134                done()
135            }
136        }
137    }
138
139    func testWaitUntilDetectsStalledMainThreadActivity() {
140        let msg = "-waitUntil() timed out but was unable to run the timeout handler because the main thread is unresponsive (0.5 seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run."
141        failsWithErrorMessage(msg) {
142            waitUntil(timeout: 1) { done in
143                Thread.sleep(forTimeInterval: 5.0)
144                done()
145            }
146        }
147    }
148
149    func testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed() {
150        // Currently we are unable to catch Objective-C exceptions when built by the Swift Package Manager
151#if !SWIFT_PACKAGE
152        let referenceLine = #line + 9
153        var msg = "Unexpected exception raised: Nested async expectations are not allowed "
154        msg += "to avoid creating flaky tests."
155        msg += "\n\n"
156        msg += "The call to\n\t"
157        msg += "expect(...).toEventually(...) at \(#file):\(referenceLine + 7)\n"
158        msg += "triggered this exception because\n\t"
159        msg += "waitUntil(...) at \(#file):\(referenceLine + 1)\n"
160        msg += "is currently managing the main run loop."
161        failsWithErrorMessage(msg) { // reference line
162            waitUntil(timeout: 2.0) { done in
163                var protected: Int = 0
164                DispatchQueue.main.async {
165                    protected = 1
166                }
167
168                expect(protected).toEventually(equal(1))
169                done()
170            }
171        }
172#endif
173    }
174
175    func testWaitUntilErrorsIfDoneIsCalledMultipleTimes() {
176        failsWithErrorMessage("waitUntil(..) expects its completion closure to be only called once") {
177            waitUntil { done in
178                deferToMainQueue {
179                    done()
180                    done()
181                }
182            }
183        }
184    }
185
186    func testWaitUntilMustBeInMainThread() {
187#if !SWIFT_PACKAGE
188        var executedAsyncBlock: Bool = false
189        let asyncOperation: () -> Void = {
190            expect {
191                waitUntil { done in done() }
192            }.to(raiseException(named: "InvalidNimbleAPIUsage"))
193            executedAsyncBlock = true
194        }
195        if #available(OSX 10.10, *) {
196            DispatchQueue.global().async(execute: asyncOperation)
197        } else {
198            DispatchQueue.global(priority: .default).async(execute: asyncOperation)
199        }
200        expect(executedAsyncBlock).toEventually(beTruthy())
201#endif
202    }
203
204    func testToEventuallyMustBeInMainThread() {
205#if !SWIFT_PACKAGE
206        var executedAsyncBlock: Bool = false
207        let asyncOperation: () -> Void = {
208            expect {
209                expect(1).toEventually(equal(2))
210            }.to(raiseException(named: "InvalidNimbleAPIUsage"))
211            executedAsyncBlock = true
212        }
213        if #available(OSX 10.10, *) {
214            DispatchQueue.global().async(execute: asyncOperation)
215        } else {
216            DispatchQueue.global(priority: .default).async(execute: asyncOperation)
217        }
218        expect(executedAsyncBlock).toEventually(beTruthy())
219#endif
220    }
221
222    final class ClassUnderTest {
223        var deinitCalled: (() -> Void)?
224        var count = 0
225        deinit { deinitCalled?() }
226    }
227
228    func testSubjectUnderTestIsReleasedFromMemory() {
229        var subject: ClassUnderTest? = ClassUnderTest()
230
231        if let sub = subject {
232            expect(sub.count).toEventually(equal(0), timeout: 0.1)
233            expect(sub.count).toEventuallyNot(equal(1), timeout: 0.1)
234        }
235
236        waitUntil(timeout: 0.5) { done in
237            subject?.deinitCalled = {
238                done()
239            }
240
241            deferToMainQueue { subject = nil }
242        }
243    }
244
245}
246
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)