krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDayTests/SpeechCompletionTests.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDayTests/SpeechCompletionTests.swift history · blame · raw

142 lines · 5748 bytes

13 symbols in this file
  1import AVFoundation
  2import Foundation
  3import Testing
  4@testable import DayByDay
  5
  6/// One serialized suite, since every test drives the shared speech engine.
  7@MainActor
  8@Suite(.serialized, .timeLimit(.minutes(1)))
  9struct SpeechCompletionTests {
 10    let speech = SpeechSynthesizer.shared
 11
 12    /// A library with "Alpha." and "Beta." as 0.3 s tones; "Gamma." has no clip.
 13    static let library: ClipLibrary = {
 14        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("clips-\(UUID().uuidString)")
 15        try! FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
 16        var entries: [[String: Any]] = []
 17        for (i, text) in ["Alpha.", "Beta."].enumerated() {
 18            let file = "tone\(i).wav"
 19            let format = AVAudioFormat(standardFormatWithSampleRate: 24_000, channels: 1)!
 20            let out = try! AVAudioFile(forWriting: dir.appendingPathComponent(file), settings: format.settings)
 21            let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 7_200)!
 22            buffer.frameLength = 7_200
 23            for n in 0..<7_200 { buffer.floatChannelData![0][n] = 0.2 * sin(Float(n) * 0.1) }
 24            try! out.write(from: buffer)
 25            entries.append(["text": text, "file": file, "seconds": 0.3])
 26        }
 27        let manifest = dir.appendingPathComponent("voice-manifest.json")
 28        try! JSONSerialization.data(withJSONObject: entries).write(to: manifest)
 29        return ClipLibrary(manifest: manifest, directory: dir)!
 30    }()
 31
 32    func say(_ text: String) async {
 33        await withCheckedContinuation { cont in speech.speak(text) { cont.resume() } }
 34    }
 35
 36    @Test func completionFiresWhenSpeechEnds() async {
 37        speech.library = nil
 38        await say("One.")
 39    }
 40
 41    @Test func interruptedSpeechDoesNotComplete() async throws {
 42        speech.library = nil
 43        var first = false
 44        speech.speak("Sunday, Monday, Tuesday, Wednesday.") { first = true }
 45        try await Task.sleep(for: .milliseconds(300))
 46        await say("Two.")
 47        #expect(!first)
 48    }
 49
 50    @Test func clipLineCompletes() async {
 51        speech.library = Self.library
 52        speech.speak("Alpha. Beta.")
 53        #expect(speech.isPlayingClips)
 54        await say("Alpha. Beta.")
 55        #expect(!speech.isPlayingClips)
 56    }
 57
 58    @Test func missingSentenceFallsBackForWholeLine() async {
 59        speech.library = Self.library
 60        speech.speak("Alpha. Gamma.")
 61        #expect(!speech.isPlayingClips)
 62        await say("Alpha. Gamma.")
 63    }
 64
 65    @Test func clipCutOffByTTSCompletesOnlySecond() async throws {
 66        speech.library = Self.library
 67        var first = false
 68        speech.speak("Alpha. Beta.") { first = true }
 69        try await Task.sleep(for: .milliseconds(100))
 70        await say("Gamma.")
 71        try await Task.sleep(for: .milliseconds(800))
 72        #expect(!first)
 73    }
 74
 75    @Test func ttsCutOffByClipCompletesOnlySecond() async throws {
 76        speech.library = Self.library
 77        var first = false
 78        speech.speak("Gamma. Sunday, Monday, Tuesday, Wednesday.") { first = true }
 79        try await Task.sleep(for: .milliseconds(300))
 80        await say("Alpha.")
 81        try await Task.sleep(for: .milliseconds(300))
 82        #expect(!first)
 83    }
 84
 85    func interrupt(_ type: AVAudioSession.InterruptionType) {
 86        NotificationCenter.default.post(name: AVAudioSession.interruptionNotification, object: nil,
 87                                        userInfo: [AVAudioSessionInterruptionTypeKey: type.rawValue])
 88    }
 89
 90    /// An interruption pauses the clip; when it ends, the clip resumes and the line finishes.
 91    @Test func interruptionPausesAndResumes() async throws {
 92        speech.library = Self.library
 93        var fired = false
 94        speech.speak("Alpha.") { fired = true }
 95        try await Task.sleep(for: .milliseconds(50))
 96        interrupt(.began)
 97        try await Task.sleep(for: .milliseconds(700))
 98        #expect(!fired)
 99        interrupt(.ended)
100        try await Task.sleep(for: .milliseconds(600))
101        #expect(fired)
102    }
103
104    /// An interruption that never ends must not freeze a game waiting on the line:
105    /// it ends once its known length plus a grace period has passed.
106    @Test func stalledClipLineStillCompletes() async throws {
107        speech.library = Self.library
108        var fired = false
109        speech.speak("Alpha.") { fired = true }
110        try await Task.sleep(for: .milliseconds(50))
111        interrupt(.began)
112        try await Task.sleep(for: .milliseconds(700))
113        #expect(!fired)
114        try await Task.sleep(for: .milliseconds(SpeechSynthesizer.clipGrace * 1_000 + 500))
115        #expect(fired)
116        #expect(!speech.isPlayingClips)
117        speech.library = ClipLibrary.bundled
118    }
119
120    /// A line the bundled clips lack would play in the system voice.
121    @Test func uncatalogedLineIsFlagged() {
122        speech.library = ClipLibrary.bundled
123        #expect(speech.missingClipWarning(for: "Super!") == nil)
124        #expect(speech.missingClipWarning(for: "Super! Not in the catalog.")?.contains("Not in the catalog.") == true)
125        #expect(speech.missingClipWarning(for: "") == nil)
126        speech.library = Self.library
127        #expect(speech.missingClipWarning(for: "Gamma.") == nil)
128        speech.library = ClipLibrary.bundled
129    }
130
131    @Test func stopDropsClipCompletion() async throws {
132        speech.library = Self.library
133        var fired = false
134        speech.speak("Alpha. Beta.") { fired = true }
135        try await Task.sleep(for: .milliseconds(100))
136        speech.stop()
137        try await Task.sleep(for: .milliseconds(1_000))
138        #expect(!fired)
139        #expect(!speech.isPlayingClips)
140        speech.library = ClipLibrary.bundled
141    }
142}