import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; String? extractAudioUrl(String responseBody) { try { final List entries = jsonDecode(responseBody) as List; for (final entry in entries) { if (entry is Map) { final phonetics = entry['phonetics']; if (phonetics is List) { for (final phonetic in phonetics) { if (phonetic is Map) { 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); }); }); }