Created
October 30, 2023 07:59
-
-
Save MaximBazarov/420409e4349555b679829f8176ebf1ab to your computer and use it in GitHub Desktop.
OSLogStorage contains a log message
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import OSLog | |
import XCTest | |
extension OSLogStore { | |
static func entities( | |
subsystem: String? = nil, | |
category: String? = nil | |
) throws -> [OSLogEntryLog] { | |
let logStore = try OSLogStore(scope: .currentProcessIdentifier) | |
let enumerator = try logStore.__entriesEnumerator(position: nil, predicate: nil) | |
return Array(enumerator) | |
.compactMap { $0 as? OSLogEntryLog } | |
.filter { | |
let matchesSubsystem = subsystem == nil || $0.subsystem == subsystem | |
let matchesCategory = category == nil || $0.category == category | |
return matchesSubsystem && matchesCategory | |
} | |
} | |
/** | |
Asserts that the logs contains a message | |
Usage: | |
```swift | |
func test_SystemUnderTest_logs_Error() async { | |
let sut = SystemUnderTest( | |
doWork: { | |
throw SystemUnderTest.FailureHappened() | |
} | |
) | |
let _ = try? await sut.doWork() | |
OSLogStore.AssertContains( | |
subsystem: SystemUnderTestModule.subsystem, | |
category: SystemUnderTest.logCategory, | |
""" | |
SystemUnderTestModule.SystemUnderTest.FailureHappened() | |
""" | |
) | |
} | |
``` | |
*/ | |
public static func AssertContains( | |
subsystem: String? = nil, | |
category: String? = nil, | |
_ message: String, | |
file: StaticString = #file, | |
line: UInt = #line | |
) { | |
let logs = try! OSLogStore.entities( | |
subsystem: subsystem, | |
category: category | |
) | |
var messages = [String]() | |
for log in logs { | |
if log.composedMessage == message { return } | |
messages.append(log.composedMessage) | |
} | |
XCTFail( | |
""" | |
Error not found in logs : | |
Expected: | |
- \(message) | |
Logs: | |
- \(messages.joined(separator: "\n - ")) | |
""", | |
file: file, | |
line: line | |
) | |
} | |
} |
let logs = try! OSLogStore.entities(
could be improved ofc
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
inspired by @ole's https://github.com/ole/OSLogStoreTest