diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index f39da0f..dfad48c 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -26,8 +26,8 @@ jobs: - uses: gradle/actions/setup-gradle@v4 with: gradle-version: '8.9' - - name: Build APK - run: gradle --no-daemon :app:assembleDebug + - name: Test and build APK + run: gradle --no-daemon :app:testDebugUnitTest :app:assembleDebug - uses: actions/upload-artifact@v4 with: name: LikeFolder-debug-apk diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 33a91cf..baf3ab6 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -7,8 +7,8 @@ android { applicationId = "com.likefolder.app" minSdk = 29 targetSdk = 35 - versionCode = 1 - versionName = "0.1.0" + versionCode = 3 + versionName = "0.1.2" } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 @@ -18,4 +18,5 @@ android { dependencies { implementation("androidx.work:work-runtime:2.10.0") + testImplementation("junit:junit:4.13.2") } diff --git a/app/src/main/java/com/likefolder/app/DeviceCodePoller.java b/app/src/main/java/com/likefolder/app/DeviceCodePoller.java new file mode 100644 index 0000000..427f014 --- /dev/null +++ b/app/src/main/java/com/likefolder/app/DeviceCodePoller.java @@ -0,0 +1,75 @@ +package com.likefolder.app; + +import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Polls one device code until authorization, cancellation, or expiry. */ +final class DeviceCodePoller { + private static final long MIN_INTERVAL_MS = 5000; + private static final long MAX_NETWORK_DELAY_MS = 60000; + private static final Pattern OAUTH_ERROR = Pattern.compile( + "\"error\"\\s*:\\s*\"(authorization_pending|slow_down)\""); + + interface Request { T request() throws IOException; } + interface Clock { long now(); } + interface Sleeper { void sleep(long millis) throws InterruptedException; } + interface Listener { void onWaiting(boolean networkRetry); } + + static final class ExpiredException extends IOException { + ExpiredException(IOException networkFailure) { + super(networkFailure == null + ? "Время действия кода истекло. Получи новый код." + : "Время действия кода истекло: нет связи с Яндексом. Проверь интернет, VPN и Частный DNS, затем получи новый код.", + networkFailure); + } + } + + static T await(Request request, long intervalMs, long expiresAtMs, + Clock clock, Sleeper sleeper, Listener listener) throws IOException, InterruptedException { + long serverInterval = Math.max(MIN_INTERVAL_MS, intervalMs); + long delay = serverInterval; + IOException lastNetworkFailure = null; + while (true) { + checkInterrupted(); + long remaining = expiresAtMs - clock.now(); + if (remaining <= 0) throw new ExpiredException(lastNetworkFailure); + sleeper.sleep(Math.min(delay, remaining)); + checkInterrupted(); + // The code can expire while sleeping, particularly after a network backoff. + if (clock.now() >= expiresAtMs) throw new ExpiredException(lastNetworkFailure); + try { + T result = request.request(); + checkInterrupted(); + return result; + } catch (IOException ex) { + checkInterrupted(); + if (ex instanceof Net.ApiError) { + Matcher error = OAUTH_ERROR.matcher(String.valueOf(ex.getMessage())); + if (!error.find()) throw ex; + lastNetworkFailure = null; + if ("slow_down".equals(error.group(1))) serverInterval += MIN_INTERVAL_MS; + delay = serverInterval; + listener.onWaiting(false); + } else if (ex instanceof UnknownHostException || ex instanceof SocketTimeoutException + || ex instanceof SocketException) { + lastNetworkFailure = ex; + delay = Math.max(serverInterval, Math.min(MAX_NETWORK_DELAY_MS, delay * 2)); + listener.onWaiting(true); + } else { + // Malformed responses, TLS errors, and other terminal failures must surface. + throw ex; + } + } + } + } + + private static void checkInterrupted() throws InterruptedException { + if (Thread.currentThread().isInterrupted()) throw new InterruptedException("Авторизация отменена"); + } + + private DeviceCodePoller() { } +} diff --git a/app/src/main/java/com/likefolder/app/MainActivity.java b/app/src/main/java/com/likefolder/app/MainActivity.java index ad2694c..ea76b07 100644 --- a/app/src/main/java/com/likefolder/app/MainActivity.java +++ b/app/src/main/java/com/likefolder/app/MainActivity.java @@ -15,6 +15,7 @@ import android.os.Bundle; import android.os.Handler; import android.os.Looper; +import android.os.SystemClock; import android.text.InputType; import android.view.Gravity; import android.view.View; @@ -27,9 +28,13 @@ import android.widget.Switch; import android.widget.TextView; import org.json.JSONObject; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; /** Lightweight native Android UI, no overlays or hooks into the official Yandex app. */ public final class MainActivity extends Activity { @@ -42,12 +47,14 @@ public final class MainActivity extends Activity { private Store store; private LinearLayout loginCard, controls; private TextView statusText, countText, folderLabel, codeLabel, codeHint; - private Button codeButton, copyButton; + private Button loginButton, codeButton, copyButton; private EditText folderEdit; private Switch quickSwitch; private CheckBox wifiOnly; private boolean changingSwitch = false; - private volatile boolean authorizing = false; + private boolean authorizing = false; + private int loginAttempt = 0; + private Future loginTask; private volatile String verificationUrl = "", userCode = ""; private final Runnable ticker = new Runnable() { @Override public void run() { refresh(); handler.postDelayed(this, 2000); } @@ -67,7 +74,9 @@ public final class MainActivity extends Activity { super.onResume(); handler.removeCallbacks(ticker); ticker.run(); } @Override protected void onPause() { handler.removeCallbacks(ticker); super.onPause(); } - @Override protected void onDestroy() { executor.shutdownNow(); super.onDestroy(); } + @Override protected void onDestroy() { + cancelLogin(); executor.shutdownNow(); super.onDestroy(); + } private void buildUI() { ScrollView scroll = new ScrollView(this); @@ -98,9 +107,9 @@ private void buildUI() { loginCard.addView(loginTitle); TextView loginDesc = text("Вход по коду на странице Яндекса. Пароль не вводится в LikeFolder.", 14, MUTED, false); marginTop(loginDesc, 8); loginCard.addView(loginDesc); - Button loginBtn = button("Получить код входа", true); - marginTop(loginBtn, 16); loginCard.addView(loginBtn); - loginBtn.setOnClickListener(v -> startLogin(loginBtn)); + loginButton = button("Получить код входа", true); + marginTop(loginButton, 16); loginCard.addView(loginButton); + loginButton.setOnClickListener(v -> startLogin()); codeLabel = text("", 26, ACCENT, true); codeLabel.setTextIsSelectable(true); marginTop(codeLabel, 14); @@ -201,52 +210,82 @@ private void buildUI() { .setPositiveButton("Отключить", (d, w) -> logout()).show()); marginTop(account, 14); controls.addView(account); } - private void startLogin(Button loginButton) { + private void startLogin() { if (authorizing) return; + final int attempt = ++loginAttempt; + clearLoginCode(); authorizing = true; loginButton.setEnabled(false); codeHint.setText("Получаю код авторизации…"); - executor.execute(() -> { + loginTask = executor.submit(() -> { try { JSONObject code = YandexApi.requestCode(UUID.randomUUID().toString().replace("-", "").substring(0, 16)); + if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); String device = code.getString("device_code"); String user = code.getString("user_code"); - String link = code.optString("verification_url", "https://ya.ru/device"); - int waitSeconds = Math.max(5, code.optInt("interval", 5)); - long until = System.currentTimeMillis() + 1000L * code.optInt("expires_in", 300); - verificationUrl = link; userCode = user; - runOnUiThread(() -> { + String link = code.optString("verification_url", "https://oauth.yandex.ru/device"); + long interval = 1000L * Math.max(5, code.optInt("interval", 5)); + long until = SystemClock.elapsedRealtime() + 1000L * Math.max(0, code.optInt("expires_in", 300)); + postLoginUpdate(attempt, () -> { + verificationUrl = link; userCode = user; codeLabel.setText(user); codeHint.setText("Открой сайт, введи код и разреши доступ. Здесь вход продолжится автоматически."); codeButton.setVisibility(View.VISIBLE); copyButton.setVisibility(View.VISIBLE); }); - while (!Thread.currentThread().isInterrupted() && System.currentTimeMillis() < until) { - Thread.sleep(waitSeconds * 1000L); + JSONObject result = DeviceCodePoller.await(() -> YandexApi.pollCode(device), + interval, until, SystemClock::elapsedRealtime, Thread::sleep, + retrying -> postLoginUpdate(attempt, () -> codeHint.setText(retrying + ? "Связь с Яндексом прервалась. Повторяю проверку автоматически — новый код пока не нужен. Если ожидание затянется, переключи Wi-Fi или мобильный интернет." + : "Ожидаю подтверждения на странице Яндекса. Вход продолжится автоматически."))); + String access = result.getString("access_token"); + String refreshToken = result.optString("refresh_token", ""); + postLoginUpdate(attempt, () -> { try { - JSONObject result = YandexApi.pollCode(device); - String access = result.getString("access_token"); - store.saveTokens(access, result.optString("refresh_token", "")); + store.saveTokens(access, refreshToken); store.status("Аккаунт подключён. Получаю исходный список лайков…"); - runOnUiThread(() -> { - loginButton.setEnabled(true); codeHint.setText("Вход выполнен"); - SyncWorker.schedule(this); - startServiceAction(SyncService.ACTION_ONCE); - refresh(); - }); - return; - } catch (Net.ApiError ex) { - String message = ex.getMessage(); - if (message.contains("authorization_pending")) continue; - if (message.contains("slow_down")) { waitSeconds += 5; continue; } - throw ex; + finishLogin("Вход выполнен"); + SyncWorker.schedule(this); + startServiceAction(SyncService.ACTION_ONCE); + refresh(); + } catch (Exception ex) { + finishLogin(loginError(ex)); } - } - throw new IllegalStateException("Время действия кода истекло. Получи новый код."); + }); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + postLoginUpdate(attempt, () -> finishLogin("Вход отменён. Получи новый код, чтобы повторить.")); } catch (Exception ex) { - runOnUiThread(() -> { codeHint.setText("Не удалось подключиться: " + ex.getMessage()); loginButton.setEnabled(true); }); - } finally { authorizing = false; } + postLoginUpdate(attempt, () -> finishLogin(loginError(ex))); + } }); } + private void postLoginUpdate(int attempt, Runnable update) { + runOnUiThread(() -> { + if (attempt == loginAttempt && !isDestroyed() && !isFinishing()) update.run(); + }); + } + private void clearLoginCode() { + verificationUrl = ""; userCode = ""; + codeLabel.setText(""); + codeButton.setVisibility(View.GONE); copyButton.setVisibility(View.GONE); + } + private void finishLogin(String message) { + authorizing = false; loginTask = null; + loginButton.setEnabled(true); + clearLoginCode(); codeHint.setText(message); + } + private void cancelLogin() { + ++loginAttempt; + if (loginTask != null) loginTask.cancel(true); + finishLogin(""); + } + private static String loginError(Exception ex) { + if (ex instanceof UnknownHostException) + return "Не удалось найти сервер Яндекса. Проверь подключение, VPN и частный DNS или переключи сеть, затем получи новый код."; + if (ex instanceof SocketTimeoutException || ex instanceof SocketException) + return "Не удалось связаться с Яндексом. Проверь интернет и получи новый код."; + return "Не удалось подключиться: " + ex.getMessage(); + } private void showTokenDialog() { EditText input = new EditText(this); input.setSingleLine(true); @@ -259,6 +298,7 @@ private void showTokenDialog() { .setPositiveButton("Подключить", (dialog, which) -> { String token = input.getText().toString().trim(); if (token.length() < 20) { store.status("Токен выглядит слишком коротким"); return; } + cancelLogin(); store.saveTokens(token, ""); store.status("Проверяю введённый токен…"); SyncWorker.schedule(this); @@ -267,12 +307,10 @@ private void showTokenDialog() { }).show(); } private void logout() { + cancelLogin(); startService(new Intent(this, SyncService.class).setAction(SyncService.ACTION_STOP)); SyncWorker.cancel(this); store.signOut(); - verificationUrl = ""; userCode = ""; - codeLabel.setText(""); codeHint.setText(""); - codeButton.setVisibility(View.GONE); copyButton.setVisibility(View.GONE); refresh(); } private void startServiceAction(String action) { diff --git a/app/src/main/java/com/likefolder/app/SyncEngine.java b/app/src/main/java/com/likefolder/app/SyncEngine.java index 058eae9..5ad8534 100644 --- a/app/src/main/java/com/likefolder/app/SyncEngine.java +++ b/app/src/main/java/com/likefolder/app/SyncEngine.java @@ -83,7 +83,7 @@ String run(Mode mode) throws IOException { lastError = ex.getMessage(); // Prevent a failing API / expired entitlement from causing hundreds of network calls. if (ok == 0 && errors >= 5) { - String status = "MP3 недоступны, первые 5 загрузок завершились ошибкой: " + lastError; + String status = "Выгрузка остановлена: первые 5 загрузок завершились ошибкой. " + lastError; store.status(status); return status; } diff --git a/app/src/main/java/com/likefolder/app/YandexApi.java b/app/src/main/java/com/likefolder/app/YandexApi.java index fc4b108..1a73f83 100644 --- a/app/src/main/java/com/likefolder/app/YandexApi.java +++ b/app/src/main/java/com/likefolder/app/YandexApi.java @@ -116,16 +116,24 @@ String mp3Url(String trackId) throws IOException { String xml; try { xml = Net.readText(conn.getInputStream()); } finally { conn.disconnect(); } - String host = xmlTag(xml, "host"); - String path = xmlTag(xml, "path"); - String ts = xmlTag(xml, "ts"); - String s = xmlTag(xml, "s"); - if (!host.matches("[A-Za-z0-9.-]+") || !path.startsWith("/") || !ts.matches("[0-9]+")) - throw new IOException("Неподдерживаемый ответ CDN"); - String md5 = md5(CDN_SALT + path.substring(1) + s); - return "https://" + host + "/get-mp3/" + md5 + "/" + ts + path; + return mp3UrlFromXml(xml); } catch (org.json.JSONException ex) { throw new IOException("Не удалось получить ссылку на MP3", ex); } } + static String mp3UrlFromXml(String xml) throws IOException { + String host = xmlTag(xml, "host"); + String path = xmlTag(xml, "path"); + String ts = xmlTag(xml, "ts"); + String s = xmlTag(xml, "s"); + if (!host.matches("[A-Za-z0-9.-]+")) + throw new IOException("Неподдерживаемый ответ CDN: неверное поле host"); + if (!path.startsWith("/")) + throw new IOException("Неподдерживаемый ответ CDN: неверное поле path"); + // CDN timestamps contain hexadecimal digits. Preserve the original URL token verbatim. + if (!ts.matches("[0-9A-Fa-f]+")) + throw new IOException("Неподдерживаемый ответ CDN: неверное поле ts"); + String sign = md5(CDN_SALT + path.substring(1) + s); + return "https://" + host + "/get-mp3/" + sign + "/" + ts + path; + } private static String xmlTag(String xml, String tag) throws IOException { Matcher m = Pattern.compile("<" + tag + ">([^<]{1,2000})").matcher(xml); if (!m.find()) throw new IOException("Нет поля " + tag + " в CDN-ответе"); diff --git a/app/src/test/java/com/likefolder/app/DeviceCodePollerTest.java b/app/src/test/java/com/likefolder/app/DeviceCodePollerTest.java new file mode 100644 index 0000000..8f0f135 --- /dev/null +++ b/app/src/test/java/com/likefolder/app/DeviceCodePollerTest.java @@ -0,0 +1,159 @@ +package com.likefolder.app; + +import org.junit.Test; + +import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import javax.net.ssl.SSLHandshakeException; + +import static org.junit.Assert.*; + +public final class DeviceCodePollerTest { + private static final class Time implements DeviceCodePoller.Clock, DeviceCodePoller.Sleeper { + long now; + final List sleeps = new ArrayList<>(); + @Override public long now() { return now; } + @Override public void sleep(long millis) { sleeps.add(millis); now += millis; } + } + + private static Net.ApiError oauthError(String code) { + return new Net.ApiError(400, "HTTP 400 ({\"error\":\"" + code + "\"})"); + } + + @Test public void dnsFailureThenPendingThenSuccessKeepsPolling() throws Exception { + Time time = new Time(); + List attempts = new ArrayList<>(); + List networkRetries = new ArrayList<>(); + String token = DeviceCodePoller.await(() -> { + attempts.add(time.now); + if (attempts.size() == 1) throw new UnknownHostException("oauth.yandex.ru"); + if (attempts.size() == 2) throw oauthError("authorization_pending"); + return "access-token"; + }, 5000, 300000, time, time, networkRetries::add); + + assertEquals("access-token", token); + assertEquals(Arrays.asList(5000L, 15000L, 20000L), attempts); + assertEquals(Arrays.asList(true, false), networkRetries); + } + + @Test public void persistentDnsFailureExpiresWithoutRequestAfterDeadline() throws Exception { + Time time = new Time(); + List attempts = new ArrayList<>(); + UnknownHostException failure = new UnknownHostException("oauth.yandex.ru"); + try { + DeviceCodePoller.await(() -> { + attempts.add(time.now); + throw failure; + }, 5000, 16000, time, time, retry -> { }); + fail("Expected expiry"); + } catch (DeviceCodePoller.ExpiredException expected) { + assertSame(failure, expected.getCause()); + } + assertEquals(Arrays.asList(5000L, 15000L), attempts); + assertEquals(Arrays.asList(5000L, 10000L, 1000L), time.sleeps); + assertEquals(16000L, time.now); + } + + @Test public void slowDownPermanentlyIncreasesServerInterval() throws Exception { + Time time = new Time(); + List attempts = new ArrayList<>(); + DeviceCodePoller.await(() -> { + attempts.add(time.now); + if (attempts.size() == 1) throw oauthError("slow_down"); + if (attempts.size() == 2) throw oauthError("authorization_pending"); + return "token"; + }, 5000, 300000, time, time, retry -> { }); + assertEquals(Arrays.asList(5000L, 15000L, 25000L), attempts); + } + + @Test public void serverMinimumIsRespectedEvenAboveNetworkBackoffCap() throws Exception { + Time time = new Time(); + int[] calls = {0}; + DeviceCodePoller.await(() -> { + if (++calls[0] == 1) throw new SocketTimeoutException("timeout"); + return "token"; + }, 90000, 300000, time, time, retry -> { }); + assertEquals(Arrays.asList(90000L, 90000L), time.sleeps); + } + + @Test public void connectionFailuresBackOffWithoutBusyLooping() throws Exception { + Time time = new Time(); + int[] calls = {0}; + DeviceCodePoller.await(() -> { + if (++calls[0] <= 5) throw new SocketException("connection reset"); + return "token"; + }, 5000, 300000, time, time, retry -> { }); + assertEquals(Arrays.asList(5000L, 10000L, 20000L, 40000L, 60000L, 60000L), time.sleeps); + } + + @Test public void terminalOAuthAndResponseFailuresAreNotRetried() throws Exception { + List failures = Arrays.asList( + oauthError("access_denied"), oauthError("invalid_grant"), + new IOException("Invalid JSON"), new SSLHandshakeException("Bad certificate"), + new Net.ApiError(400, "{\"error\":\"access_denied\",\"error_description\":\"authorization_pending\"}")); + for (IOException failure : failures) { + Time time = new Time(); + int[] calls = {0}; + try { + DeviceCodePoller.await(() -> { + calls[0]++; + throw failure; + }, 5000, 300000, time, time, retry -> fail("Must not retry")); + fail("Expected terminal error"); + } catch (IOException expected) { + assertSame(failure, expected); + } + assertEquals(1, calls[0]); + } + } + + @Test public void expiredCodeMakesNoNetworkRequest() throws Exception { + Time time = new Time(); + time.now = 10000; + try { + DeviceCodePoller.await(() -> { + fail("Expired code must not be polled"); + return "token"; + }, 5000, 10000, time, time, retry -> { }); + fail("Expected expiry"); + } catch (DeviceCodePoller.ExpiredException expected) { + assertNull(expected.getCause()); + } + assertTrue(time.sleeps.isEmpty()); + } + + @Test public void interruptionDuringWaitCancelsBeforeRequest() throws Exception { + Time time = new Time(); + try { + DeviceCodePoller.await(() -> { + fail("Cancelled request must not start"); + return "token"; + }, 5000, 300000, time, millis -> { + throw new InterruptedException("cancelled"); + }, retry -> { }); + fail("Expected cancellation"); + } catch (InterruptedException expected) { + assertEquals("cancelled", expected.getMessage()); + } + } + + @Test public void interruptedResponseCannotReturnToken() throws Exception { + Time time = new Time(); + try { + DeviceCodePoller.await(() -> { + Thread.currentThread().interrupt(); + return "token"; + }, 5000, 300000, time, time, retry -> { }); + fail("Cancelled result must not be returned"); + } catch (InterruptedException expected) { + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } +} diff --git a/app/src/test/java/com/likefolder/app/YandexApiCdnTest.java b/app/src/test/java/com/likefolder/app/YandexApiCdnTest.java new file mode 100644 index 0000000..23fdca3 --- /dev/null +++ b/app/src/test/java/com/likefolder/app/YandexApiCdnTest.java @@ -0,0 +1,69 @@ +package com.likefolder.app; + +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +public final class YandexApiCdnTest { + private static final String HOST = "cdn.example.org"; + private static final String PATH = "/music/test-track.mp3"; + // Independently calculated from the synthetic path and salt with Python hashlib.md5. + private static final String SIGNED_PREFIX = + "https://cdn.example.org/get-mp3/803dcdbb83831a5cecfd09a5fde16261/"; + + private static String xml(String host, String path, String ts) { + return "" + host + "" + path + + "" + ts + "test-salt"; + } + + @Test public void hexadecimalTimestampProducesExpectedSignedUrl() throws Exception { + assertEquals(SIGNED_PREFIX + "1a02f27aee4" + PATH, + YandexApi.mp3UrlFromXml(xml(HOST, PATH, "1a02f27aee4"))); + } + + @Test public void digitOnlyTimestampRemainsSupported() throws Exception { + assertEquals(SIGNED_PREFIX + "1668329810" + PATH, + YandexApi.mp3UrlFromXml(xml(HOST, PATH, "1668329810"))); + } + + @Test public void timestampCaseAndLeadingZerosArePreserved() throws Exception { + for (String ts : new String[]{"0001A02F27AEE4", "0001a02F27aEe4"}) { + assertEquals(SIGNED_PREFIX + ts + PATH, + YandexApi.mp3UrlFromXml(xml(HOST, PATH, ts))); + } + } + + @Test public void invalidTimestampReportsFieldWithoutLeakingValue() { + for (String ts : new String[]{"1a02/private", "1a02?key=private", "1a02#private", + "1a02g", "0x1a02", "1a02 private"}) { + IOException error = assertThrows(IOException.class, + () -> YandexApi.mp3UrlFromXml(xml(HOST, PATH, ts))); + assertEquals("Неподдерживаемый ответ CDN: неверное поле ts", error.getMessage()); + } + } + + @Test public void invalidHostReportsFieldWithoutLeakingValue() { + IOException error = assertThrows(IOException.class, + () -> YandexApi.mp3UrlFromXml(xml("cdn.example.org/private", PATH, "1a02f"))); + assertEquals("Неподдерживаемый ответ CDN: неверное поле host", error.getMessage()); + } + + @Test public void relativePathIsRejectedWithoutLeakingValue() { + IOException error = assertThrows(IOException.class, + () -> YandexApi.mp3UrlFromXml(xml(HOST, "music/private-track.mp3", "1a02f"))); + assertEquals("Неподдерживаемый ответ CDN: неверное поле path", error.getMessage()); + } + + @Test public void missingRequiredFieldsAreReported() { + for (String field : new String[]{"host", "path", "ts", "s"}) { + String incomplete = xml(HOST, PATH, "1a02f") + .replaceFirst("<" + field + ">[^<]*", ""); + IOException error = assertThrows(IOException.class, + () -> YandexApi.mp3UrlFromXml(incomplete)); + assertEquals("Нет поля " + field + " в CDN-ответе", error.getMessage()); + } + } +}