utils/github_device_auth/test/device_auth_poll_test.dart
Krzysztof kuhy Rudnicki 200432a2b4 dart: split ten oversized test files by group
firebase_auth_rest_test.dart  525 -> 153 + _google 158 + _tokens 206 + _uid 141
  sync_revisions_test.dart      451 -> 223 + _peers 228 + _backends 158
                                       + _order 165 + _persistence 215
  sync_settings_screen_test     457 -> 207 + _backup 143 + _google 145
  mirror_store_test.dart        452 -> 209 + _reads 172 + _fallback 196 + _revisions 244
  firebase_client_test.dart     374 -> 198 + _writes 227
  firebase_config_test.dart     360 -> 138 + _client 148 + _client_google 164
  device_auth_test.dart         307 -> 128 + _poll 201
  github_client_test.dart       291 -> 143 + _writes 201
  sync_test.dart                269 -> 160 + _skips 175

Two traps this hit, both invisible to a line count:

  - _FakePersistence is declared *after* main(), so a naive cut at the last
    brace dropped it; sync_revisions_persistence_test.dart failed to load
    until it was carried across. Audited every other split file for trailing
    top-level declarations — this was the only one.
  - Copying the preamble into each sibling left helpers the sibling never
    uses. `dart analyze` flagged 12; all removed rather than left as dead
    code, and the analyzer is now clean.

crdt_sync_dart 280 passed, sync_settings_ui 29 passed, github_device_auth
analyze clean — all matching a clean HEAD worktree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CFSGeWxHPY5rHUGrPqhcmG
2026-08-22 14:54:35 +02:00

205 lines
5.7 KiB
Dart

import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:github_device_auth/github_device_auth.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
/// Never actually waits: the poll loop's pacing is injected so a test that
/// exercises `slow_down` does not take 15 real seconds.
Future<void> noDelay(Duration _) async {}
GitHubDeviceAuth authWith(
MockClient client, {
String scope = 'repo',
}) => GitHubDeviceAuth(
clientId: 'cid',
scope: scope,
httpClient: client,
delay: noDelay,
);
void main() {
group('pollForToken', () {
const device = DeviceCodeResponse(
deviceCode: 'dc',
userCode: 'UC',
verificationUri: 'u',
interval: 1,
expiresIn: 60,
);
test('returns the token once the user authorizes', () async {
var calls = 0;
final auth = authWith(
MockClient((_) async {
calls += 1;
// First poll pending, second succeeds -- the normal path.
return http.Response(
calls == 1
? jsonEncode({'error': 'authorization_pending'})
: jsonEncode({'access_token': 'tok'}),
200,
);
}),
);
expect(await auth.pollForToken(device), 'tok');
expect(calls, 2);
});
test('obeys slow_down by taking GitHub s new interval', () async {
var calls = 0;
final auth = authWith(
MockClient((_) async {
calls += 1;
return http.Response(
calls == 1
? jsonEncode({'error': 'slow_down', 'interval': 30})
: jsonEncode({'access_token': 'tok'}),
200,
);
}),
);
expect(await auth.pollForToken(device), 'tok');
});
test('slow_down without an interval still backs off', () async {
var calls = 0;
final auth = authWith(
MockClient((_) async {
calls += 1;
return http.Response(
calls == 1
? jsonEncode({'error': 'slow_down'})
: jsonEncode({'access_token': 'tok'}),
200,
);
}),
);
expect(await auth.pollForToken(device), 'tok');
});
test('throws on a terminal error', () async {
final auth = authWith(
MockClient(
(_) async => http.Response(
jsonEncode({
'error': 'access_denied',
'error_description': 'user said no',
}),
200,
),
),
);
await expectLater(
auth.pollForToken(device),
throwsA(
isA<DeviceAuthException>()
.having((e) => e.code, 'code', 'access_denied')
.having((e) => e.message, 'message', 'user said no'),
),
);
});
test('falls back to the code when no description is given', () async {
final auth = authWith(
MockClient(
(_) async => http.Response(jsonEncode({'error': 'expired'}), 200),
),
);
await expectLater(
auth.pollForToken(device),
throwsA(
isA<DeviceAuthException>().having((e) => e.message, 'msg', 'expired'),
),
);
});
test('throws on a response with neither a token nor an error', () async {
final auth = authWith(
MockClient((_) async => http.Response(jsonEncode({'x': 1}), 200)),
);
await expectLater(
auth.pollForToken(device),
throwsA(
isA<DeviceAuthException>().having((e) => e.code, 'code', 'unknown'),
),
);
});
test('retries a transient network failure instead of giving up', () async {
// GitHub can close the connection at the moment the user authorizes,
// and a phone can drop its network mid-poll. Losing an approved grant
// to a socket blip is the bug this retry exists to prevent.
var calls = 0;
final auth = authWith(
MockClient((_) async {
calls += 1;
if (calls == 1) {
throw http.ClientException('Connection closed before full header');
}
return http.Response(jsonEncode({'access_token': 'tok'}), 200);
}),
);
expect(await auth.pollForToken(device), 'tok');
expect(calls, 2);
});
test('gives up once the device code has expired', () async {
const expired = DeviceCodeResponse(
deviceCode: 'dc',
userCode: 'UC',
verificationUri: 'u',
interval: 1,
// Already in the past, so the loop body never runs.
expiresIn: -1,
);
final auth = authWith(MockClient((_) async => http.Response('{}', 200)));
await expectLater(
auth.pollForToken(expired),
throwsA(
isA<DeviceAuthException>().having(
(e) => e.code,
'code',
'expired_token',
),
),
);
});
});
test('close() is safe to call', () {
authWith(MockClient((_) async => http.Response('{}', 200))).close();
});
test('constructs with a real http client and default scope', () {
final auth = GitHubDeviceAuth(clientId: 'cid')..close();
expect(auth.scope, 'repo');
});
test('polls the overridden token endpoint', () async {
late Uri seen;
final auth = GitHubDeviceAuth(
clientId: 'cid',
tokenUrl: 'http://127.0.0.1:9/gh/auth/device/poll',
httpClient: MockClient((req) async {
seen = req.url;
return http.Response(jsonEncode({'access_token': 'tok'}), 200);
}),
delay: noDelay,
);
await auth.pollForToken(
const DeviceCodeResponse(
deviceCode: 'dc',
userCode: 'UC',
verificationUri: 'u',
interval: 1,
expiresIn: 60,
),
);
expect(seen.toString(), 'http://127.0.0.1:9/gh/auth/device/poll');
});
}