From 9b83d91047588c84a3cabb6ee2015ea2dd13832c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Rodr=C3=ADguez=20Troiti=C3=B1o?= Date: Wed, 7 Aug 2019 15:15:17 -0700 Subject: [PATCH] [gardening] Migrate from unwrapped() to XCTUnwrap() Instead of using an extension on Optional only available in Foundation, we should start using the recently introduced XCTUnwrap available in XCTest to perform the same job. The XCTest API would probably be more known in other code bases, so people will be more willing to use it and learn it. The commit removes all the usages of unwrapped and replaces them with XCTUnwrap. Additionally it marks unwrapped() as deprecated, so people receive a clear message about the disappearance with a helpful hint of what to use instead. --- Docs/Testing.md | 8 +- TestFoundation/FixtureValues.swift | 8 +- TestFoundation/TestCachedURLResponse.swift | 28 +++--- TestFoundation/TestCalendar.swift | 10 +-- TestFoundation/TestDateFormatter.swift | 6 +- .../TestDateIntervalFormatter.swift | 12 +-- TestFoundation/TestDecimal.swift | 8 +- TestFoundation/TestFileManager.swift | 14 +-- TestFoundation/TestHTTPCookie.swift | 40 ++++----- TestFoundation/TestNSCalendar.swift | 86 +++++++++---------- TestFoundation/TestNSString.swift | 10 +-- TestFoundation/TestObjCRuntime.swift | 2 +- TestFoundation/TestPipe.swift | 4 +- TestFoundation/TestScanner.swift | 2 +- TestFoundation/TestSocketPort.swift | 10 +-- TestFoundation/TestTimeZone.swift | 12 +-- TestFoundation/TestURL.swift | 2 +- TestFoundation/TestURLCache.swift | 6 +- TestFoundation/TestURLCredentialStorage.swift | 14 +-- TestFoundation/TestURLRequest.swift | 2 +- TestFoundation/TestURLResponse.swift | 20 ++--- TestFoundation/TestURLSession.swift | 30 +++---- TestFoundation/Utilities.swift | 10 +-- .../GenerateTestFixtures/Utilities.swift | 16 ++-- 24 files changed, 177 insertions(+), 183 deletions(-) diff --git a/Docs/Testing.md b/Docs/Testing.md index eb0147264b..b000a2a144 100644 --- a/Docs/Testing.md +++ b/Docs/Testing.md @@ -7,7 +7,7 @@ swift-corelibs-foundation uses XCTest for its own test suite. This document expl ### In brief * Tests should fail rather than crashing; swift-corelibs-xctest does not implement any crash recovery -* You should avoid forced optional unwrapping (e.g.: `aValue!`). Use `try aValue.unwrapped()` instead +* You should avoid forced optional unwrapping (e.g.: `aValue!`). Use `try XCTUnwrap(aValue)` instead * You can test code that is expected to crash; you must mark the whole body of the test method with `assertCrashes(within:)` * If a test or a portion of a test is giving the build trouble, use `testExpectedToFail` and write a bug @@ -19,7 +19,7 @@ Due to this, it is important to avoid crashing in test code, and to properly han #### Avoiding Forced Unwrapping -Forced unwrapping is easily the easiest way to crash the test process, and should be avoided. We have an ergonomic replacement in the form of the `.unwrapped()` extension method on the `Optional` type. +Forced unwrapping is easily the easiest way to crash the test process, and should be avoided. XCTest have an ergonomic replacement in the form of the `XCTUnwrap()` function. The following code is a liability and code review should flag it: @@ -34,14 +34,14 @@ func testSomeInterestingAPI() { Instead: 1. Change the test method to throw errors by adding the `throws` clause. Tests that throw errors will fail and stop the first time an error is thrown, so plan accordingly, but a thrown error will not stop the test run, merely fail this test. -2. Change the forced unwrapping to `try ….unwrapped()`. +2. Change the forced unwrapping to `try XCTUnwrap(…)`. For example, the code above can be fixed as follows: ```swift func testSomeInterestingAPI() throws { // Step 1: Add 'throws' // Step 2: Replace the unwrap. - let x = try interestingAPI.someOptionalProperty.unwrapped() + let x = try XCTUnwrap(interestingAPI.someOptionalProperty) XCTAssertEqual(x, 42, "The correct answer is present") } diff --git a/TestFoundation/FixtureValues.swift b/TestFoundation/FixtureValues.swift index ad4ce7667f..2472c0ca99 100644 --- a/TestFoundation/FixtureValues.swift +++ b/TestFoundation/FixtureValues.swift @@ -41,7 +41,7 @@ enum Fixtures { attrs3Maybe = nil } - let attrs3 = try attrs3Maybe.unwrapped() + let attrs3 = try XCTUnwrap(attrs3Maybe) string.setAttributes(attrs1, range: NSMakeRange(1, string.length - 2)) string.setAttributes(attrs2, range: NSMakeRange(2, 2)) @@ -147,7 +147,7 @@ enum Fixtures { static let textCheckingResultSimpleRegex = TypedFixture("NSTextCheckingResult-SimpleRegex") { let string = "aaa" let regexp = try NSRegularExpression(pattern: "aaa", options: []) - let result = try regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first.unwrapped() + let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first) return result } @@ -156,7 +156,7 @@ enum Fixtures { static let textCheckingResultExtendedRegex = TypedFixture("NSTextCheckingResult-ExtendedRegex") { let string = "aaaaaa" let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a)))))", options: []) - let result = try regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first.unwrapped() + let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first) return result } @@ -164,7 +164,7 @@ enum Fixtures { static let textCheckingResultComplexRegex = TypedFixture("NSTextCheckingResult-ComplexRegex") { let string = "aaaaaaaaa" let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a(a(a(a))))))))", options: []) - let result = try regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first.unwrapped() + let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first) return result } diff --git a/TestFoundation/TestCachedURLResponse.swift b/TestFoundation/TestCachedURLResponse.swift index 2ca82a7dd4..da0b10f4e2 100644 --- a/TestFoundation/TestCachedURLResponse.swift +++ b/TestFoundation/TestCachedURLResponse.swift @@ -9,7 +9,7 @@ class TestCachedURLResponse : XCTestCase { func test_copy() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -26,7 +26,7 @@ class TestCachedURLResponse : XCTestCase { } func test_initDefaultUserInfoAndStoragePolicy() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -39,7 +39,7 @@ class TestCachedURLResponse : XCTestCase { } func test_initDefaultUserInfo() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -53,7 +53,7 @@ class TestCachedURLResponse : XCTestCase { } func test_initWithoutDefaults() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -68,7 +68,7 @@ class TestCachedURLResponse : XCTestCase { } func test_equalWithTheSameInstance() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -80,7 +80,7 @@ class TestCachedURLResponse : XCTestCase { } func test_equalWithUnrelatedObject() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -92,7 +92,7 @@ class TestCachedURLResponse : XCTestCase { } func test_equalCheckingResponse() throws { - let url1 = try URL(string: "http://example.com/").unwrapped() + let url1 = try XCTUnwrap(URL(string: "http://example.com/")) let response1 = URLResponse(url: url1, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -100,11 +100,11 @@ class TestCachedURLResponse : XCTestCase { let storagePolicy = URLCache.StoragePolicy.allowedInMemoryOnly let cachedResponse1 = CachedURLResponse(response: response1, data: data, userInfo: userInfo, storagePolicy: storagePolicy) - let url2 = try URL(string: "http://example.com/second").unwrapped() + let url2 = try XCTUnwrap(URL(string: "http://example.com/second")) let response2 = URLResponse(url: url2, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let cachedResponse2 = CachedURLResponse(response: response2, data: data, userInfo: userInfo, storagePolicy: storagePolicy) - let url3 = try URL(string: "http://example.com/").unwrapped() + let url3 = try XCTUnwrap(URL(string: "http://example.com/")) let response3 = URLResponse(url: url3, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let cachedResponse3 = CachedURLResponse(response: response3, data: data, userInfo: userInfo, storagePolicy: storagePolicy) @@ -115,7 +115,7 @@ class TestCachedURLResponse : XCTestCase { } func test_equalCheckingData() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes1: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data1 = Data(bytes: bytes1, count: bytes1.count) @@ -138,7 +138,7 @@ class TestCachedURLResponse : XCTestCase { } func test_equalCheckingStoragePolicy() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data = Data(bytes: bytes, count: bytes.count) @@ -159,7 +159,7 @@ class TestCachedURLResponse : XCTestCase { } func test_hash() throws { - let url1 = try URL(string: "http://example.com/").unwrapped() + let url1 = try XCTUnwrap(URL(string: "http://example.com/")) let response1 = URLResponse(url: url1, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes1: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data1 = Data(bytes: bytes1, count: bytes1.count) @@ -167,7 +167,7 @@ class TestCachedURLResponse : XCTestCase { let storagePolicy1 = URLCache.StoragePolicy.allowedInMemoryOnly let cachedResponse1 = CachedURLResponse(response: response1, data: data1, userInfo: userInfo1, storagePolicy: storagePolicy1) - let url2 = try URL(string: "http://example.com/").unwrapped() + let url2 = try XCTUnwrap(URL(string: "http://example.com/")) let response2 = URLResponse(url: url2, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes2: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let data2 = Data(bytes: bytes2, count: bytes2.count) @@ -176,7 +176,7 @@ class TestCachedURLResponse : XCTestCase { let cachedResponse2 = CachedURLResponse(response: response2, data: data2, userInfo: userInfo2, storagePolicy: storagePolicy2) // Ideally, this cached response should have a different hash. - let url3 = try URL(string: "http://example.com/second").unwrapped() + let url3 = try XCTUnwrap(URL(string: "http://example.com/second")) let response3 = URLResponse(url: url3, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let bytes3: [UInt8] = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] let data3 = Data(bytes: bytes3, count: bytes3.count) diff --git a/TestFoundation/TestCalendar.swift b/TestFoundation/TestCalendar.swift index 542e7bd3dd..1246265d32 100644 --- a/TestFoundation/TestCalendar.swift +++ b/TestFoundation/TestCalendar.swift @@ -234,21 +234,21 @@ class TestCalendar: XCTestCase { // Check that date(from:) does not change the timeZone of the calendar let df = DateFormatter() df.dateFormat = "yyyy-MM-dd" - df.timeZone = try TimeZone(identifier: "UTC").unwrapped() + df.timeZone = try XCTUnwrap(TimeZone(identifier: "UTC")) var calendar = Calendar(identifier: .gregorian) calendar.locale = Locale(identifier: "en_US_POSIX") - calendar.timeZone = try TimeZone(secondsFromGMT: 0).unwrapped() + calendar.timeZone = try XCTUnwrap(TimeZone(secondsFromGMT: 0)) let calendarCopy = calendar XCTAssertEqual(calendarCopy.timeZone.identifier, "GMT") XCTAssertEqual(calendarCopy.timeZone.description, "GMT (fixed)") - let dc = try calendarCopy.dateComponents(in: TimeZone(identifier: "America/New_York").unwrapped(), from: df.date(from: "2019-01-01").unwrapped()) + let dc = try calendarCopy.dateComponents(in: XCTUnwrap(TimeZone(identifier: "America/New_York")), from: XCTUnwrap(df.date(from: "2019-01-01"))) XCTAssertEqual(calendarCopy.timeZone.identifier, "GMT") XCTAssertEqual(calendarCopy.timeZone.description, "GMT (fixed)") - let dt = try calendarCopy.date(from: dc).unwrapped() + let dt = try XCTUnwrap(calendarCopy.date(from: dc)) XCTAssertEqual(dt.description, "2019-01-01 00:00:00 +0000") XCTAssertEqual(calendarCopy.timeZone.identifier, "GMT") XCTAssertEqual(calendarCopy.timeZone.description, "GMT (fixed)") @@ -498,7 +498,7 @@ class TestNSDateComponents: XCTestCase { let date3 = Date(timeIntervalSince1970: 46570600.45678) var calendar = Calendar.current - calendar.timeZone = try TimeZone(abbreviation: "UTC").unwrapped() + calendar.timeZone = try XCTUnwrap(TimeZone(abbreviation: "UTC")) let diff1 = calendar.dateComponents([.nanosecond], from: date1, to: date2) XCTAssertEqual(diff1.nanosecond, 1230003) diff --git a/TestFoundation/TestDateFormatter.swift b/TestFoundation/TestDateFormatter.swift index bf92133187..7c9ebf3de9 100644 --- a/TestFoundation/TestDateFormatter.swift +++ b/TestFoundation/TestDateFormatter.swift @@ -419,12 +419,12 @@ class TestDateFormatter: XCTestCase { formatter.dateFormat = "yyyy-MM-dd" XCTAssertNil(formatter.date(from: "2018-03-09T10:25:16+01:00")) - let d1 = try formatter.date(from: "2018-03-09").unwrapped() + let d1 = try XCTUnwrap(formatter.date(from: "2018-03-09")) XCTAssertEqual(d1.description, "2018-03-09 00:00:00 +0000") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" XCTAssertNil(formatter.date(from: "2018-03-09")) - let d2 = try formatter.date(from: "2018-03-09T10:25:16+01:00").unwrapped() + let d2 = try XCTUnwrap(formatter.date(from: "2018-03-09T10:25:16+01:00")) XCTAssertEqual(d2.description, "2018-03-09 09:25:16 +0000") } @@ -471,7 +471,7 @@ class TestDateFormatter: XCTestCase { let formatter = DateFormatter() formatter.timeZone = TimeZone(identifier: "CET") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" - let date = try formatter.date(from: "2019-05-05T12:52:10").unwrapped() + let date = try XCTUnwrap(formatter.date(from: "2019-05-05T12:52:10")) let applySettings: [(String, (DateFormatter) -> Void)] = [(".timeZone", { diff --git a/TestFoundation/TestDateIntervalFormatter.swift b/TestFoundation/TestDateIntervalFormatter.swift index 88e07aa124..e28f3a01cc 100644 --- a/TestFoundation/TestDateIntervalFormatter.swift +++ b/TestFoundation/TestDateIntervalFormatter.swift @@ -107,14 +107,14 @@ class TestDateIntervalFormatter: XCTestCase { let result = formatter.string(from: date, to: date) result.assertContainsInOrder(requiresLastToBeAtEnd: true, "February 4", "2001", "5:20:00 PM", "Greenwich Mean Time") - let firstFebruary = try result.range(of: "February").unwrapped() + let firstFebruary = try XCTUnwrap(result.range(of: "February")) XCTAssertNil(result[firstFebruary.upperBound...].range(of: "February")) // February appears only once. } func testStringFromDateIntervalAcrossThreeMillionSeconds() throws { let interval = DateInterval(start: Date(timeIntervalSinceReferenceDate: 0), duration: 3e6) - let result = try formatter.string(from: interval).unwrapped() + let result = try XCTUnwrap(formatter.string(from: interval)) result.assertContainsInOrder("January 1", "2001", "12:00:00 AM", "Greenwich Mean Time", "February 4", "2001", "5:20:00 PM", "Greenwich Mean Time") } @@ -195,7 +195,7 @@ class TestDateIntervalFormatter: XCTestCase { let result = formatter.string(from: older, to: newer) result.assertContainsInOrder(requiresLastToBeAtEnd: true, "January", "1", "2001", "12:00:00 AM", "5:00:00 AM", "GMT") - let firstJanuary = try result.range(of: "January").unwrapped() + let firstJanuary = try XCTUnwrap(result.range(of: "January")) XCTAssertNil(result[firstJanuary.upperBound...].range(of: "January")) // January appears only once. } @@ -217,7 +217,7 @@ class TestDateIntervalFormatter: XCTestCase { let result = formatter.string(from: older, to: newer) result.assertContainsInOrder(requiresLastToBeAtEnd: true, "January", "1", "2001", "12:00:00 AM", "6:00:00 PM", "GMT") - let firstJanuary = try result.range(of: "January").unwrapped() + let firstJanuary = try XCTUnwrap(result.range(of: "January")) XCTAssertNil(result[firstJanuary.upperBound...].range(of: "January")) // January appears only once. } @@ -229,8 +229,8 @@ class TestDateIntervalFormatter: XCTestCase { XCTAssertNotNil(lhs) XCTAssertNotNil(rhs) - let a = try lhs.unwrapped() - let b = try rhs.unwrapped() + let a = try XCTUnwrap(lhs) + let b = try XCTUnwrap(rhs) XCTAssertEqual(a.dateStyle, b.dateStyle, message()) XCTAssertEqual(a.timeStyle, b.timeStyle, message()) diff --git a/TestFoundation/TestDecimal.swift b/TestFoundation/TestDecimal.swift index 87e7ad5d64..c1b0fe7d7f 100644 --- a/TestFoundation/TestDecimal.swift +++ b/TestFoundation/TestDecimal.swift @@ -602,10 +602,10 @@ class TestDecimal: XCTestCase { XCTAssertEqual(NSDecimalNumber(decimal: Decimal(UInt64.min)).description, UInt64.min.description) XCTAssertEqual(NSDecimalNumber(decimal: Decimal(UInt64.max)).description, UInt64.max.description) - XCTAssertEqual(try NSDecimalNumber(decimal: Decimal(string: "12.34").unwrapped()).description, "12.34") - XCTAssertEqual(try NSDecimalNumber(decimal: Decimal(string: "0.0001").unwrapped()).description, "0.0001") - XCTAssertEqual(try NSDecimalNumber(decimal: Decimal(string: "-1.0002").unwrapped()).description, "-1.0002") - XCTAssertEqual(try NSDecimalNumber(decimal: Decimal(string: "0.0").unwrapped()).description, "0") + XCTAssertEqual(NSDecimalNumber(decimal: try XCTUnwrap(Decimal(string: "12.34"))).description, "12.34") + XCTAssertEqual(NSDecimalNumber(decimal: try XCTUnwrap(Decimal(string: "0.0001"))).description, "0.0001") + XCTAssertEqual(NSDecimalNumber(decimal: try XCTUnwrap(Decimal(string: "-1.0002"))).description, "-1.0002") + XCTAssertEqual(NSDecimalNumber(decimal: try XCTUnwrap(Decimal(string: "0.0"))).description, "0") } func test_PositivePowers() { diff --git a/TestFoundation/TestFileManager.swift b/TestFoundation/TestFileManager.swift index 1d03477bd1..67f90c5e64 100644 --- a/TestFoundation/TestFileManager.swift +++ b/TestFoundation/TestFileManager.swift @@ -340,7 +340,7 @@ class TestFileManager : XCTestCase { let creationDate = attrs[.creationDate] as? Date if ProcessInfo.processInfo.isOperatingSystemAtLeast(requiredVersion) { XCTAssertNotNil(creationDate) - XCTAssertGreaterThan(Date().timeIntervalSince1970, try creationDate.unwrapped().timeIntervalSince1970) + XCTAssertGreaterThan(Date().timeIntervalSince1970, try XCTUnwrap(creationDate).timeIntervalSince1970) } else { XCTAssertNil(creationDate) } @@ -1564,7 +1564,7 @@ VIDEOS=StopgapVideos #endif do { - let components = try fm.componentsToDisplay(forPath: a.path).unwrapped() + let components = try XCTUnwrap(fm.componentsToDisplay(forPath: a.path)) XCTAssertGreaterThanOrEqual(components.count, 2) XCTAssertEqual(components.last, "a") } @@ -1572,10 +1572,10 @@ VIDEOS=StopgapVideos do { #if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT let components = try fm._overridingDisplayNameLanguages(with: ["it"]) { - return try fm.componentsToDisplay(forPath: a_Test.path).unwrapped() + return try XCTUnwrap(fm.componentsToDisplay(forPath: a_Test.path)) } #else - let components = try fm.componentsToDisplay(forPath: a_Test.path).unwrapped() + let components = try XCTUnwrap(fm.componentsToDisplay(forPath: a_Test.path)) #endif XCTAssertGreaterThanOrEqual(components.count, 3) @@ -1589,10 +1589,10 @@ VIDEOS=StopgapVideos do { #if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT let components = try fm._overridingDisplayNameLanguages(with: ["en"]) { - return try fm.componentsToDisplay(forPath: a_Test_b.path).unwrapped() + return try XCTUnwrap(fm.componentsToDisplay(forPath: a_Test_b.path)) } #else - let components = try fm.componentsToDisplay(forPath: a_Test_b.path).unwrapped() + let components = try XCTUnwrap(fm.componentsToDisplay(forPath: a_Test_b.path)) #endif XCTAssertGreaterThanOrEqual(components.count, 4) @@ -1696,7 +1696,7 @@ VIDEOS=StopgapVideos XCTAssertNil(cAttributes) } - let newA = try result.unwrapped() + let newA = try XCTUnwrap(result) let finalAttributes = try fm.attributesOfItem(atPath: newA.path) XCTAssertEqual(initialAttributes[.creationDate] as? AnyHashable, finalAttributes[.creationDate] as? AnyHashable) diff --git a/TestFoundation/TestHTTPCookie.swift b/TestFoundation/TestHTTPCookie.swift index c13279e21f..b234779882 100644 --- a/TestFoundation/TestHTTPCookie.swift +++ b/TestFoundation/TestHTTPCookie.swift @@ -186,41 +186,41 @@ class TestHTTPCookie: XCTestCase { func test_cookiesWithResponseHeaderNoNameValue() throws { let header = ["Set-Cookie": ";attr1=value1"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 0) } func test_cookiesWithResponseHeaderNoName() throws { let header = ["Set-Cookie": "=value1;attr2=value2"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 0) } func test_cookiesWithResponseHeaderEmptyName() throws { let header = ["Set-Cookie": " =value1;attr2=value2"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 0) } func test_cookiesWithResponseHeaderNoValue() throws { let header = ["Set-Cookie": "name;attr2=value2"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 0) } func test_cookiesWithResponseHeaderAttributeWithoutNameIsIgnored() throws { let header = ["Set-Cookie": "name=value;Comment=value1; =value2;CommentURL=value3"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies[0].name, "name") XCTAssertEqual(cookies[0].value, "value") XCTAssertEqual(cookies[0].comment, "value1") - XCTAssertEqual(cookies[0].commentURL, try URL(string: "value3").unwrapped()) + XCTAssertEqual(cookies[0].commentURL, try XCTUnwrap(URL(string: "value3"))) } func test_cookiesWithResponseHeaderValuelessAttributes() throws { let header = ["Set-Cookie": "name=value;Secure;Comment;Discard;CommentURL;HttpOnly"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies[0].name, "name") XCTAssertEqual(cookies[0].value, "value") @@ -235,7 +235,7 @@ class TestHTTPCookie: XCTestCase { // The attributes that do not need value will be ignored if they have // a value. let header = ["Set-Cookie": "name=value;Secure=1;Discard=TRUE;HttpOnly=Yes"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies[0].name, "name") XCTAssertEqual(cookies[0].value, "value") @@ -246,14 +246,14 @@ class TestHTTPCookie: XCTestCase { func test_cookiesWithResponseHeaderInvalidPath() throws { let header = ["Set-Cookie": "name=value;Path=This/is/not/a/valid/path"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies[0].path, "/") } func test_cookiesWithResponseHeaderWithEqualsInValue() throws { let header = ["Set-Cookie": "name=v=a=l=u=e;attr1=value1;attr2=value2"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies[0].name, "name") XCTAssertEqual(cookies[0].value, "v=a=l=u=e") @@ -261,18 +261,18 @@ class TestHTTPCookie: XCTestCase { func test_cookiesWithResponseHeaderSecondCookieInvalidToken() throws { let header = ["Set-Cookie": "n=v; Comment=real value, tok@en=second; CommentURL=https://example.com/second"] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try URL(string: "https://example.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: try XCTUnwrap(URL(string: "https://example.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies[0].name, "n") XCTAssertEqual(cookies[0].value, "v") XCTAssertEqual(cookies[0].comment, "real value, tok@en=second") - XCTAssertEqual(cookies[0].commentURL, try URL(string: "https://example.com/second").unwrapped()) + XCTAssertEqual(cookies[0].commentURL, try XCTUnwrap(URL(string: "https://example.com/second"))) } func test_cookiesWithExpiresAsLastAttribute() throws { let cookies = HTTPCookie.cookies(withResponseHeaderFields: [ "Set-Cookie": "AAA=111; path=/; domain=.example.com; expires=Sun, 16-Aug-2025 22:39:54 GMT, BBB=222; path=/; domain=.example.com; HttpOnly; expires=Sat, 15-Feb-2014 22:39:54 GMT" - ], for: try URL(string: "http://www.example.com/").unwrapped()) + ], for: try XCTUnwrap(URL(string: "http://www.example.com/"))) XCTAssertEqual(cookies.count, 2) XCTAssertEqual(cookies[0].name, "AAA") XCTAssertEqual(cookies[0].value, "111") @@ -284,7 +284,7 @@ class TestHTTPCookie: XCTestCase { do { let cookies = HTTPCookie.cookies(withResponseHeaderFields: [ "Set-Cookie": "AAA =1; path=/; domain=.example.com; expires=Sun, 16-Aug-2025 22:39:54 GMT, BBB=2; path=/; domain=.example.com; HttpOnly; expires=Sat, 15-Feb-2014 22:39:54 GMT" - ], for: try URL(string: "http://www.example.com/").unwrapped()) + ], for: try XCTUnwrap(URL(string: "http://www.example.com/"))) XCTAssertEqual(cookies.count, 2) XCTAssertEqual(cookies[0].name, "AAA") XCTAssertEqual(cookies[0].value, "1") @@ -295,7 +295,7 @@ class TestHTTPCookie: XCTestCase { do { let cookies = HTTPCookie.cookies(withResponseHeaderFields: [ "Set-Cookie": " AAA=1; path=/; domain=.example.com; expires=Sun, 16-Aug-2025 22:39:54 GMT, BBB=2; path=/; domain=.example.com; HttpOnly; expires=Sat, 15-Feb-2014 22:39:54 GMT" - ], for: try URL(string: "http://www.example.com/").unwrapped()) + ], for: try XCTUnwrap(URL(string: "http://www.example.com/"))) XCTAssertEqual(cookies.count, 2) XCTAssertEqual(cookies[0].name, "AAA") XCTAssertEqual(cookies[0].value, "1") @@ -309,7 +309,7 @@ class TestHTTPCookie: XCTestCase { let headers = [ "Set-Cookie": "PREF=a=b; expires=\(formattedCookieTime(sinceNow: 100))); path=/; domain=eXample.com" ] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try URL(string: "http://eXample.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try XCTUnwrap(URL(string: "http://eXample.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies.first?.domain, ".example.com") } @@ -318,7 +318,7 @@ class TestHTTPCookie: XCTestCase { let headers = [ "Set-Cookie": "PREF=a=b; expires=\(formattedCookieTime(sinceNow: 100))); path=/; domain=.eXample.com" ] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try URL(string: "http://eXample.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try XCTUnwrap(URL(string: "http://eXample.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies.first?.domain, ".example.com") } @@ -327,7 +327,7 @@ class TestHTTPCookie: XCTestCase { let headers = [ "Set-Cookie": "PREF=a=b; expires=\(formattedCookieTime(sinceNow: 100))); path=/; domain=a.eXample.com" ] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try URL(string: "http://a.eXample.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try XCTUnwrap(URL(string: "http://a.eXample.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies.first?.domain, ".a.example.com") } @@ -336,7 +336,7 @@ class TestHTTPCookie: XCTestCase { let headers = [ "Set-Cookie": "PREF=a=b; expires=\(formattedCookieTime(sinceNow: 100))); path=/" ] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try URL(string: "http://a.eXample.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try XCTUnwrap(URL(string: "http://a.eXample.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies.first?.domain, "a.example.com") } @@ -345,7 +345,7 @@ class TestHTTPCookie: XCTestCase { let headers = [ "Set-Cookie": "PREF=a=b; expires=\(formattedCookieTime(sinceNow: 100))); path=/; domain=1.2.3.4" ] - let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try URL(string: "http://eXample.com").unwrapped()) + let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: try XCTUnwrap(URL(string: "http://eXample.com"))) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies.first?.domain, "1.2.3.4") } diff --git a/TestFoundation/TestNSCalendar.swift b/TestFoundation/TestNSCalendar.swift index 69c1eb3932..1489c4ec73 100644 --- a/TestFoundation/TestNSCalendar.swift +++ b/TestFoundation/TestNSCalendar.swift @@ -51,30 +51,30 @@ class TestNSCalendar: XCTestCase { func test_isEqualWithDifferentWaysToCreateCalendar() throws { let date = Date(timeIntervalSinceReferenceDate: 497973600) // 2016-10-12 07:00:00 +0000; - let gregorianCalendar = try NSCalendar(identifier: .gregorian).unwrapped() - let gregorianCalendar2 = try gregorianCalendar.components(.calendar, from: date).calendar.unwrapped() as NSCalendar + let gregorianCalendar = try XCTUnwrap(NSCalendar(identifier: .gregorian)) + let gregorianCalendar2 = try XCTUnwrap(gregorianCalendar.components(.calendar, from: date).calendar) as NSCalendar XCTAssertEqual(gregorianCalendar, gregorianCalendar2) - let timeZone = try TimeZone(identifier: "Antarctica/Vostok").unwrapped() + let timeZone = try XCTUnwrap(TimeZone(identifier: "Antarctica/Vostok")) gregorianCalendar.timeZone = timeZone - let gregorianCalendar3 = try gregorianCalendar.components(.calendar, from: date).calendar.unwrapped() as NSCalendar + let gregorianCalendar3 = try XCTUnwrap(gregorianCalendar.components(.calendar, from: date).calendar) as NSCalendar XCTAssertEqual(gregorianCalendar, gregorianCalendar3) } func test_isEqual() throws { - let testCal1 = try NSCalendar(identifier: .gregorian).unwrapped() - let testCal2 = try NSCalendar(identifier: .gregorian).unwrapped() + let testCal1 = try XCTUnwrap(NSCalendar(identifier: .gregorian)) + let testCal2 = try XCTUnwrap(NSCalendar(identifier: .gregorian)) XCTAssertEqual(testCal1, testCal2) - testCal2.timeZone = try TimeZone(identifier: "Antarctica/Vostok").unwrapped() + testCal2.timeZone = try XCTUnwrap(TimeZone(identifier: "Antarctica/Vostok")) testCal2.locale = Locale(identifier: "ru_RU") testCal2.firstWeekday += 1 testCal2.minimumDaysInFirstWeek += 1 XCTAssertNotEqual(testCal1, testCal2) - let testCal3 = try NSCalendar(calendarIdentifier: .chinese).unwrapped() + let testCal3 = try XCTUnwrap(NSCalendar(calendarIdentifier: .chinese)) XCTAssertNotEqual(testCal1, testCal3) } @@ -101,15 +101,15 @@ class TestNSCalendar: XCTestCase { } func test_copy() throws { - let cal = try NSCalendar(identifier: .gregorian).unwrapped() - let calCopy = try (cal.copy() as? NSCalendar).unwrapped() + let cal = try XCTUnwrap(NSCalendar(identifier: .gregorian)) + let calCopy = try XCTUnwrap((cal.copy() as? NSCalendar)) XCTAssertEqual(cal, calCopy) XCTAssert(cal !== calCopy) } func test_copyCurrentCalendar() throws { let cal = NSCalendar.current as NSCalendar - let calCopy = try (cal.copy() as? NSCalendar).unwrapped() + let calCopy = try XCTUnwrap((cal.copy() as? NSCalendar)) XCTAssertEqual(cal, calCopy) XCTAssert(cal !== calCopy) } @@ -170,8 +170,8 @@ class TestNSCalendar: XCTestCase { ]; func test_next50MonthsFromDate() throws { - let calendar = try NSCalendar(identifier: .gregorian).unwrapped() - calendar.timeZone = try TimeZone(identifier: "America/Los_Angeles").unwrapped() + let calendar = try XCTUnwrap(NSCalendar(identifier: .gregorian)) + calendar.timeZone = try XCTUnwrap(TimeZone(identifier: "America/Los_Angeles")) let startDate = Date(timeIntervalSinceReferenceDate: 347113850) // 2012-01-01 12:30:50 +0000 @@ -262,16 +262,16 @@ class TestNSCalendar: XCTestCase { func performTest_dateByAdding(with calendar: NSCalendar, components: NSDateComponents, toAdd secondComponents: NSDateComponents, options: NSCalendar.Options, expected: NSDateComponents, addSingleUnit: Bool) throws { - let date = try calendar.date(from: components as DateComponents).unwrapped() + let date = try XCTUnwrap(calendar.date(from: components as DateComponents)) var returnedDate: Date if addSingleUnit { let unit = units(in: secondComponents) let valueToAdd = secondComponents.value(forComponent: unit) - returnedDate = try calendar.date(byAdding: unit, value: valueToAdd, to: date, options: options).unwrapped() + returnedDate = try XCTUnwrap(calendar.date(byAdding: unit, value: valueToAdd, to: date, options: options)) } else { - returnedDate = try calendar.date(byAdding: secondComponents as DateComponents, to: date, options: options).unwrapped() + returnedDate = try XCTUnwrap(calendar.date(byAdding: secondComponents as DateComponents, to: date, options: options)) } let expectedUnitFlags = units(in: expected) @@ -293,8 +293,8 @@ class TestNSCalendar: XCTestCase { } func performTest_componentsFromDateToDate(with calendar: NSCalendar, from fromComponents: NSDateComponents, to toComponents: NSDateComponents, expected: NSDateComponents, options: NSCalendar.Options) throws { - let fromDate = try calendar.date(from: fromComponents as DateComponents).unwrapped() - let toDate = try calendar.date(from: toComponents as DateComponents).unwrapped() + let fromDate = try XCTUnwrap(calendar.date(from: fromComponents as DateComponents)) + let toDate = try XCTUnwrap(calendar.date(from: toComponents as DateComponents)) let expectedUnitFlags = units(in: expected) let returned = calendar.components(expectedUnitFlags, from: fromDate, to: toDate, options: options) as NSDateComponents @@ -311,7 +311,7 @@ class TestNSCalendar: XCTestCase { let originalTZ = fromCalendar.timeZone fromCalendar.timeZone = toCalendar.timeZone - let fromDate = try fromCalendar.date(from: fromComponents as DateComponents).unwrapped() + let fromDate = try XCTUnwrap(fromCalendar.date(from: fromComponents as DateComponents)) fromCalendar.timeZone = originalTZ @@ -323,14 +323,14 @@ class TestNSCalendar: XCTestCase { func test_dateByAddingUnit_withWrapOption() throws { let locale = Locale(identifier: "ar_EG") - let calendar = try NSCalendar(identifier: .gregorian).unwrapped() - let timeZone = try TimeZone(abbreviation: "GMT").unwrapped() + let calendar = try XCTUnwrap(NSCalendar(identifier: .gregorian)) + let timeZone = try XCTUnwrap(TimeZone(abbreviation: "GMT")) calendar.locale = locale calendar.timeZone = timeZone let date = try self.date(fromFixture: "2013-09-20 23:20:28 +0000") - let newDate = try calendar.date(byAdding: .hour, value: 12, to: date, options: .wrapComponents).unwrapped() + let newDate = try XCTUnwrap(calendar.date(byAdding: .hour, value: 12, to: date, options: .wrapComponents)) XCTAssertEqual(newDate, try self.date(fromFixture: "2013-09-20 11:20:28 +0000")) } @@ -342,12 +342,12 @@ class TestNSCalendar: XCTestCase { formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" formatter.locale = Locale(identifier: "en_US") - return try formatter.date(from: string).unwrapped() + return try XCTUnwrap(formatter.date(from: string)) } func enumerateTestDates(using block: (NSCalendar, Date, NSDateComponents) throws -> Void) throws { func yield(to block: (NSCalendar, Date, NSDateComponents) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, dateString: String)) throws { - let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(calendarIdentifier: element.calendarIdentifier)) let currentCalendar = NSCalendar.current as NSCalendar let autoCalendar = NSCalendar.autoupdatingCurrent as NSCalendar @@ -357,7 +357,7 @@ class TestNSCalendar: XCTestCase { } let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale - let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped() + let timeZone = try XCTUnwrap(TimeZone(identifier: element.timeZoneName)) calendar.locale = locale calendar.timeZone = timeZone @@ -447,7 +447,7 @@ class TestNSCalendar: XCTestCase { func test_dateWithYear_month_day_hour_minute_second_nanosecond() throws { try enumerateTestDates() { (calendar, date, components) in - let returnedDate = try calendar.date(era: components.era, year: components.year, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second, nanosecond: components.nanosecond).unwrapped() + let returnedDate = try XCTUnwrap(calendar.date(era: components.era, year: components.year, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second, nanosecond: components.nanosecond)) let interval = date.timeIntervalSince(returnedDate) XCTAssertEqual(fabs(interval), 0, accuracy: 0.0000001) @@ -465,7 +465,7 @@ class TestNSCalendar: XCTestCase { return; } - let returnedDate = try calendar.date(era: components.era, yearForWeekOfYear: components.yearForWeekOfYear, weekOfYear: components.weekOfYear, weekday: components.weekday, hour: components.hour, minute: components.minute, second: components.second, nanosecond: components.nanosecond).unwrapped() + let returnedDate = try XCTUnwrap(calendar.date(era: components.era, yearForWeekOfYear: components.yearForWeekOfYear, weekOfYear: components.weekOfYear, weekday: components.weekday, hour: components.hour, minute: components.minute, second: components.second, nanosecond: components.nanosecond)) let interval = date.timeIntervalSince(returnedDate) XCTAssertEqual(fabs(interval), 0, accuracy: 0.0000001) @@ -474,7 +474,7 @@ class TestNSCalendar: XCTestCase { func enumerateTestDatesWithStartOfDay(using block: (NSCalendar, Date, Date) throws -> Void) throws { func yield(to block: (NSCalendar, Date, Date) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, dateString: String, startOfDayDateString: String)) throws { - let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(calendarIdentifier: element.calendarIdentifier)) let currentCalendar = NSCalendar.current as NSCalendar let autoCalendar = NSCalendar.autoupdatingCurrent as NSCalendar @@ -484,7 +484,7 @@ class TestNSCalendar: XCTestCase { } let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale - let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped() + let timeZone = try XCTUnwrap(TimeZone(identifier: element.timeZoneName)) calendar.locale = locale calendar.timeZone = timeZone @@ -509,7 +509,7 @@ class TestNSCalendar: XCTestCase { func test_componentsInTimeZone_fromDate() throws { try enumerateTestDates() { (calendar, date, components) in - let calendarWithoutTimeZone = try NSCalendar(identifier: calendar.calendarIdentifier).unwrapped() + let calendarWithoutTimeZone = try XCTUnwrap(NSCalendar(identifier: calendar.calendarIdentifier)) calendarWithoutTimeZone.locale = calendar.locale let timeZone = calendar.timeZone @@ -521,7 +521,7 @@ class TestNSCalendar: XCTestCase { func enumerateTestDateComparisons(using block: (NSCalendar, Date, Date, NSCalendar.Unit, ComparisonResult) throws -> Void) throws { func yield(to block: (NSCalendar, Date, Date, NSCalendar.Unit, ComparisonResult) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, firstDateString: String, secondDateString: String, granularity: NSCalendar.Unit, expectedResult: ComparisonResult)) throws { - let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(calendarIdentifier: element.calendarIdentifier)) let currentCalendar = NSCalendar.current as NSCalendar let autoCalendar = NSCalendar.autoupdatingCurrent as NSCalendar @@ -531,7 +531,7 @@ class TestNSCalendar: XCTestCase { } let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale - let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped() + let timeZone = try XCTUnwrap(TimeZone(identifier: element.timeZoneName)) calendar.locale = locale calendar.timeZone = timeZone @@ -631,7 +631,7 @@ class TestNSCalendar: XCTestCase { func test_isDateInToday() throws { var datesTested: [Date] = [] for identifier in availableCalendarIdentifiers { - let calendar = try NSCalendar(identifier: identifier).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(identifier: identifier)) var foundDate = false var dateInToday = Date() @@ -655,14 +655,14 @@ class TestNSCalendar: XCTestCase { func test_isDateInYesterday() throws { var datesTested: [Date] = [] for identifier in availableCalendarIdentifiers { - let calendar = try NSCalendar(identifier: identifier).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(identifier: identifier)) var foundDate = false var dateInToday = Date() for _ in 0..<10 { let delta = NSDateComponents() delta.day = -1 - let dateInYesterday = try calendar.date(byAdding: delta as DateComponents, to: dateInToday).unwrapped() + let dateInYesterday = try XCTUnwrap(calendar.date(byAdding: delta as DateComponents, to: dateInToday)) datesTested.append(dateInYesterday) if calendar.isDateInYesterday(dateInYesterday) { @@ -683,14 +683,14 @@ class TestNSCalendar: XCTestCase { func test_isDateInTomorrow() throws { var datesTested: [Date] = [] for identifier in availableCalendarIdentifiers { - let calendar = try NSCalendar(identifier: identifier).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(identifier: identifier)) var foundDate = false var dateInToday = Date() for _ in 0..<10 { let delta = NSDateComponents() delta.day = 1 - let dateInTomorrow = try calendar.date(byAdding: delta as DateComponents, to: dateInToday).unwrapped() + let dateInTomorrow = try XCTUnwrap(calendar.date(byAdding: delta as DateComponents, to: dateInToday)) datesTested.append(dateInTomorrow) if calendar.isDateInTomorrow(dateInTomorrow) { @@ -710,10 +710,10 @@ class TestNSCalendar: XCTestCase { func enumerateTestWeekends(using block: (NSCalendar, DateInterval) throws -> Void) throws { func yield(to block: (NSCalendar, DateInterval) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, firstDateString: String, secondDateString: String)) throws { - let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(calendarIdentifier: element.calendarIdentifier)) let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale - let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped() + let timeZone = try XCTUnwrap(TimeZone(identifier: element.timeZoneName)) calendar.locale = locale calendar.timeZone = timeZone @@ -769,9 +769,9 @@ class TestNSCalendar: XCTestCase { } func test_enumerateDatesStartingAfterDate_chineseEra_matchYearOne() throws { - let calendar = try NSCalendar(calendarIdentifier: .chinese).unwrapped() + let calendar = try XCTUnwrap(NSCalendar(calendarIdentifier: .chinese)) let locale = Locale(identifier: "zh_CN") - let timeZone = try TimeZone(identifier: "Asia/Chongqing").unwrapped() + let timeZone = try XCTUnwrap(TimeZone(identifier: "Asia/Chongqing")) calendar.locale = locale calendar.timeZone = timeZone @@ -826,8 +826,8 @@ class TestNSCalendar: XCTestCase { // This leads us to propose a potential match twice in certain circumstances (when the highest set date component is hour and we're looking for hour 0). // // We want to ensure this never happens, and that all matches are strictly increasing or decreasing in time. - let calendar = try NSCalendar(identifier: .gregorian).unwrapped() - calendar.timeZone = try TimeZone(identifier: "America/Los_Angeles").unwrapped() + let calendar = try XCTUnwrap(NSCalendar(identifier: .gregorian)) + calendar.timeZone = try XCTUnwrap(TimeZone(identifier: "America/Los_Angeles")) let reference = try date(fromFixture: "2018-02-13 12:00:00 -0800") let expectations: [(minute: Int, second: Int, results: TimeIntervalQuintuple)] = [ diff --git a/TestFoundation/TestNSString.swift b/TestFoundation/TestNSString.swift index 1c3c94c2fc..2e26d28e0c 100755 --- a/TestFoundation/TestNSString.swift +++ b/TestFoundation/TestNSString.swift @@ -1116,15 +1116,15 @@ class TestNSString: LoopbackServerTest { do { let string = NSString(string: "this is an external string that should be representable by data") - let UTF8Data = try string.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false).unwrapped() as NSData + let UTF8Data = try XCTUnwrap(string.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)) as NSData let UTF8Length = UTF8Data.length XCTAssertEqual(UTF8Length, 63, "NSString should successfully produce an external UTF8 representation with a length of 63 but got \(UTF8Length) bytes") - let UTF16Data = try string.data(using: String.Encoding.utf16.rawValue, allowLossyConversion: false).unwrapped() as NSData + let UTF16Data = try XCTUnwrap(string.data(using: String.Encoding.utf16.rawValue, allowLossyConversion: false)) as NSData let UTF16Length = UTF16Data.length XCTAssertEqual(UTF16Length, 128, "NSString should successfully produce an external UTF16 representation with a length of 128 but got \(UTF16Length) bytes") - let ISOLatin1Data = try string.data(using: String.Encoding.isoLatin1.rawValue, allowLossyConversion: false).unwrapped() as NSData + let ISOLatin1Data = try XCTUnwrap(string.data(using: String.Encoding.isoLatin1.rawValue, allowLossyConversion: false)) as NSData let ISOLatin1Length = ISOLatin1Data.length XCTAssertEqual(ISOLatin1Length, 63, "NSString should successfully produce an external ISOLatin1 representation with a length of 63 but got \(ISOLatin1Length) bytes") } @@ -1132,11 +1132,11 @@ class TestNSString: LoopbackServerTest { do { let string = NSString(string: "🐢 encoding all the way down. 🐢🐢🐢") - let UTF8Data = try string.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false).unwrapped() as NSData + let UTF8Data = try XCTUnwrap(string.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)) as NSData let UTF8Length = UTF8Data.length XCTAssertEqual(UTF8Length, 44, "NSString should successfully produce an external UTF8 representation with a length of 44 but got \(UTF8Length) bytes") - let UTF16Data = try string.data(using: String.Encoding.utf16.rawValue, allowLossyConversion: false).unwrapped() as NSData + let UTF16Data = try XCTUnwrap(string.data(using: String.Encoding.utf16.rawValue, allowLossyConversion: false)) as NSData let UTF16Length = UTF16Data.length XCTAssertEqual(UTF16Length, 74, "NSString should successfully produce an external UTF16 representation with a length of 74 but got \(UTF16Length) bytes") diff --git a/TestFoundation/TestObjCRuntime.swift b/TestFoundation/TestObjCRuntime.swift index 2e13a5fbfb..24810e8feb 100644 --- a/TestFoundation/TestObjCRuntime.swift +++ b/TestFoundation/TestObjCRuntime.swift @@ -65,7 +65,7 @@ class TestObjCRuntime: XCTestCase { func testClassesRenamedByAPINotes() throws { for entry in _NSClassesRenamedByObjCAPINotes { XCTAssert(NSClassFromString(NSStringFromClass(entry.class)) === entry.class) - XCTAssert(NSStringFromClass(try NSClassFromString(entry.objCName).unwrapped()) == entry.objCName) + XCTAssert(NSStringFromClass(try XCTUnwrap(NSClassFromString(entry.objCName))) == entry.objCName) } } #endif diff --git a/TestFoundation/TestPipe.swift b/TestFoundation/TestPipe.swift index d5e501d19e..51faf93187 100644 --- a/TestFoundation/TestPipe.swift +++ b/TestFoundation/TestPipe.swift @@ -59,14 +59,14 @@ class TestPipe: XCTestCase { let text = "test-pipe" // First write some data into the pipe - let stringAsData = try text.data(using: .utf8).unwrapped() + let stringAsData = try XCTUnwrap(text.data(using: .utf8)) try aPipe.fileHandleForWriting.write(contentsOf: stringAsData) // SR-10240 - Check empty Data() can be written without crashing aPipe.fileHandleForWriting.write(Data()) // Then read it out again - let data = try aPipe.fileHandleForReading.read(upToCount: stringAsData.count).unwrapped() + let data = try XCTUnwrap(aPipe.fileHandleForReading.read(upToCount: stringAsData.count)) // Confirm that we did read data XCTAssertEqual(data.count, stringAsData.count, "Expected to read \(String(describing:stringAsData.count)) from pipe but read \(data.count) instead") diff --git a/TestFoundation/TestScanner.swift b/TestFoundation/TestScanner.swift index ef49a18412..ee4af05f62 100644 --- a/TestFoundation/TestScanner.swift +++ b/TestFoundation/TestScanner.swift @@ -488,7 +488,7 @@ class TestScanner : XCTestCase { func testLocalizedScanner() throws { let ds = Locale.current.decimalSeparator ?? "." let string = "123\(ds)456" - let scanner = try (Scanner.localizedScanner(with: string) as? Scanner).unwrapped() + let scanner = try XCTUnwrap((Scanner.localizedScanner(with: string) as? Scanner)) XCTAssertNotNil(scanner.locale) var value: Decimal = 0 XCTAssertTrue(scanner.scanDecimal(&value)) diff --git a/TestFoundation/TestSocketPort.swift b/TestFoundation/TestSocketPort.swift index 50631fea41..41d84b8230 100644 --- a/TestFoundation/TestSocketPort.swift +++ b/TestFoundation/TestSocketPort.swift @@ -60,21 +60,21 @@ class TestSocketPort : XCTestCase { } func testInitPicksATCPPort() throws { - let local = try SocketPort(tcpPort: 0).unwrapped() + let local = try XCTUnwrap(SocketPort(tcpPort: 0)) defer { local.invalidate() } - let port = try tcpOrUdpPort(of: local).unwrapped() + let port = try XCTUnwrap(tcpOrUdpPort(of: local)) XCTAssertNotEqual(port, 0) XCTAssert(port >= 1024) } func testSendingOneMessageRemoteToLocal() throws { - let local = try SocketPort(tcpPort: 0).unwrapped() + let local = try XCTUnwrap(SocketPort(tcpPort: 0)) defer { local.invalidate() } - let tcpPort = try UInt16(tcpOrUdpPort(of: local).unwrapped()) + let tcpPort = try UInt16(XCTUnwrap(tcpOrUdpPort(of: local))) - let remote = try SocketPort(remoteWithTCPPort: tcpPort, host: "localhost").unwrapped() + let remote = try XCTUnwrap(SocketPort(remoteWithTCPPort: tcpPort, host: "localhost")) defer { remote.invalidate() } let data = Data("I cannot weave".utf8) diff --git a/TestFoundation/TestTimeZone.swift b/TestFoundation/TestTimeZone.swift index 655e44926a..44d7b58796 100644 --- a/TestFoundation/TestTimeZone.swift +++ b/TestFoundation/TestTimeZone.swift @@ -226,12 +226,12 @@ class TestTimeZone: XCTestCase { func test_nextDaylightSavingTimeTransition() throws { // Timezones without DST - let gmt = try TimeZone(secondsFromGMT: 0).unwrapped() - let msk = try TimeZone(identifier: "Europe/Moscow").unwrapped() + let gmt = try XCTUnwrap(TimeZone(secondsFromGMT: 0)) + let msk = try XCTUnwrap(TimeZone(identifier: "Europe/Moscow")) // Timezones with DST - let bst = try TimeZone(abbreviation: "BST").unwrapped() - let aest = try TimeZone(identifier: "Australia/Sydney").unwrapped() + let bst = try XCTUnwrap(TimeZone(abbreviation: "BST")) + let aest = try XCTUnwrap(TimeZone(identifier: "Australia/Sydney")) XCTAssertNil(gmt.nextDaylightSavingTimeTransition) XCTAssertNil(msk.nextDaylightSavingTimeTransition) @@ -242,14 +242,14 @@ class TestTimeZone: XCTestCase { formatter.timeZone = TimeZone(identifier: "UTC") formatter.dateFormat = "yyyy-MM-dd" - let dt1 = try formatter.date(from: "2018-01-01").unwrapped() + let dt1 = try XCTUnwrap(formatter.date(from: "2018-01-01")) XCTAssertNil(gmt.nextDaylightSavingTimeTransition(after: dt1)) XCTAssertNil(msk.nextDaylightSavingTimeTransition(after: dt1)) XCTAssertEqual(bst.nextDaylightSavingTimeTransition(after: dt1)?.description, "2018-03-25 01:00:00 +0000") XCTAssertEqual(aest.nextDaylightSavingTimeTransition(after: dt1)?.description, "2018-03-31 16:00:00 +0000") formatter.timeZone = aest - let dt2 = try formatter.date(from: "2018-06-06").unwrapped() + let dt2 = try XCTUnwrap(formatter.date(from: "2018-06-06")) XCTAssertNil(gmt.nextDaylightSavingTimeTransition(after: dt2)) XCTAssertNil(msk.nextDaylightSavingTimeTransition(after: dt2)) XCTAssertEqual(bst.nextDaylightSavingTimeTransition(after: dt2)?.description, "2018-10-28 01:00:00 +0000") diff --git a/TestFoundation/TestURL.swift b/TestFoundation/TestURL.swift index 21f9ca8817..5963101dbe 100644 --- a/TestFoundation/TestURL.swift +++ b/TestFoundation/TestURL.swift @@ -739,7 +739,7 @@ class TestURLComponents : XCTestCase { func test_url() throws { - let baseURL = try URL(string: "https://www.example.com").unwrapped() + let baseURL = try XCTUnwrap(URL(string: "https://www.example.com")) /* test NSURLComponents without authority */ guard var compWithAuthority = URLComponents(string: "https://www.swift.org") else { diff --git a/TestFoundation/TestURLCache.swift b/TestFoundation/TestURLCache.swift index 11864f2e2b..f5f2164fa4 100644 --- a/TestFoundation/TestURLCache.swift +++ b/TestFoundation/TestURLCache.swift @@ -232,7 +232,7 @@ class TestURLCache : XCTestCase { let response = cache.cachedResponse(for: requestB) XCTAssertNotNil(response) - XCTAssertEqual((try response.unwrapped()).data, responseB.data) + XCTAssertEqual((try XCTUnwrap(response)).data, responseB.data) } // ----- @@ -260,9 +260,9 @@ class TestURLCache : XCTestCase { } func cachePair(for urlString: String, ofSize size: Int, storagePolicy: URLCache.StoragePolicy = .allowed, startingWith: UInt8 = 0) throws -> (URLRequest, CachedURLResponse) { - let url = try URL(string: urlString).unwrapped() + let url = try XCTUnwrap(URL(string: urlString)) let request = URLRequest(url: url) - let response = try HTTPURLResponse(url: url, statusCode: 200, httpVersion: "1.1", headerFields: [:]).unwrapped() + let response = try XCTUnwrap(HTTPURLResponse(url: url, statusCode: 200, httpVersion: "1.1", headerFields: [:])) var data = Data(count: size) if data.count > 0 { diff --git a/TestFoundation/TestURLCredentialStorage.swift b/TestFoundation/TestURLCredentialStorage.swift index 0ad8370a17..36705458d7 100644 --- a/TestFoundation/TestURLCredentialStorage.swift +++ b/TestFoundation/TestURLCredentialStorage.swift @@ -26,7 +26,7 @@ class TestURLCredentialStorage : XCTestCase { XCTAssertEqual(storage.credentials(for: space)?.count, 1) guard let credentials = storage.credentials(for: space), - let recovered = credentials[try credential.user.unwrapped()] else { + let recovered = credentials[try XCTUnwrap(credential.user)] else { XCTFail("Credential not found in storage") return } @@ -84,7 +84,7 @@ class TestURLCredentialStorage : XCTestCase { XCTAssertEqual(storage.credentials(for: space)?.count, 1) guard let credentials = storage.credentials(for: space), - let recovered = credentials[try credential.user.unwrapped()] else { + let recovered = credentials[try XCTUnwrap(credential.user)] else { XCTFail("Credential not found in storage") return } @@ -428,7 +428,7 @@ class TestURLCredentialStorage : XCTestCase { let space = URLProtectionSpace(host: "example.com", port: 0, protocol: NSURLProtectionSpaceHTTP, realm: nil, authenticationMethod: NSURLAuthenticationMethodDefault) let urlSession = URLSession.shared - let task = urlSession.dataTask(with: try URL(string: "http://example.com/").unwrapped()) + let task = urlSession.dataTask(with: try XCTUnwrap(URL(string: "http://example.com/"))) storage.set(credential, for: space) @@ -451,7 +451,7 @@ class TestURLCredentialStorage : XCTestCase { let space = URLProtectionSpace(host: "example.com", port: 0, protocol: NSURLProtectionSpaceHTTP, realm: nil, authenticationMethod: NSURLAuthenticationMethodDefault) let urlSession = URLSession.shared - let task = urlSession.dataTask(with: try URL(string: "http://example.com/").unwrapped()) + let task = urlSession.dataTask(with: try XCTUnwrap(URL(string: "http://example.com/"))) storage.set(credential, for: space, task: task) @@ -479,7 +479,7 @@ class TestURLCredentialStorage : XCTestCase { let space = URLProtectionSpace(host: "example.com", port: 0, protocol: NSURLProtectionSpaceHTTP, realm: nil, authenticationMethod: NSURLAuthenticationMethodDefault) let urlSession = URLSession.shared - let task = urlSession.dataTask(with: try URL(string: "http://example.com/").unwrapped()) + let task = urlSession.dataTask(with: try XCTUnwrap(URL(string: "http://example.com/"))) storage.set(credential, for: space) @@ -495,7 +495,7 @@ class TestURLCredentialStorage : XCTestCase { let space = URLProtectionSpace(host: "example.com", port: 0, protocol: NSURLProtectionSpaceHTTP, realm: nil, authenticationMethod: NSURLAuthenticationMethodDefault) let urlSession = URLSession.shared - let task = urlSession.dataTask(with: try URL(string: "http://example.com/").unwrapped()) + let task = urlSession.dataTask(with: try XCTUnwrap(URL(string: "http://example.com/"))) storage.setDefaultCredential(credential, for: space) @@ -517,7 +517,7 @@ class TestURLCredentialStorage : XCTestCase { let space = URLProtectionSpace(host: "example.com", port: 0, protocol: NSURLProtectionSpaceHTTP, realm: nil, authenticationMethod: NSURLAuthenticationMethodDefault) let urlSession = URLSession.shared - let task = urlSession.dataTask(with: try URL(string: "http://example.com/").unwrapped()) + let task = urlSession.dataTask(with: try XCTUnwrap(URL(string: "http://example.com/"))) expectChanges(storage.allCredentials.count, by: 1) { storage.setDefaultCredential(credential, for: space, task: task) diff --git a/TestFoundation/TestURLRequest.swift b/TestFoundation/TestURLRequest.swift index d76ef6ce75..fef01c487d 100644 --- a/TestFoundation/TestURLRequest.swift +++ b/TestFoundation/TestURLRequest.swift @@ -284,7 +284,7 @@ class TestURLRequest : XCTestCase { func test_relativeURL() throws { let baseUrl = URL(string: "http://httpbin.org") - let url = try URL(string: "/get", relativeTo: baseUrl).unwrapped() + let url = try XCTUnwrap(URL(string: "/get", relativeTo: baseUrl)) XCTAssertEqual(url.description, "/get -- http://httpbin.org") XCTAssertEqual(url.baseURL?.description, "http://httpbin.org") diff --git a/TestFoundation/TestURLResponse.swift b/TestFoundation/TestURLResponse.swift index de4de0756a..55f5c602c3 100644 --- a/TestFoundation/TestURLResponse.swift +++ b/TestFoundation/TestURLResponse.swift @@ -112,24 +112,24 @@ class TestURLResponse : XCTestCase { } func test_equalWithTheSameInstance() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) XCTAssertTrue(response.isEqual(response)) } func test_equalWithUnrelatedObject() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) XCTAssertFalse(response.isEqual(NSObject())) } func test_equalCheckingURL() throws { - let url1 = try URL(string: "http://example.com/").unwrapped() + let url1 = try XCTUnwrap(URL(string: "http://example.com/")) let response1 = URLResponse(url: url1, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) - let url2 = try URL(string: "http://example.com/second").unwrapped() + let url2 = try XCTUnwrap(URL(string: "http://example.com/second")) let response2 = URLResponse(url: url2, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) let response3 = URLResponse(url: url1, mimeType: nil, expectedContentLength: -1, textEncodingName: nil) @@ -141,7 +141,7 @@ class TestURLResponse : XCTestCase { } func test_equalCheckingMimeType() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response1 = URLResponse(url: url, mimeType: "mimeType1", expectedContentLength: -1, textEncodingName: nil) let response2 = URLResponse(url: url, mimeType: "mimeType2", expectedContentLength: -1, textEncodingName: nil) @@ -155,7 +155,7 @@ class TestURLResponse : XCTestCase { } func test_equalCheckingExpectedContentLength() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response1 = URLResponse(url: url, mimeType: nil, expectedContentLength: 100, textEncodingName: nil) let response2 = URLResponse(url: url, mimeType: nil, expectedContentLength: 200, textEncodingName: nil) @@ -169,7 +169,7 @@ class TestURLResponse : XCTestCase { } func test_equalCheckingTextEncodingName() throws { - let url = try URL(string: "http://example.com/").unwrapped() + let url = try XCTUnwrap(URL(string: "http://example.com/")) let response1 = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: "textEncodingName1") let response2 = URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: "textEncodingName2") @@ -183,13 +183,13 @@ class TestURLResponse : XCTestCase { } func test_hash() throws { - let url1 = try URL(string: "http://example.com/").unwrapped() + let url1 = try XCTUnwrap(URL(string: "http://example.com/")) let response1 = URLResponse(url: url1, mimeType: "mimeType1", expectedContentLength: 100, textEncodingName: "textEncodingName1") - let url2 = try URL(string: "http://example.com/").unwrapped() + let url2 = try XCTUnwrap(URL(string: "http://example.com/")) let response2 = URLResponse(url: url2, mimeType: "mimeType1", expectedContentLength: 100, textEncodingName: "textEncodingName1") - let url3 = try URL(string: "http://example.com/second").unwrapped() + let url3 = try XCTUnwrap(URL(string: "http://example.com/second")) let response3 = URLResponse(url: url3, mimeType: "mimeType3", expectedContentLength: 200, textEncodingName: "textEncodingName3") XCTAssertEqual(response1.hash, response2.hash) diff --git a/TestFoundation/TestURLSession.swift b/TestFoundation/TestURLSession.swift index cea3ebefe9..5dce4ae929 100644 --- a/TestFoundation/TestURLSession.swift +++ b/TestFoundation/TestURLSession.swift @@ -776,7 +776,7 @@ class TestURLSession : LoopbackServerTest { func test_checkErrorTypeAfterInvalidateAndCancel() throws { let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt" - let url = try URL(string: urlString).unwrapped() + let url = try XCTUnwrap(URL(string: urlString)) var urlRequest = URLRequest(url: url) urlRequest.addValue("5", forHTTPHeaderField: "X-Pause") let expect = expectation(description: "Check error code of tasks after invalidateAndCancel") @@ -799,12 +799,12 @@ class TestURLSession : LoopbackServerTest { let expect = expectation(description: "Check task count after invalidateAndCancel") let session = URLSession(configuration: .default) - var request = URLRequest(url: try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt").unwrapped()) + var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"))) request.addValue("5", forHTTPHeaderField: "X-Pause") let task1 = session.dataTask(with: request) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders")) let task2 = session.dataTask(with: request) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost")) let task3 = session.dataTask(with: request) task1.resume() @@ -837,12 +837,12 @@ class TestURLSession : LoopbackServerTest { let expect = expectation(description: "Tasks URLSession.getAllTasks") let session = URLSession(configuration: .default) - var request = URLRequest(url: try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt").unwrapped()) + var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"))) request.addValue("5", forHTTPHeaderField: "X-Pause") let dataTask1 = session.dataTask(with: request) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders")) let dataTask2 = session.dataTask(with: request) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost")) let dataTask3 = session.dataTask(with: request) session.getAllTasks { (tasksBeforeResume) in @@ -885,20 +885,20 @@ class TestURLSession : LoopbackServerTest { let expect = expectation(description: "Test URLSession.getTasksWithCompletion") let session = URLSession(configuration: .default) - var request = URLRequest(url: try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt").unwrapped()) + var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/country.txt"))) request.addValue("5", forHTTPHeaderField: "X-Pause") let dataTask1 = session.dataTask(with: request) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/requestHeaders")) let dataTask2 = session.dataTask(with: request) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/emptyPost")) let dataTask3 = session.dataTask(with: request) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/upload").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/upload")) let uploadTask1 = session.uploadTask(with: request, from: Data()) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/echo").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/echo")) let uploadTask2 = session.uploadTask(with: request, from: Data()) - request.url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/DTDs/PropertyList-1.0.dtd").unwrapped() + request.url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/DTDs/PropertyList-1.0.dtd")) let downloadTask1 = session.downloadTask(with: request) session.getTasksWithCompletionHandler { (dataTasksBeforeCancel, uploadTasksBeforeCancel, downloadTasksBeforeCancel) in @@ -936,7 +936,7 @@ class TestURLSession : LoopbackServerTest { let callback2 = expectation(description: "Callback call #2") callback2.isInverted = true let delegate = SessionDelegate() - let url = try URL(string: urlString).unwrapped() + let url = try XCTUnwrap(URL(string: urlString)) let configuration = URLSessionConfiguration.default configuration.protocolClasses = [FailFastProtocol.self] let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) @@ -959,7 +959,7 @@ class TestURLSession : LoopbackServerTest { } func test_cancelledTasksCannotBeResumed() throws { - let url = try URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal").unwrapped() + let url = try XCTUnwrap(URL(string: "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal")) let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil) let task = session.dataTask(with: url) diff --git a/TestFoundation/Utilities.swift b/TestFoundation/Utilities.swift index a82d74d50d..64b476e946 100644 --- a/TestFoundation/Utilities.swift +++ b/TestFoundation/Utilities.swift @@ -138,13 +138,9 @@ enum TestError: Error { } extension Optional { + @available(*, unavailable, message: "Use XCTUnwrap() instead") func unwrapped(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) throws -> Wrapped { - if let x = self { - return x - } else { - XCTFail("Tried to invoke .unwrapped() on nil in \(file):\(line):\(fn)") - throw TestError.unexpectedNil - } + return try XCTUnwrap(self, file: file, line: line) } } @@ -232,7 +228,7 @@ func expectNoChanges(_ check: @autoclosure () -> T, by differe extension Fixture where ValueType: NSObject & NSCoding { func loadEach(handler: (ValueType, FixtureVariant) throws -> Void) throws { - try self.loadEach(fixtureRepository: try testBundle().url(forResource: "Fixtures", withExtension: nil).unwrapped(), handler: handler) + try self.loadEach(fixtureRepository: try XCTUnwrap(testBundle().url(forResource: "Fixtures", withExtension: nil)), handler: handler) } func assertLoadedValuesMatch(_ matchHandler: (ValueType, ValueType) -> Bool = { $0 == $1 }) throws { diff --git a/Tools/GenerateTestFixtures/GenerateTestFixtures/Utilities.swift b/Tools/GenerateTestFixtures/GenerateTestFixtures/Utilities.swift index b97e77dcac..ae0a08e2e7 100644 --- a/Tools/GenerateTestFixtures/GenerateTestFixtures/Utilities.swift +++ b/Tools/GenerateTestFixtures/GenerateTestFixtures/Utilities.swift @@ -6,20 +6,18 @@ // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// This is the same as the .unwrapped() method used in TestFoundation, but does not invoke XCTFail. +// This is the same as the XCTUnwrap() method used in TestFoundation, but does not require XCTest. enum TestError: Error { case unexpectedNil } -extension Optional { - // Same signature as the original. - func unwrapped(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) throws -> Wrapped { - if let x = self { - return x - } else { - throw TestError.unexpectedNil - } +// Same signature as the original. +func XCTUnwrap(_ expression: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) throws -> T { + if let value = try expression() { + return value + } else { + throw TestError.unexpectedNil } }