From 326b7eb3391a3c0dede41b0e56765bc07dfc5e0e Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 14 Apr 2023 13:32:33 +0200 Subject: [PATCH] test: Remove subclass of NSTimer (#2904) We subclassed NSTimer, which is not allowed see: https://developer.apple.com/documentation/foundation/nstimer#1770465. This sometimes leads to crashes in TestSentryNSTimerWrapper with EXC_BAD_ACCESS. The subclass is now removed. --- .../TestSentryNSTimerWrapper.swift | 31 ++++++++----------- .../Transaction/SentryTracerTests.swift | 2 +- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/SentryTestUtils/TestSentryNSTimerWrapper.swift b/SentryTestUtils/TestSentryNSTimerWrapper.swift index 5def3be65f8..2969151dd85 100644 --- a/SentryTestUtils/TestSentryNSTimerWrapper.swift +++ b/SentryTestUtils/TestSentryNSTimerWrapper.swift @@ -1,31 +1,26 @@ import Foundation import Sentry -public class TestTimer: Timer { - public var invalidateCount = 0 - - public override func invalidate() { - // no-op as this timer doesn't actually schedule anything on a runloop - invalidateCount += 1 - } -} - +// We must not subclass NSTimer, see https://developer.apple.com/documentation/foundation/nstimer#1770465. +// Therefore we return a NSTimer instance here with TimeInterval.infinity. public class TestSentryNSTimerWrapper: SentryNSTimerWrapper { - public struct Overrides { - public var timer: TestTimer! - var block: ((Timer) -> Void)? - } - public var overrides = Overrides() + private var _timer: Timer? + + public var timer: Timer { + get { + _timer ?? Timer() + } + } public override func scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) -> Timer { - let timer = TestTimer() - overrides.timer = timer - overrides.block = block + let timer = Timer.scheduledTimer(withTimeInterval: TimeInterval.infinity, repeats: repeats, block: block) + _timer = timer + return timer } public func fire() { - overrides.block?(overrides.timer) + _timer?.fire() } } diff --git a/Tests/SentryTests/Transaction/SentryTracerTests.swift b/Tests/SentryTests/Transaction/SentryTracerTests.swift index f27f3da33b3..acf4365b92d 100644 --- a/Tests/SentryTests/Transaction/SentryTracerTests.swift +++ b/Tests/SentryTests/Transaction/SentryTracerTests.swift @@ -209,7 +209,7 @@ class SentryTracerTests: XCTestCase { let sut = fixture.getSut() sut.finish() - XCTAssertEqual(fixture.timerWrapper.overrides.timer.invalidateCount, 1) + XCTAssertFalse(fixture.timerWrapper.timer.isValid) } func testFinish_CheckDefaultStatus() {