Files
Speech/apps/api/internal/services/speech_test.go
T
Eugenius Naumenko e274eaab2b Adaptiven A1-Kurs und statistisches Aussprachetraining integrieren
Direkte DeepSeek- und Mistral-Anbindung mit versionierten Aktionsprofilen,
Budgetreservierung, Tokenabrechnung und administrativen Qualitätsprüfungen
ersetzen die Flowise-Abhängigkeit im regulären Betrieb.

840 geprüfte A1-Aufgaben mit geschützter Testauswertung und konkreten offenen
Arbeitsaufträgen ergänzen den Kurs. Inhalts- und Sprachbewertung bleiben von
Azure-Aussprachewerten getrennt; historische Aufgaben und Antworten bleiben erhalten.

Echte Wort- und Phonemmessungen werden mit Herkunft, Aktualität und Nachweisdichte
gebündelt. Go bestimmt Trainingsziele und Wiederholungen, das Modell formuliert
dazu passende Nachsprechübungen. Profilansicht und Auswahlgründe werden angezeigt.

Validierung: Go-Race-Tests mit lokaler PostgreSQL-Integration, go vet,
Web-Build, Audit aller 840 Aufgaben und drei Browser-Smokes mit lokalen
Modell-/Speech-Fixtures bestanden. Keine Produktionsänderungen oder Live-Aufrufe.
2026-11-01 23:23:20 +00:00

207 lines
7.2 KiB
Go

