cyberhybridhub/test/services/dictionary_audio_parsing_test.dart
nathanAndrinoid a521a74214
Some checks failed
Admin portal tests / test (push) Has been cancelled
balance controled working spelling and market questions.
2026-06-17 04:20:45 +00:00

113 lines
2.7 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
String? extractAudioUrl(String responseBody) {
try {
final List<dynamic> entries = jsonDecode(responseBody) as List<dynamic>;
for (final entry in entries) {
if (entry is Map<String, dynamic>) {
final phonetics = entry['phonetics'];
if (phonetics is List<dynamic>) {
for (final phonetic in phonetics) {
if (phonetic is Map<String, dynamic>) {
final String? audio = phonetic['audio'] as String?;
if (audio != null && audio.isNotEmpty) {
if (audio.startsWith('//')) {
return 'https:$audio';
}
return audio;
}
}
}
}
}
}
} catch (_) {}
return null;
}
void main() {
group('Dictionary Audio Parser Tests', () {
test('extracts standard audio URL', () {
const jsonStr = '''
[
{
"word": "hello",
"phonetics": [
{
"text": "/həˈləʊ/",
"audio": "https://api.dictionaryapi.dev/media/pronunciations/en/hello-uk.mp3"
}
]
}
]
''';
expect(
extractAudioUrl(jsonStr),
'https://api.dictionaryapi.dev/media/pronunciations/en/hello-uk.mp3',
);
});
test('handles protocol-relative URL starting with //', () {
const jsonStr = '''
[
{
"word": "test",
"phonetics": [
{
"audio": "//ssl.gstatic.com/dictionary/static/sounds/20201201/test--us.mp3"
}
]
}
]
''';
expect(
extractAudioUrl(jsonStr),
'https://ssl.gstatic.com/dictionary/static/sounds/20201201/test--us.mp3',
);
});
test('skips empty audio fields and selects first valid audio URL', () {
const jsonStr = '''
[
{
"word": "multiple",
"phonetics": [
{
"text": "/mʌl.tɪ.pl̩/",
"audio": ""
},
{
"audio": "https://example.com/valid.mp3"
}
]
}
]
''';
expect(
extractAudioUrl(jsonStr),
'https://example.com/valid.mp3',
);
});
test('returns null for empty json or missing audio', () {
expect(extractAudioUrl('[]'), isNull);
expect(extractAudioUrl('invalid json'), isNull);
const missingAudioJson = '''
[
{
"word": "missing",
"phonetics": [
{
"text": "/mɪs.ɪŋ/"
}
]
}
]
''';
expect(extractAudioUrl(missingAudioJson), isNull);
});
});
}