From 280312a6e24ff694d3757e62453eb6aff4d69465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Fri, 26 Jan 2024 16:27:23 +0100 Subject: [PATCH] fix: Priority inversion could happend with TolerantDispatchGroup. test: Unit testing TolerantDispatchGroup QoS --- .../Asynchronous/TolerantDispatchGroup.swift | 6 ++-- .../UTTolerantDispatchGroup.swift | 32 ++++++++++++++++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/Sources/InfomaniakCore/Asynchronous/TolerantDispatchGroup.swift b/Sources/InfomaniakCore/Asynchronous/TolerantDispatchGroup.swift index d5b4697..a1c3b31 100644 --- a/Sources/InfomaniakCore/Asynchronous/TolerantDispatchGroup.swift +++ b/Sources/InfomaniakCore/Asynchronous/TolerantDispatchGroup.swift @@ -20,12 +20,12 @@ import CocoaLumberjackSwift import Foundation public final class TolerantDispatchGroup { - private let syncQueue = DispatchQueue(label: "com.infomaniak.TolerantDispatchGroup") + let syncQueue: DispatchQueue private let dispatchGroup = DispatchGroup() private var callBalancer = 0 - public init() { - // Meta: Keep Sonar Cloud happy + public init(qos: DispatchQoS = .default) { + syncQueue = DispatchQueue(label: "com.infomaniak.TolerantDispatchGroup", qos: qos) } public func enter() { diff --git a/Tests/InfomaniakCoreTests/UTTolerantDispatchGroup.swift b/Tests/InfomaniakCoreTests/UTTolerantDispatchGroup.swift index 134913e..72dc02e 100644 --- a/Tests/InfomaniakCoreTests/UTTolerantDispatchGroup.swift +++ b/Tests/InfomaniakCoreTests/UTTolerantDispatchGroup.swift @@ -16,9 +16,15 @@ along with this program. If not, see . */ -import InfomaniakCore +@testable import InfomaniakCore import XCTest +extension DispatchQoS: CaseIterable { + public static var allCases: [DispatchQoS] { + [.background, .utility, .default, .userInitiated, .userInteractive, .unspecified] + } +} + final class UTTolerantDispatchGroup: XCTestCase { func testCanInit() { // WHEN @@ -27,4 +33,28 @@ final class UTTolerantDispatchGroup: XCTestCase { // THEN XCTAssertNotNil(dispatchGroup) } + + func testPriorityDefault() { + // WHEN + let dispatchGroup = TolerantDispatchGroup() + + // THEN + XCTAssertNotNil(dispatchGroup) + XCTAssertEqual(dispatchGroup.syncQueue.qos, DispatchQoS.default, "default constructor should have default priority") + } + + func testPriorityAnyIsSet() { + // GIVEN + guard let expectedQoS = DispatchQoS.allCases.randomElement() else { + XCTFail("unexpected") + return + } + + // WHEN + let dispatchGroup = TolerantDispatchGroup(qos: expectedQoS) + + // THEN + XCTAssertNotNil(dispatchGroup) + XCTAssertEqual(dispatchGroup.syncQueue.qos, expectedQoS, "QoS should match") + } }