package services
import (
"context"
"encoding/xml"
"io"
"log/slog"
"net/http"
"strings"
"testing"
"speech-learning-api/internal/config"
)
type speechRoundTripFunc func(*http.Request) (*http.Response, error)
func (fn speechRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
func TestSynthesizeExerciseSendsValidSSML(t *testing.T) {
for _, test := range []struct {
mode string
word string
rates []string
}{
{"slow", "", []string{"0.8"}},
{"focus", "chips", []string{"0.7", "0.8"}},
} {
t.Run(test.mode, func(t *testing.T) {
var body string
service := &AzureSpeechService{
cfg: config.Config{AzureSpeechKey: "test-key", AzureRegion: "test-region"},
client: &http.Client{Transport: speechRoundTripFunc(func(req *http.Request) (*http.Response, error) {
payload, err := io.ReadAll(req.Body)
if err != nil {
t.Fatal(err)
}
body = string(payload)
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("mp3")), Header: make(http.Header)}, nil
})},
}
_, _, err := service.SynthesizeExercise(context.Background(), "en-US", "en-US-JennyNeural", "Fish & chips are tasty.", test.mode, test.word)
if err != nil {
t.Fatal(err)
}
decoder := xml.NewDecoder(strings.NewReader(body))
for {
_, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("invalid SSML: %v; body %q", err, body)
}
}
if !strings.Contains(body, "Fish & chips are tasty.") {
t.Fatalf("sentence was not XML-escaped: %q", body)
}
for _, rate := range test.rates {
if !strings.Contains(body, `rate="`+rate+`"`) {
t.Fatalf("missing rate %s: %q", rate, body)
}
}
if test.mode == "focus" && (!strings.Contains(body, `<break time="400ms"/>`) || !strings.Contains(body, `>chips</prosody>`)) {
t.Fatalf("focus clip lacks the word or pause: %q", body)
}
})
}
}
func TestMockPronunciationReturnsWordScores(t *testing.T) {
result := mockPronunciation("Hello, my name is Anna.")
if result.Provider != "mock" {
t.Fatalf("expected mock provider, got %s", result.Provider)
}
if len(result.WordScores) != 5 {
t.Fatalf("expected 5 word scores, got %d", len(result.WordScores))
}
if result.OverallScore <= 0 {
t.Fatalf("expected positive score, got %f", result.OverallScore)
}
}
func TestParseAzurePronunciationTopLevelScores(t *testing.T) {
body := []byte(`{
"RecognitionStatus": "Success",
"DisplayText": "Can I have a coffee please?",
"NBest": [{
"Display": "Can I have a coffee please?",
"AccuracyScore": 94.0,
"FluencyScore": 99.0,
"CompletenessScore": 100.0,
"PronScore": 96.2,
"Words": [{
"Word": "can",
"AccuracyScore": 94.0,
"ErrorType": "None",
"Phonemes": [{"Phoneme": "k"}, {"Phoneme": "ae"}, {"Phoneme": "n"}]
}]
}]
}`)
result, err := parseAzurePronunciation(body)
if err != nil {
t.Fatalf("parse azure pronunciation: %v", err)
}
if result.Provider != "azure" {
t.Fatalf("expected azure provider, got %s", result.Provider)
}
if result.OverallScore != 96.2 {
t.Fatalf("expected overall score 96.2, got %f", result.OverallScore)
}
if result.AccuracyScore != 94 {
t.Fatalf("expected accuracy score 94, got %f", result.AccuracyScore)
}
if len(result.WordScores) != 1 {
t.Fatalf("expected one word score, got %d", len(result.WordScores))
}
if result.WordScores[0].Accuracy != 94 {
t.Fatalf("expected word accuracy 94, got %f", result.WordScores[0].Accuracy)
}
if result.WordScores[0].Highlight != "good" {
t.Fatalf("expected good highlight, got %s", result.WordScores[0].Highlight)
}
if len(result.WordScores[0].PhonemeScores) != 0 {
t.Fatalf("unscored phonemes must not become zero-point weaknesses: %#v", result.WordScores[0].PhonemeScores)
}
}
func TestParseAzurePronunciationKeepsPhonemeScores(t *testing.T) {
body := []byte(`{
"NBest": [{"Display":"water","PronScore":82,"Words":[{
"Word":"water","AccuracyScore":80,
"Phonemes":[
{"Phoneme":"w","PronunciationAssessment":{"AccuracyScore":93}},
{"Phoneme":"ɔ","PronunciationAssessment":{"AccuracyScore":0}},
{"Phoneme":"t","AccuracyScore":58},
{"Phoneme":"ə"}
]
}]}]
}`)
result, err := parseAzurePronunciation(body)
if err != nil {
t.Fatalf("parse azure pronunciation: %v", err)
}
word := result.WordScores[0]
if len(word.Phonemes) != 4 || len(word.PhonemeScores) != 3 {
t.Fatalf("expected four phoneme labels and three scored phonemes, got %#v", word)
}
if word.PhonemeScores[0].Accuracy != 93 || word.PhonemeScores[0].Highlight != "good" {
t.Fatalf("unexpected first phoneme score %#v", word.PhonemeScores[0])
}
if word.PhonemeScores[1].Accuracy != 0 || word.PhonemeScores[1].Highlight != "weak" {
t.Fatalf("zero is a valid low score, got %#v", word.PhonemeScores[1])
}
if word.PhonemeScores[2].Accuracy != 58 || word.PhonemeScores[2].Highlight != "weak" {
t.Fatalf("top-level phoneme score was not read: %#v", word.PhonemeScores[2])
}
}
func TestFreeSpeechTranscribesActualAudioWithoutReference(t *testing.T) {
calls := 0
service := NewAzureSpeechService(config.Config{AzureSpeechKey: "test-key", AzureRegion: "test-region"}, slog.New(slog.NewTextHandler(io.Discard, nil)))
service.client = &http.Client{Transport: speechRoundTripFunc(func(r *http.Request) (*http.Response, error) {
calls++
if r.URL.Query().Get("language") != "es-ES" || r.Header.Get("Pronunciation-Assessment") != "" {
t.Error("transcription must not have a reference assessment")
}
body, _ := io.ReadAll(r.Body)
if string(body) != "actual recording" {
t.Error("recording changed")
}
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"RecognitionStatus":"Success","NBest":[{"Display":"Me llamo Ana."}]}`)), Header: http.Header{}}, nil
})}
transcript, err := service.Transcribe(context.Background(), []byte("actual recording"), "audio/wav", "es-ES")
if err != nil || transcript != "Me llamo Ana." {
t.Fatal(transcript, err)
}
service.cfg.AzureMock = true
if _, err = service.Transcribe(context.Background(), []byte("actual recording"), "audio/wav", "es-ES"); err == nil || calls != 1 {
t.Fatal("mock fabricated a free-speech transcript")
}
}
func TestAzureParserMissingWordScoreIsNotZeroEvidence(t *testing.T) {
result, err := parseAzurePronunciation([]byte(`{"RecognitionStatus":"Success","NBest":[{"Words":[{"Word":"cat","Phonemes":[{"Phoneme":"k","PronunciationAssessment":{"AccuracyScore":30}}]}]}]}`))
if err != nil {
t.Fatal(err)
}
if len(result.WordScores) != 1 || result.WordScores[0].AccuracyMeasured == nil || *result.WordScores[0].AccuracyMeasured {
t.Fatal("missing score labelled measured", result)
}
}
func TestAzureParserPreservesOriginalPositionsAcrossMissingScores(t *testing.T) {
result, err := parseAzurePronunciation([]byte(`{"NBest":[{"Words":[{"Word":"cat","AccuracyScore":90,"Phonemes":[{"Phoneme":"k","AccuracyScore":40},{"Phoneme":"æ"},{"Phoneme":"t","AccuracyScore":70}]}]}]}`))
if err != nil {
t.Fatal(err)
}
scores := result.WordScores[0].PhonemeScores
if len(scores) != 2 || scores[0].Position == nil || *scores[0].Position != 0 || scores[1].Position == nil || *scores[1].Position != 2 {
t.Fatal("original positions lost", scores)
}
}