Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

test: cover the Ling rate gate, Ming interpretation parsing and the BlackHole hash check with stubbed network

wqugurucc792c05c5d0
diff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swift
index 2935bc3..b10235d 100644
--- a/Sources/LiveSubs/Ling.swift
+++ b/Sources/LiveSubs/Ling.swift
@@ -13,8 +13,12 @@ import Security
enum AIKey {
private static var cached: String??
+ /// Tests only: keep the key in this folder instead, and leave the Keychain alone, so a test
+ /// run never touches the user's real key.
+ static var folderOverride: URL? { didSet { cached = nil } }
+
private static var folder: URL {
- FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ folderOverride ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent(DevBuild.supportFolder)
}
private static var file: URL { folder.appendingPathComponent("ling-api-key") }
@@ -23,7 +27,7 @@ enum AIKey {
if let cached { return cached }
var value = (try? String(contentsOf: file, encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines)
if value?.isEmpty ?? true { value = nil }
- if value == nil, let old = LegacyKeychain.take() {
+ if value == nil, folderOverride == nil, let old = LegacyKeychain.take() {
// One last Keychain prompt, then the key lives in the file.
value = old
write(old)
@@ -41,7 +45,7 @@ enum AIKey {
static func remove() {
try? FileManager.default.removeItem(at: file)
- LegacyKeychain.delete()
+ if folderOverride == nil { LegacyKeychain.delete() }
cached = .some(nil)
}
@@ -151,6 +155,9 @@ final class LingClient: ObservableObject {
/// Debug control only: act as if there were no key, without touching the key file.
var hideKey = false
+ /// Tests swap in a session with a stub protocol.
+ var session: URLSession = .shared
+
var hasKey: Bool { key != nil }
var key: String? { hideKey ? nil : AIKey.read() }
/// The key is known to work (or at least not known to be bad).
@@ -315,7 +322,7 @@ final class LingClient: ObservableObject {
if let language { body["language_id"] = language }
req.httpBody = try? JSONSerialization.data(withJSONObject: body)
do {
- let (bytes, response) = try await URLSession.shared.bytes(for: req)
+ let (bytes, response) = try await self.session.bytes(for: req)
switch (response as? HTTPURLResponse)?.statusCode ?? 0 {
case 200: break
case 401, 403:
@@ -352,7 +359,7 @@ final class LingClient: ObservableObject {
let data: Data
let response: URLResponse
do {
- (data, response) = try await URLSession.shared.data(for: req)
+ (data, response) = try await session.data(for: req)
} catch let e as URLError where e.code == .timedOut {
throw Failure.timeout
} catch {
diff --git a/Sources/LiveSubs/VirtualMic.swift b/Sources/LiveSubs/VirtualMic.swift
index 0db75c3..dfd82e8 100644
--- a/Sources/LiveSubs/VirtualMic.swift
+++ b/Sources/LiveSubs/VirtualMic.swift
@@ -48,6 +48,8 @@ final class VirtualMicInstaller: ObservableObject {
var speakThrough: ((_ text: String, _ language: String, _ device: OutputDevice) async -> Void)?
/// Called once Core Audio has the device (after an install or reload).
var onLoaded: (() -> Void)?
+ /// Tests swap in a session with a stub protocol.
+ var session: URLSession = .shared
var device: OutputDevice? { AudioDevices.virtualMic }
var isLoaded: Bool { device != nil }
@@ -120,7 +122,7 @@ final class VirtualMicInstaller: ObservableObject {
private func download() async -> URL? {
state = .downloading
do {
- let (tmp, response) = try await URLSession.shared.download(from: Self.packageURL)
+ let (tmp, response) = try await session.download(from: Self.packageURL)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
state = .failed(L("下载失败,请检查网络"))
return nil
diff --git a/Tests/LiveSubsTests/LingTests.swift b/Tests/LiveSubsTests/LingTests.swift
new file mode 100644
index 0000000..57133c4
--- /dev/null
+++ b/Tests/LiveSubsTests/LingTests.swift
@@ -0,0 +1,168 @@
+import Foundation
+import Testing
+@testable import LiveSubs
+
+/// Answers Ling requests from the test, and keeps what was asked. Requests reach a URLProtocol
+/// with the body as a stream, not `httpBody`.
+final class LingStub: URLProtocol, @unchecked Sendable {
+ nonisolated(unsafe) static var reply: (Int, String) = (200, "")
+ nonisolated(unsafe) static var seen: [(at: Date, body: [String: Any])] = []
+ private static let lock = NSLock()
+
+ static func reset(_ status: Int = 200, _ body: String) {
+ lock.withLock { reply = (status, body); seen = [] }
+ }
+
+ static func chatReply(_ text: String, finish: String? = "stop") -> String {
+ var choice: [String: Any] = ["message": ["content": text]]
+ if let finish { choice["finish_reason"] = finish }
+ return String(data: try! JSONSerialization.data(withJSONObject: ["choices": [choice]]), encoding: .utf8)!
+ }
+
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+
+ override func startLoading() {
+ var data = Data()
+ if let stream = request.httpBodyStream {
+ stream.open()
+ var buf = [UInt8](repeating: 0, count: 4096)
+ while stream.hasBytesAvailable { let n = stream.read(&buf, maxLength: buf.count); if n <= 0 { break }; data.append(buf, count: n) }
+ stream.close()
+ }
+ let body = (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:]
+ let (status, text) = Self.lock.withLock { Self.seen.append((Date(), body)); return Self.reply }
+ let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Data(text.utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
+/// The key file and the Ling client share `AIKey`'s state, so these run one at a time in a temp folder.
+@MainActor @Suite(.serialized) struct LingTests {
+ let folder: URL
+
+ init() {
+ folder = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-key-\(UUID().uuidString)")
+ AIKey.folderOverride = folder
+ }
+
+ private func client() -> LingClient {
+ AIKey.save("sk-test-0000000000")
+ let ling = LingClient()
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [LingStub.self]
+ ling.session = URLSession(configuration: config)
+ return ling
+ }
+
+ // MARK: Key file
+
+ @Test func keyFileIsOnlyForThisUser() throws {
+ #expect(AIKey.save("sk-abc1234567890"))
+ let file = folder.appendingPathComponent("ling-api-key")
+ let fm = FileManager.default
+ #expect(try fm.attributesOfItem(atPath: file.path)[.posixPermissions] as? Int == 0o600)
+ #expect(try fm.attributesOfItem(atPath: folder.path)[.posixPermissions] as? Int == 0o700)
+ #expect(try file.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup == true)
+ #expect(try String(contentsOf: file, encoding: .utf8) == "sk-abc1234567890")
+ }
+
+ @Test func keyIsNotInUserDefaults() {
+ let key = "sk-not-in-defaults-\(UUID().uuidString)"
+ AIKey.save(key)
+ let values = UserDefaults.standard.dictionaryRepresentation().values.map { "\($0)" }
+ #expect(!values.contains(where: { $0.contains(key) }))
+ }
+
+ @Test func keyReadsTrimmedAndRemoves() throws {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ try " sk-spaced-key \n".write(to: folder.appendingPathComponent("ling-api-key"), atomically: true, encoding: .utf8)
+ AIKey.folderOverride = folder // forget the cached value
+ #expect(AIKey.read() == "sk-spaced-key")
+ AIKey.remove()
+ #expect(AIKey.read() == nil)
+ #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("ling-api-key").path))
+ }
+
+ @Test func emptyKeyFileIsNoKey() throws {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ try " \n".write(to: folder.appendingPathComponent("ling-api-key"), atomically: true, encoding: .utf8)
+ AIKey.folderOverride = folder
+ #expect(AIKey.read() == nil)
+ }
+
+ @Test func maskedShowsOnlyTheEnds() {
+ #expect(AIKey.masked("sk-abcdefghij3f9a") == "sk-" + String(repeating: "•", count: 12) + "3f9a")
+ #expect(AIKey.masked("short") == "sk-…")
+ }
+
+ // MARK: Client
+
+ @Test func contentGoesInTheSystemMessageAndThinkingIsOff() async throws {
+ let ling = client()
+ LingStub.reset(200, LingStub.chatReply(" Hello. "))
+ let out = try await ling.chat(content: "你好。", instruction: "Translate the system message.", priority: .translate)
+ #expect(out == "Hello.")
+ let body = try #require(LingStub.seen.first?.body)
+ #expect((body["thinking"] as? [String: String])?["type"] == "disabled")
+ #expect(body["stream"] as? Bool == false)
+ let messages = try #require(body["messages"] as? [[String: Any]])
+ #expect(messages.count == 2)
+ #expect(messages[0]["role"] as? String == "system")
+ #expect(messages[0]["content"] as? String == "你好。")
+ #expect(messages[1]["role"] as? String == "user")
+ #expect(messages[1]["content"] as? String == "Translate the system message.")
+ }
+
+ @Test func rejectedKeyIsMarkedInvalid() async {
+ let ling = client()
+ LingStub.reset(401, "{}")
+ await #expect(throws: LingClient.Failure.invalidKey) {
+ try await ling.chat(content: "x", instruction: "y", priority: .translate)
+ }
+ #expect(ling.keyState == .invalid)
+ #expect(!ling.usable)
+ }
+
+ @Test func searchStyleRepliesAreDropped() async {
+ let ling = client()
+ LingStub.reset(200, LingStub.chatReply("根据现有检索证据,……"))
+ await #expect(throws: LingClient.Failure.hijacked) {
+ try await ling.chat(content: "x", instruction: "y", priority: .translate)
+ }
+ LingStub.reset(200, LingStub.chatReply("Hello.", finish: nil))
+ await #expect(throws: LingClient.Failure.hijacked) {
+ try await ling.chat(content: "x", instruction: "y", priority: .translate)
+ }
+ }
+
+ @Test func noKeyMeansNoRequest() async {
+ let ling = client()
+ AIKey.remove()
+ LingStub.reset(200, LingStub.chatReply("Hello."))
+ await #expect(throws: LingClient.Failure.noKey) {
+ try await ling.chat(content: "x", instruction: "y", priority: .translate)
+ }
+ #expect(LingStub.seen.isEmpty)
+ }
+
+ @Test func startsAreSpacedAndGoInPriorityOrder() async throws {
+ let ling = client()
+ LingStub.reset(200, LingStub.chatReply("ok"))
+ // The first call takes the gate; the next three queue behind it, asked in reverse priority.
+ _ = try await ling.chat(content: "first", instruction: "i", priority: .notes)
+ async let notes = ling.chat(content: "notes", instruction: "i", priority: .notes)
+ async let translate = ling.chat(content: "translate", instruction: "i", priority: .translate)
+ async let speak = ling.chat(content: "speak", instruction: "i", priority: .speak)
+ _ = try await (notes, translate, speak)
+ let order = LingStub.seen.map { (($0.body["messages"] as? [[String: Any]])?.first?["content"] as? String) ?? "" }
+ #expect(order == ["first", "speak", "translate", "notes"])
+ let times = LingStub.seen.map(\.at)
+ for (a, b) in zip(times, times.dropFirst()) {
+ #expect(b.timeIntervalSince(a) >= 0.55)
+ }
+ }
+}
diff --git a/Tests/LiveSubsTests/TranslatorTests.swift b/Tests/LiveSubsTests/TranslatorTests.swift
index d0f5862..d98773e 100644
--- a/Tests/LiveSubsTests/TranslatorTests.swift
+++ b/Tests/LiveSubsTests/TranslatorTests.swift
@@ -47,4 +47,21 @@ import Testing
#expect(TranslationService.cleanTranslation("We ship on Friday.", target: "zh-CN") == nil)
#expect(TranslationService.cleanTranslation("我们周五发布。", target: "en-US") == nil)
}
+
+ // What you say is spoken into the room only as Ming's translation; anything that is not
+ // clearly one sends the press to the on-device path instead.
+ @MainActor @Test func interpretationNeedsBothLinesAndARealTranslation() {
+ let good = TranslationService.parseInterpretation("ORIGINAL: 我们周五发布。\nTRANSLATION: We ship on Friday.", target: "en-US")
+ #expect(good?.original == "我们周五发布。")
+ #expect(good?.translation == "We ship on Friday.")
+ #expect(TranslationService.parseInterpretation("ORIGINAL: 我们周五发布。", target: "en-US") == nil)
+ #expect(TranslationService.parseInterpretation("ORIGINAL: 我们周五发布。\nTRANSLATION:", target: "en-US") == nil)
+ #expect(TranslationService.parseInterpretation("We ship on Friday.", target: "en-US") == nil)
+ }
+
+ @MainActor @Test func interpretationThatRepeatsTheOriginalIsDropped() {
+ #expect(TranslationService.parseInterpretation("ORIGINAL: OK.\nTRANSLATION: OK.", target: "zh-CN") == nil)
+ #expect(TranslationService.parseInterpretation("ORIGINAL: 我们周五发布。\nTRANSLATION: 我们周五发布。", target: "en-US") == nil)
+ #expect(TranslationService.parseInterpretation("ORIGINAL: We ship on Friday.\nTRANSLATION: We ship on Friday", target: "zh-CN") == nil)
+ }
}
diff --git a/Tests/LiveSubsTests/VirtualMicTests.swift b/Tests/LiveSubsTests/VirtualMicTests.swift
new file mode 100644
index 0000000..253a927
--- /dev/null
+++ b/Tests/LiveSubsTests/VirtualMicTests.swift
@@ -0,0 +1,39 @@
+import Foundation
+import Testing
+@testable import LiveSubs
+
+/// Serves a package that is not BlackHole.
+final class FakePackage: URLProtocol, @unchecked Sendable {
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+ override func startLoading() {
+ let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Data("not the driver".utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
+@MainActor @Suite struct VirtualMicTests {
+ @Test func pinnedPackageIsHTTPSAndAFullHash() {
+ #expect(VirtualMicInstaller.packageURL.scheme == "https")
+ #expect(VirtualMicInstaller.packageSHA256.range(of: "^[0-9a-f]{64}$", options: .regularExpression) != nil)
+ }
+
+ @Test func aPackageWithTheWrongHashIsNotInstalled() async throws {
+ let pkg = FileManager.default.temporaryDirectory.appendingPathComponent("LiveSubsMic/BlackHole2ch.pkg")
+ try? FileManager.default.removeItem(at: pkg)
+ let installer = VirtualMicInstaller()
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [FakePackage.self]
+ installer.session = URLSession(configuration: config)
+ installer.install(verifyOnly: true)
+ for _ in 0..<100 {
+ if case .failed = installer.state { break }
+ try await Task.sleep(nanoseconds: 50_000_000)
+ }
+ #expect(installer.state == .failed(L("安装包校验未通过,已中止安装")))
+ #expect(!FileManager.default.fileExists(atPath: pkg.path))
+ }
+}