# Using Dispatch Internals for Testing

**URL:** <https://forums.swift.org/t/using-dispatch-internals-for-testing/34769>\
**Category:** Core Libraries\
**Tags:** dispatch, testing, libdispatch\
**Created:** [March 25, 2020, 2:50am UTC](https://forums.swift.org/t/using-dispatch-internals-for-testing/34769 "2020-03-25T02:50:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![SlaunchaMan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slaunchaman/32/520_2.png) [@SlaunchaMan](https://forums.swift.org/u/SlaunchaMan)\
**Post date:** [March 25, 2020, 2:50am UTC](https://forums.swift.org/t/using-dispatch-internals-for-testing/34769/1 "2020-03-25T02:50:58Z")

</div>

After the release of my [ErrorAssertions](https://github.com/SlaunchaMan/ErrorAssertions) package that allows you to write tests around places your code calls `fatalError()` and friends, I turned my attention to another assertion method in Swift: Dispatch’s [`dispatchPrecondition(condition:)`](https://developer.apple.com/documentation/dispatch/1780605-dispatchprecondition) method. If I were successful, I’d be able to write this in the context of an XCTest test method:

```swift
expectDispatchPreconditionFailure {
    let queue = DispatchQueue(label: "com.slaunchaman.testqueue")
    queue.async {
        dispatchPrecondition(.notOnQueue(queue))
    }
}

```

This is a contrived example, but the long and short of it is that this allows you to test your error cases that would otherwise crash the test suite. Unfortunately, digging into the implementation of `dispatchPrecondition(condition:)`, we find ourselves in [`dispatch_assert_queue()`](https://github.com/apple/swift-corelibs-libdispatch/blob/master/src/queue.c#L61-L78), and a failure there calls more internal methods to crash.

A good implementation of my code would be able to evaluate a `DispatchPredicate` without crashing. A tweak of `dispatch_assert_queue()` might look like this:

```nohighlight
bool
dispatch_assert_queue_evaluate(dispatch_queue_t dq)
{
	unsigned long metatype = dx_metatype(dq);
	if (unlikely(metatype != _DISPATCH_LANE_TYPE &&
			metatype != _DISPATCH_WORKLOOP_TYPE)) {
		DISPATCH_CLIENT_CRASH(metatype, "invalid queue passed to "
				"dispatch_assert_queue()");
	}
	uint64_t dq_state = os_atomic_load2o(dq, dq_state, relaxed);
	if (likely(_dq_state_drain_locked_by_self(dq_state))) {
		return true;
	}
	if (likely(_dispatch_thread_frame_find_queue(dq))) {
		return true;
	}
	return false;
}

```

In fact, you could rewrite `dispatch_assert_queue()` to take advantage of this method, but I don’t know if the additional overhead would be a problem for such low-level code.

So, if you’ve gotten this far, thanks! **Here’s the real question.** Is it possible to access the two conditions in the code above—`_dq_state_drain_locked_by_self(dq_state)` and `_dispatch_thread_frame_find_queue(dq)`—from Swift? I have a naïve implementation that evaluates a `DispatchPredicate` in [my WIP branch](https://github.com/SlaunchaMan/ErrorAssertions/blob/dispatch-assertions/Sources/DispatchAssertionExpectations/DispatchPreconditionExpectations.swift#L18-L34):

```swift
func currentQueueName() -> String? {
    let name = __dispatch_queue_get_label(nil)
    return String(cString: name, encoding: .utf8)
}

@available(macOS 10.12, iOS 10, watchOS 3, tvOS 10, *)
extension DispatchPredicate {
    
    func evaluate() -> Bool {
        switch self {
        case .onQueue(let queue):
            return currentQueueName() == queue.label
        case .notOnQueue(let queue):
            return currentQueueName() != queue.label
        default:
            fatalError("Haven't implemented this yet.")
        }
    }
    
}

```

This is obviously problematic in several ways.

Second question: If I were to submit a patch to swift-corelibs-libdispatch that exposed the evaluation of these conditions, would that be a desirable and acceptable solution to this problem?

---

<div class="post-metadata">

**Author:** ![sveinhal](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/sveinhal/32/3992_2.png) [@sveinhal](https://forums.swift.org/u/sveinhal)\
**Post date:** [March 25, 2020, 9:07am UTC](https://forums.swift.org/t/using-dispatch-internals-for-testing/34769/2 "2020-03-25T09:07:33Z")

</div>

> [@SlaunchaMan](#):
>
> ```swift
> func currentQueueName() -> String? { 
> let name = __dispatch_queue_get_label(nil) 
> return String(cString: name, encoding: .utf8) 
> }
> 
> ```

I've resorted to the same trick in my tests: [Dispatch precondition false positive?](https://forums.swift.org/t/dispatch-precondition-false-positive/28498)
