Skip to content

Commit

Permalink
test: convert some test code from crashable to failable (#4125)
Browse files Browse the repository at this point in the history
  • Loading branch information
armcknight authored Jun 28, 2024
1 parent efd8ddb commit 4597906
Show file tree
Hide file tree
Showing 28 changed files with 357 additions and 329 deletions.
4 changes: 1 addition & 3 deletions Tests/SentryProfilerTests/SentryTraceProfilerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -429,9 +429,7 @@ private extension SentryTraceProfilerTests {
}

func printTimestamps(entries: [[String: Any]]) -> [NSString] {
entries.reduce(into: [NSString](), { partialResult, entry in
partialResult.append(entry["elapsed_since_start_ns"] as! NSString)
})
entries.compactMap({ $0["elapsed_since_start_ns"] as? NSString })
}

func assertMetricEntries(measurements: [String: Any], key: String, expectedEntries: [[String: Any]], transaction: Transaction) throws {
Expand Down
38 changes: 22 additions & 16 deletions Tests/SentryTests/Helper/SentryFileManagerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class SentryFileManagerTests: XCTestCase {
var delegate: TestFileManagerDelegate!
// swiftlint:enable weak_delegate

init() {
init() throws {
currentDateProvider = TestCurrentDateProvider()
dispatchQueueWrapper = TestSentryDispatchQueueWrapper()

Expand All @@ -39,7 +39,7 @@ class SentryFileManagerTests: XCTestCase {

sessionEnvelope = SentryEnvelope(session: session)

let sessionCopy = session.copy() as! SentrySession
let sessionCopy = try XCTUnwrap(session.copy() as? SentrySession)
sessionCopy.incrementErrors()
// We need to serialize in order to set the timestamp and the duration
sessionUpdate = SentrySession(jsonObject: sessionCopy.serialize())!
Expand All @@ -48,7 +48,7 @@ class SentryFileManagerTests: XCTestCase {
let items = [SentryEnvelopeItem(session: sessionUpdate), SentryEnvelopeItem(event: event)]
sessionUpdateEnvelope = SentryEnvelope(id: event.eventId, items: items)

let sessionUpdateCopy = sessionUpdate.copy() as! SentrySession
let sessionUpdateCopy = try XCTUnwrap(sessionUpdate.copy() as? SentrySession)
// We need to serialize in order to set the timestamp and the duration
expectedSessionUpdate = SentrySession(jsonObject: sessionUpdateCopy.serialize())!
// We can only set the init flag after serialize, because the duration is not set if the init flag is set
Expand All @@ -75,9 +75,9 @@ class SentryFileManagerTests: XCTestCase {
private var fixture: Fixture!
private var sut: SentryFileManager!

override func setUp() {
super.setUp()
fixture = Fixture()
override func setUpWithError() throws {
try super.setUpWithError()
fixture = try Fixture()
SentryDependencyContainer.sharedInstance().dateProvider = fixture.currentDateProvider

sut = fixture.getSut()
Expand Down Expand Up @@ -665,7 +665,7 @@ class SentryFileManagerTests: XCTestCase {

#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)

func testReadPreviousBreadcrumbs() {
func testReadPreviousBreadcrumbs() throws {
let observer = SentryWatchdogTerminationScopeObserver(maxBreadcrumbs: 2, fileManager: sut)

for count in 0..<3 {
Expand All @@ -677,14 +677,17 @@ class SentryFileManagerTests: XCTestCase {
}

sut.moveBreadcrumbsToPreviousBreadcrumbs()
let result = sut.readPreviousBreadcrumbs()
var result = sut.readPreviousBreadcrumbs()

XCTAssertEqual(result.count, 3)
XCTAssertEqual((result[0] as! NSDictionary)["message"] as! String, "0")
XCTAssertEqual((result[1] as! NSDictionary)["message"] as! String, "1")
XCTAssertEqual((result[2] as! NSDictionary)["message"] as! String, "2")
XCTAssertEqual(try XCTUnwrap(result.first as? NSDictionary)["message"] as? String, "0")
result = [Any](result.dropFirst())
XCTAssertEqual(try XCTUnwrap(result.first as? NSDictionary)["message"] as? String, "1")
result = [Any](result.dropFirst())
XCTAssertEqual(try XCTUnwrap(result.first as? NSDictionary)["message"] as? String, "2")
}

func testReadPreviousBreadcrumbsCorrectOrderWhenFileTwoHasMoreCrumbs() {
func testReadPreviousBreadcrumbsCorrectOrderWhenFileTwoHasMoreCrumbs() throws {
let observer = SentryWatchdogTerminationScopeObserver(maxBreadcrumbs: 2, fileManager: sut)

for count in 0..<5 {
Expand All @@ -696,11 +699,14 @@ class SentryFileManagerTests: XCTestCase {
}

sut.moveBreadcrumbsToPreviousBreadcrumbs()
let result = sut.readPreviousBreadcrumbs()
var result = sut.readPreviousBreadcrumbs()

XCTAssertEqual(result.count, 3)
XCTAssertEqual((result[0] as! NSDictionary)["message"] as! String, "2")
XCTAssertEqual((result[1] as! NSDictionary)["message"] as! String, "3")
XCTAssertEqual((result[2] as! NSDictionary)["message"] as! String, "4")
XCTAssertEqual(try XCTUnwrap(result.first as? NSDictionary)["message"] as? String, "2")
result = [Any](result.dropFirst())
XCTAssertEqual(try XCTUnwrap(result.first as? NSDictionary)["message"] as? String, "3")
result = [Any](result.dropFirst())
XCTAssertEqual(try XCTUnwrap(result.first as? NSDictionary)["message"] as? String, "4")
}

#endif // os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,14 +171,14 @@ class SentryCoreDataTrackerTests: XCTestCase {
try assertSave("INSERTED 2 items, UPDATED 2 items, DELETED 2 items")
}

func test_Operation_InData() {
func test_Operation_InData() throws {
fixture.context.inserted = [fixture.testEntity(), fixture.testEntity(), fixture.secondTestEntity()]
fixture.context.updated = [fixture.testEntity(), fixture.secondTestEntity(), fixture.secondTestEntity()]
fixture.context.deleted = [fixture.testEntity(), fixture.testEntity(), fixture.secondTestEntity(), fixture.secondTestEntity(), fixture.secondTestEntity()]

let sut = fixture.getSut()

let transaction = startTransaction()
let transaction = try startTransaction()

XCTAssertNoThrow(try sut.managedObjectContext(fixture.context) { _ in
return true
Expand Down Expand Up @@ -223,10 +223,10 @@ class SentryCoreDataTrackerTests: XCTestCase {
XCTAssertEqual(updated["SecondTestEntity"] as? Int, 2)
}

func test_Request_with_Error() {
func test_Request_with_Error() throws {
let fetch = NSFetchRequest<TestEntity>(entityName: "TestEntity")

let transaction = startTransaction()
let transaction = try startTransaction()
let sut = fixture.getSut()

let context = fixture.context
Expand All @@ -239,10 +239,10 @@ class SentryCoreDataTrackerTests: XCTestCase {
XCTAssertEqual(transaction.children[0].status, .internalError)
}

func test_Request_with_Error_is_nil() {
func test_Request_with_Error_is_nil() throws {
let fetch = NSFetchRequest<TestEntity>(entityName: "TestEntity")

let transaction = startTransaction()
let transaction = try startTransaction()
let sut = fixture.getSut()

let context = fixture.context
Expand All @@ -255,8 +255,8 @@ class SentryCoreDataTrackerTests: XCTestCase {
XCTAssertEqual(transaction.children[0].status, .internalError)
}

func test_save_with_Error() {
let transaction = startTransaction()
func test_save_with_Error() throws {
let transaction = try startTransaction()
let sut = fixture.getSut()
fixture.context.inserted = [fixture.testEntity()]
XCTAssertThrowsError(try sut.managedObjectContext(fixture.context) { _ in
Expand All @@ -267,8 +267,8 @@ class SentryCoreDataTrackerTests: XCTestCase {
XCTAssertEqual(transaction.children[0].status, .internalError)
}

func test_save_with_error_is_nil() {
let transaction = startTransaction()
func test_save_with_error_is_nil() throws {
let transaction = try startTransaction()
let sut = fixture.getSut()
fixture.context.inserted = [fixture.testEntity()]

Expand All @@ -280,10 +280,10 @@ class SentryCoreDataTrackerTests: XCTestCase {
XCTAssertEqual(transaction.children[0].status, .internalError)
}

func test_Save_NoChanges() {
func test_Save_NoChanges() throws {
let sut = fixture.getSut()

let transaction = startTransaction()
let transaction = try startTransaction()

XCTAssertNoThrow(try sut.managedObjectContext(fixture.context) { _ in
return true
Expand All @@ -299,7 +299,7 @@ private extension SentryCoreDataTrackerTests {
func assertSave(_ expectedDescription: String, mainThread: Bool = true) throws {
let sut = fixture.getSut()

let transaction = startTransaction()
let transaction = try startTransaction()

XCTAssertNoThrow(try sut.managedObjectContext(fixture.context) { _ in
return true
Expand All @@ -311,7 +311,7 @@ private extension SentryCoreDataTrackerTests {
}

func assertRequest(_ fetch: NSFetchRequest<TestEntity>, expectedDescription: String, mainThread: Bool = true) throws {
let transaction = startTransaction()
let transaction = try startTransaction()
let sut = fixture.getSut()

let context = fixture.context
Expand Down Expand Up @@ -350,8 +350,8 @@ private extension SentryCoreDataTrackerTests {
}
}

private func startTransaction() -> SentryTracer {
return SentrySDK.startTransaction(name: "TestTransaction", operation: "TestTransaction", bindToScope: true) as! SentryTracer
private func startTransaction() throws -> SentryTracer {
return try XCTUnwrap(SentrySDK.startTransaction(name: "TestTransaction", operation: "TestTransaction", bindToScope: true) as? SentryTracer)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,19 @@ class SentryCoreDataTrackingIntegrationTests: XCTestCase {
assert_DontInstall { $0.enableCoreDataTracing = false }
}

func test_Fetch() {
func test_Fetch() throws {
SentrySDK.start(options: fixture.options)
let stack = fixture.coreDataStack
let fetch = NSFetchRequest<TestEntity>(entityName: "TestEntity")
let transaction = startTransaction()
let transaction = try startTransaction()
var _ = try? stack.managedObjectContext.fetch(fetch)
XCTAssertEqual(transaction.children.count, 1)
}

func test_Save() {
func test_Save() throws {
SentrySDK.start(options: fixture.options)
let stack = fixture.coreDataStack
let transaction = startTransaction()
let transaction = try startTransaction()
let newEntity: TestEntity = stack.getEntity()
newEntity.field1 = "Some Update"
try? stack.managedObjectContext.save()
Expand All @@ -77,30 +77,30 @@ class SentryCoreDataTrackingIntegrationTests: XCTestCase {
XCTAssertEqual(transaction.children[0].operation, "db.sql.transaction")
}

func test_Save_noChanges() {
func test_Save_noChanges() throws {
SentrySDK.start(options: fixture.options)
let stack = fixture.coreDataStack
let transaction = startTransaction()
let transaction = try startTransaction()

try? stack.managedObjectContext.save()

XCTAssertEqual(transaction.children.count, 0)
}

func test_Fetch_StoppedSwizzling() {
func test_Fetch_StoppedSwizzling() throws {
SentrySDK.start(options: fixture.options)
let stack = fixture.coreDataStack
let fetch = NSFetchRequest<TestEntity>(entityName: "TestEntity")
let transaction = startTransaction()
let transaction = try startTransaction()
SentryCoreDataSwizzling.sharedInstance.stop()
var _ = try? stack.managedObjectContext.fetch(fetch)
XCTAssertEqual(transaction.children.count, 0)
}

func test_Save_StoppedSwizzling() {
func test_Save_StoppedSwizzling() throws {
SentrySDK.start(options: fixture.options)
let stack = fixture.coreDataStack
let transaction = startTransaction()
let transaction = try startTransaction()
let newEntity: TestEntity = stack.getEntity()
newEntity.field1 = "Some Update"
SentryCoreDataSwizzling.sharedInstance.stop()
Expand All @@ -116,7 +116,7 @@ class SentryCoreDataTrackingIntegrationTests: XCTestCase {
XCTAssertNil(SentryCoreDataSwizzling.sharedInstance.coreDataTracker)
}

private func startTransaction() -> SentryTracer {
return SentrySDK.startTransaction(name: "TestTransaction", operation: "TestTransaction", bindToScope: true) as! SentryTracer
private func startTransaction() throws -> SentryTracer {
return try XCTUnwrap(SentrySDK.startTransaction(name: "TestTransaction", operation: "TestTransaction", bindToScope: true) as? SentryTracer)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,26 @@ class SentryNetworkTrackerIntegrationTests: XCTestCase {
XCTAssertNil(configuration.httpAdditionalHeaders)
}

func testNetworkTrackerDisabled_WhenNetworkTrackingDisabled() {
assertNetworkTrackerDisabled { options in
func testNetworkTrackerDisabled_WhenNetworkTrackingDisabled() throws {
try assertNetworkTrackerDisabled { options in
options.enableNetworkTracking = false
}
}

func testNetworkTrackerDisabled_WhenAutoPerformanceTrackingDisabled() {
assertNetworkTrackerDisabled { options in
func testNetworkTrackerDisabled_WhenAutoPerformanceTrackingDisabled() throws {
try assertNetworkTrackerDisabled { options in
options.enableAutoPerformanceTracing = false
}
}

func testNetworkTrackerDisabled_WhenTracingDisabled() {
assertNetworkTrackerDisabled { options in
func testNetworkTrackerDisabled_WhenTracingDisabled() throws {
try assertNetworkTrackerDisabled { options in
options.tracesSampleRate = 0.0
}
}

func testNetworkTrackerDisabled_WhenSwizzlingDisabled() {
assertNetworkTrackerDisabled { options in
func testNetworkTrackerDisabled_WhenSwizzlingDisabled() throws {
try assertNetworkTrackerDisabled { options in
options.enableSwizzling = false
}
}
Expand Down Expand Up @@ -106,12 +106,12 @@ class SentryNetworkTrackerIntegrationTests: XCTestCase {
/**
* Reproduces https://github.com/getsentry/sentry-cocoa/issues/1288
*/
func testCustomURLProtocol_BlocksAllRequests() {
func testCustomURLProtocol_BlocksAllRequests() throws {
startSDK()

let expect = expectation(description: "Callback Expectation")

let customConfiguration = URLSessionConfiguration.default.copy() as! URLSessionConfiguration
let customConfiguration = try XCTUnwrap(URLSessionConfiguration.default.copy() as? URLSessionConfiguration)
customConfiguration.protocolClasses?.insert(BlockAllRequestsProtocol.self, at: 0)
let session = URLSession(configuration: customConfiguration)

Expand Down Expand Up @@ -154,9 +154,9 @@ class SentryNetworkTrackerIntegrationTests: XCTestCase {
XCTAssertEqual(1, breadcrumbs?.count)
}

func testGetRequest_SpanCreatedAndBaggageHeaderAdded() {
func testGetRequest_SpanCreatedAndBaggageHeaderAdded() throws {
startSDK()
let transaction = SentrySDK.startTransaction(name: "Test Transaction", operation: "TEST", bindToScope: true) as! SentryTracer
let transaction = try XCTUnwrap(SentrySDK.startTransaction(name: "Test Transaction", operation: "TEST", bindToScope: true) as? SentryTracer)
let expect = expectation(description: "Request completed")
let session = URLSession(configuration: URLSessionConfiguration.default)

Expand All @@ -176,17 +176,17 @@ class SentryNetworkTrackerIntegrationTests: XCTestCase {
let children = Dynamic(transaction).children as [Span]?

XCTAssertEqual(children?.count, 1) //Span was created in task resume swizzle.
let networkSpan = children![0]
let networkSpan = try XCTUnwrap(children?.first)
XCTAssertTrue(networkSpan.isFinished) //Span was finished in task setState swizzle.
XCTAssertEqual(SENTRY_NETWORK_REQUEST_OPERATION, networkSpan.operation)
XCTAssertEqual("GET \(SentryNetworkTrackerIntegrationTests.testBaggageURL)", networkSpan.spanDescription)

XCTAssertEqual("200", networkSpan.data["http.response.status_code"] as? String)
}

func testGetRequest_CompareSentryTraceHeader() {
func testGetRequest_CompareSentryTraceHeader() throws {
startSDK()
let transaction = SentrySDK.startTransaction(name: "Test Transaction", operation: "TEST", bindToScope: true) as! SentryTracer
let transaction = try XCTUnwrap(SentrySDK.startTransaction(name: "Test Transaction", operation: "TEST", bindToScope: true) as? SentryTracer)
let expect = expectation(description: "Request completed")
let session = URLSession(configuration: URLSessionConfiguration.default)
var response: String?
Expand Down Expand Up @@ -274,13 +274,13 @@ class SentryNetworkTrackerIntegrationTests: XCTestCase {
XCTAssertEqual(sentryResponse?["status_code"] as? NSNumber, 400)
}

private func assertNetworkTrackerDisabled(configureOptions: (Options) -> Void) {
private func assertNetworkTrackerDisabled(configureOptions: (Options) -> Void) throws {
configureOptions(fixture.options)

startSDK()

let configuration = URLSessionConfiguration.default
_ = startTransactionBoundToScope()
_ = try startTransactionBoundToScope()
XCTAssertNil(configuration.httpAdditionalHeaders)
}

Expand All @@ -290,8 +290,8 @@ class SentryNetworkTrackerIntegrationTests: XCTestCase {
SentrySDK.start(options: self.fixture.options)
}

private func startTransactionBoundToScope() -> SentryTracer {
return SentrySDK.startTransaction(name: "Test", operation: "test", bindToScope: true) as! SentryTracer
private func startTransactionBoundToScope() throws -> SentryTracer {
return try XCTUnwrap(SentrySDK.startTransaction(name: "Test", operation: "test", bindToScope: true) as? SentryTracer)
}

private func assertRemovedIntegration(_ options: Options) {
Expand Down
Loading

0 comments on commit 4597906

Please sign in to comment.