113 lines
2.7 KiB
Dart
113 lines
2.7 KiB
Dart
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);
|
||
});
|
||
});
|
||
}
|