Skip to content

Instantly share code, notes, and snippets.

@KaiOelfke
Created March 17, 2022 09:53
Show Gist options
  • Save KaiOelfke/4c6f6ffe0a55ab2ce287c2120f12c393 to your computer and use it in GitHub Desktop.
Save KaiOelfke/4c6f6ffe0a55ab2ce287c2120f12c393 to your computer and use it in GitHub Desktop.
import Foundation
import XCTestDynamicOverlay
@propertyWrapper public struct PreMainActor<T> {
private var _wrappedValue: T
public var wrappedValue: T {
get {
#if DEBUG
if !Thread.isMainThread {
XCTFail("Property must be read on the main thread only")
if !ProcessInfo.runningUnitTests {
assertionFailure("Property must be read on the main thread only")
}
}
#endif
return _wrappedValue
}
set {
#if DEBUG
if !Thread.isMainThread {
XCTFail("Property must be set on the main thread only")
if !ProcessInfo.runningUnitTests {
assertionFailure("Property must be set on the main thread only")
}
}
#endif
_wrappedValue = newValue
}
}
public init(wrappedValue: T) {
#if DEBUG
if !Thread.isMainThread {
XCTFail("Property must be initialized on the main thread only")
if !ProcessInfo.runningUnitTests {
assertionFailure("Property must be initialized on the main thread only")
}
}
#endif
_wrappedValue = wrappedValue
}
}
import XCTest
final class PreMainActorTests: XCTestCase {
private let queue = DispatchQueue(label: "PreMainActorTests", target: .global(qos: .background))
func testQueueIsOnBackgroundThread() {
let expectation = XCTestExpectation()
queue.async {
XCTAssertFalse(Thread.isMainThread)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
func testGetterSetterAndInitOnMainThread() {
XCTAssertTrue(Thread.isMainThread)
@PreMainActor var number = 42
XCTAssertEqual(number, 42)
number = 1234
XCTAssertEqual(number, 1234)
}
func testInitOnBackgroundThread() {
XCTExpectFailure()
let expectation = XCTestExpectation()
queue.async {
@PreMainActor var number = 42
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
func testGetOnBackgroundThread() {
XCTExpectFailure()
let expectation = XCTestExpectation()
@PreMainActor var number = 42
queue.async {
_ = number
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
func testSetOnBackgroundThread() {
XCTExpectFailure()
let expectation = XCTestExpectation()
@PreMainActor var number = 42
queue.async {
number = 1234
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment