chore: archive completed task files and add contract-related files

- Move 01_contract_mapping files to archive
- Add alt_api_result.dart contract implementation
- Add alt_api_result_test.dart
This commit is contained in:
toki 2026-06-02 10:15:26 +09:00
parent fc1b94bf5c
commit 259a86c2fa
6 changed files with 490 additions and 101 deletions

View file

@ -0,0 +1,150 @@
<!-- task=m-operator-client-api-core-integration/01_contract_mapping plan=0 tag=API -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> If implementation is blocked by a user-only decision, user-owned external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Evidence gaps that a follow-up agent can close by rerunning commands or collecting artifacts are normal follow-up issues, not user-review blockers by themselves.
> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## 개요
date=2026-06-02
task=m-operator-client-api-core-integration/01_contract_mapping, plan=0, tag=API
## Roadmap Targets
- Milestone: `agent-roadmap/phase/operator-surface/milestones/operator-client-api-core-integration.md`
- Task ids:
- `client-contracts`: generated/mapped contracts를 client core에서 사용할 수 있게 정리한다.
- Completion mode: check-on-pass
## 이 파일을 읽는 리뷰 에이전트에게
> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.
각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
## 구현 항목별 완료 여부
| 항목 | 완료 여부 |
|------|---------|
| [API-1] Client result/error mapping 추가 | [x] |
| [API-2] Response error extraction helper 추가 | [x] |
## 구현 체크리스트
- [x] `AltApiResult<T>`, `AltApiError`, `AltTransportState` 등 UI copy 없는 client core result 타입을 추가하고 `ErrorInfo` mapping test를 작성한다. 검증: `cd apps/client && flutter test test/contracts/alt_api_result_test.dart`
- [x] response별 `ErrorInfo` 추출 helper를 추가해 market/backtest response에서 공통으로 쓸 수 있게 한다. 검증: `cd apps/client && flutter test test/contracts/alt_api_result_test.dart`
- [x] `cd apps/client && flutter test`를 실행해 기존 parser/socket/widget 회귀를 확인한다.
- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
## 코드리뷰 전용 체크리스트
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_{review_lane}_GNN_N.log`로 아카이브한다.
- [x] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_M.log`로 아카이브한다.
- [x] PASS이면 `complete.log`를 작성하고 active task directory를 archive로 이동한다.
- [x] PASS이고 task group이 `m-<milestone-slug>`이면 완료 이벤트 메타데이터를 보고하고 roadmap은 직접 수정하지 않는다.
## 계획 대비 변경 사항
- PLAN과 CODE_REVIEW 체크리스트는 result 타입을 `AltTransportState`로 칭하지만, transport 실패는 별도 상태 객체가 아니라 `AltApiResult`의 한 variant + 안정 분류 enum이 적절하다고 판단해 `AltTransportFailure<T>` variant와 `AltTransportKind` enum으로 구현했다. 의미(transport 실패를 UI copy 없는 안정 상태로 보존)는 동일하다.
- API-2 helper는 PLAN 예시의 `ListInstrumentsResponse(:final error)` 패턴 대신 `Type() when response.hasError() => response.error` 형태로 작성했다. `error` field만 binding하면 `hasError()` 가드와 함께 쓸 때 미사용 binding lint가 걸릴 수 있어, type 매칭 + 가드 + getter 접근으로 통일했다.
- PLAN이 명시한 6개 외에 `error` field를 가진 나머지 response(`GetBacktestRunResponse`, `CompareBacktestRunsResponse`)도 helper와 테스트에 포함했다. 후속 backtest/market repository가 동일 helper를 빠짐없이 재사용하도록 하기 위함이며, 범위는 동일하게 client core result/error mapping 안에 머문다.
## 주요 설계 결정
- `AltApiResult<T>`는 `sealed class`로 두고 `AltApiSuccess` / `AltApiFailure` / `AltTransportFailure` 세 variant를 final 서브클래스로 노출했다. 후속 plan이 `switch`로 exhaustive하게 분기할 수 있고(테스트에서 exhaustive switch로 검증), named factory(`.success` / `.apiError` / `.transportFailure`)로 호출부 가독성을 유지한다.
- `AltApiError`는 generated `ErrorInfo`의 `code`/`message`만 보존하고 UI 문구는 담지 않는다. 표시 문구 결정은 presentation layer 책임으로 남겨, client domain rule의 "presentation은 state를 소비한다" 경계를 따른다.
- result/error 타입에 value equality(`==`/`hashCode`)를 구현해 후속 socket/market/backtest state controller가 안정 상태 비교(rebuild 억제, 테스트 단언)에 그대로 쓸 수 있게 했다.
- `altResponseError`는 unsupported type과 error 미설정 시 모두 `null`을 반환해 success path를 깨지 않는다(테스트로 검증). generated 파일은 손대지 않고 client core helper로만 매핑한다.
## 사용자 리뷰 요청
_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._
- 상태: 없음
- 사유 유형: 없음
- 결정 필요: 없음
- 차단 근거: 없음
- 실행한 검증/명령: 없음
- 자동 후속 불가 이유: 없음
- 재개 조건: 없음
## 리뷰어를 위한 체크포인트
- generated 파일을 손수 수정하지 않았는가
- typed `ErrorInfo`와 transport failure가 UI copy 없이 stable state로 남는가
- 후속 repository plan이 재사용할 수 있는 API인가
## 검증 결과
_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._
> API-1, API-2는 같은 테스트 파일(`test/contracts/alt_api_result_test.dart`)을 공유하므로 한 번의 실행으로 두 항목을 함께 검증한다. 보조로 `flutter analyze`를 신규 파일에 실행했다.
### API-1 중간 검증
```text
$ cd apps/client && flutter test test/contracts/alt_api_result_test.dart
00:00 +0: AltApiError mapping fromErrorInfo preserves stable code and message
00:00 +1: AltApiError mapping keeps empty fields when ErrorInfo is empty
00:00 +2: AltApiError mapping value equality is based on code and message
00:00 +3: AltApiResult variants success carries the decoded value
00:00 +4: AltApiResult variants apiError carries the mapped error
00:00 +5: AltApiResult variants transportFailure stays a stable state without ErrorInfo
00:00 +6: AltApiResult variants transportFailure supports a bare kind with no detail
00:00 +7: AltApiResult variants exhaustive switch covers every variant
00:00 +8: altResponseError extraction reads typed error from each supported response
00:00 +9: altResponseError extraction returns null when a supported response has no error set
00:00 +10: altResponseError extraction returns null for unsupported response types
00:00 +11: All tests passed!
```
### API-2 중간 검증
```text
$ cd apps/client && flutter test test/contracts/alt_api_result_test.dart
00:00 +11: All tests passed!
(API-1과 동일 실행. altResponseError extraction 그룹 3개 테스트가 8개 지원 response의 typed error 추출, error 미설정 시 null, unsupported type null을 덮는다.)
$ cd apps/client && flutter analyze lib/src/contracts/alt_api_result.dart test/contracts/alt_api_result_test.dart
Analyzing 2 items...
No issues found! (ran in 2.6s)
```
### 최종 검증
```text
$ cd apps/client && flutter test
00:01 +37: .../test/widget_test.dart: switches ALT workbench center content from the right rail
00:01 +38: All tests passed!
(신규 11개 포함 전체 38개 통과, exit code 0.)
```
## 코드리뷰 결과
- 종합 판정: PASS
- 차원별 평가:
- correctness: Pass
- completeness: Pass
- test coverage: Pass
- API contract: Pass
- code quality: Pass
- plan deviation: Pass
- verification trust: Pass
- 발견된 문제: 없음
- 다음 단계: PASS이므로 active plan/review를 log로 아카이브하고 `complete.log` 작성 후 task directory를 archive로 이동한다.
### 리뷰 근거
- `apps/client/lib/src/contracts/alt_api_result.dart`가 `AltApiResult<T>`, `AltApiError`, `AltTransportKind`, `AltTransportFailure<T>`를 UI copy 없이 stable client core state로 추가했고, generated protobuf 파일은 수정하지 않았다.
- `altResponseError`는 market/backtest response의 모든 현재 `ErrorInfo error` field 보유 response를 `hasError()`로 가드해 추출하며, unsupported/success path는 `null`로 유지한다.
- `apps/client/test/contracts/alt_api_result_test.dart`가 error mapping, result variant, exhaustive switch, supported response error extraction, unset error, unsupported type을 덮는다.
- 로컬 재검증:
- `cd apps/client && flutter test test/contracts/alt_api_result_test.dart` - PASS; 11 tests passed.
- `cd apps/client && flutter analyze lib/src/contracts/alt_api_result.dart test/contracts/alt_api_result_test.dart` - PASS; No issues found.
- `cd apps/client && flutter test` - PASS; 38 tests passed.

View file

@ -0,0 +1,42 @@
# Complete - m-operator-client-api-core-integration/01_contract_mapping
## 완료 일시
2026-06-02
## 요약
Client contract result/error mapping foundation completed in 1 review loop with final verdict PASS.
## 루프 이력
| Plan | Review | Verdict | 메모 |
|------|--------|---------|------|
| `plan_cloud_G06_0.log` | `code_review_cloud_G06_0.log` | PASS | `AltApiResult<T>`, `AltApiError`, transport failure kind, and shared response error extraction helper were implemented and verified. |
## 구현/정리 내용
- Added UI-copy-free client core result/error types in `apps/client/lib/src/contracts/alt_api_result.dart`.
- Added `altResponseError` to extract populated `ErrorInfo` from supported market/backtest responses without touching generated protobuf output.
- Added focused Flutter tests for error mapping, result variants, exhaustive switching, supported response extraction, unset errors, and unsupported types.
## 최종 검증
- `cd apps/client && flutter test test/contracts/alt_api_result_test.dart` - PASS; 11 tests passed.
- `cd apps/client && flutter analyze lib/src/contracts/alt_api_result.dart test/contracts/alt_api_result_test.dart` - PASS; No issues found.
- `cd apps/client && flutter test` - PASS; 38 tests passed.
## Roadmap Completion
- Milestone: `agent-roadmap/phase/operator-surface/milestones/operator-client-api-core-integration.md`
- Completed task ids:
- `client-contracts`: PASS; evidence=`plan_cloud_G06_0.log`, `code_review_cloud_G06_0.log`; verification=`cd apps/client && flutter test test/contracts/alt_api_result_test.dart`, `cd apps/client && flutter analyze lib/src/contracts/alt_api_result.dart test/contracts/alt_api_result_test.dart`, `cd apps/client && flutter test`
- Not completed task ids: 없음
## 잔여 Nit
- 없음
## 후속 작업
- 없음

View file

@ -1,101 +0,0 @@
<!-- task=m-operator-client-api-core-integration/01_contract_mapping plan=0 tag=API -->
# Code Review Reference - API
> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.**
> The task is NOT complete until every implementation-owned section below is filled in.
> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving.
> Fill implementation-owned sections, then stop with active files in place and report ready for review.
> If implementation is blocked by a user-only decision, user-owned external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Evidence gaps that a follow-up agent can close by rerunning commands or collecting artifacts are normal follow-up issues, not user-review blockers by themselves.
> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume.
> Follow the ownership table at the bottom of this file for which sections you own.
## 개요
date=2026-06-02
task=m-operator-client-api-core-integration/01_contract_mapping, plan=0, tag=API
## Roadmap Targets
- Milestone: `agent-roadmap/phase/operator-surface/milestones/operator-client-api-core-integration.md`
- Task ids:
- `client-contracts`: generated/mapped contracts를 client core에서 사용할 수 있게 정리한다.
- Completion mode: check-on-pass
## 이 파일을 읽는 리뷰 에이전트에게
> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.
각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
## 구현 항목별 완료 여부
| 항목 | 완료 여부 |
|------|---------|
| [API-1] Client result/error mapping 추가 | [ ] |
| [API-2] Response error extraction helper 추가 | [ ] |
## 구현 체크리스트
- [ ] `AltApiResult<T>`, `AltApiError`, `AltTransportState` 등 UI copy 없는 client core result 타입을 추가하고 `ErrorInfo` mapping test를 작성한다. 검증: `cd apps/client && flutter test test/contracts/alt_api_result_test.dart`
- [ ] response별 `ErrorInfo` 추출 helper를 추가해 market/backtest response에서 공통으로 쓸 수 있게 한다. 검증: `cd apps/client && flutter test test/contracts/alt_api_result_test.dart`
- [ ] `cd apps/client && flutter test`를 실행해 기존 parser/socket/widget 회귀를 확인한다.
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
## 코드리뷰 전용 체크리스트
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
- [ ] `코드리뷰 결과``PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
- [ ] active `CODE_REVIEW-*-G??.md``code_review_{review_lane}_GNN_N.log`로 아카이브한다.
- [ ] active `PLAN-*-G??.md``plan_{build_lane}_GNN_M.log`로 아카이브한다.
- [ ] PASS이면 `complete.log`를 작성하고 active task directory를 archive로 이동한다.
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 완료 이벤트 메타데이터를 보고하고 roadmap은 직접 수정하지 않는다.
## 계획 대비 변경 사항
_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._
## 주요 설계 결정
_구현 에이전트가 주요 설계 결정 사항을 기록한다._
## 사용자 리뷰 요청
_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._
- 상태: 없음
- 사유 유형: 없음
- 결정 필요: 없음
- 차단 근거: 없음
- 실행한 검증/명령: 없음
- 자동 후속 불가 이유: 없음
- 재개 조건: 없음
## 리뷰어를 위한 체크포인트
- generated 파일을 손수 수정하지 않았는가
- typed `ErrorInfo`와 transport failure가 UI copy 없이 stable state로 남는가
- 후속 repository plan이 재사용할 수 있는 API인가
## 검증 결과
_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._
### API-1 중간 검증
```text
$ cd apps/client && flutter test test/contracts/alt_api_result_test.dart
(output)
```
### API-2 중간 검증
```text
$ cd apps/client && flutter test test/contracts/alt_api_result_test.dart
(output)
```
### 최종 검증
```text
$ cd apps/client && flutter test
(output)
```

View file

@ -0,0 +1,160 @@
import 'package:alt_client/src/generated/alt/v1/backtest.pb.dart';
import 'package:alt_client/src/generated/alt/v1/common.pb.dart';
import 'package:alt_client/src/generated/alt/v1/market.pb.dart';
/// Transport-level failure kind that is independent of any ALT [ErrorInfo].
///
/// socket/market/backtest repository가 transport
/// client core에 . UI enum만 .
enum AltTransportKind {
/// .
timeout,
/// .
disconnected,
/// payload를 message로 .
decodeFailure,
/// .
unexpectedResponse,
/// transport .
unknown,
}
/// Stable, UI-copy-free client core error mapped from an ALT [ErrorInfo].
///
/// `code`/`message` server가 ,
/// presentation layer에 .
final class AltApiError {
const AltApiError({required this.code, required this.message});
/// Maps a generated [ErrorInfo] payload into a stable client core error.
factory AltApiError.fromErrorInfo(ErrorInfo info) =>
AltApiError(code: info.code, message: info.message);
/// Stable error code reported by the ALT API.
final String code;
/// Stable, non-localized message reported by the ALT API.
final String message;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AltApiError &&
runtimeType == other.runtimeType &&
code == other.code &&
message == other.message;
@override
int get hashCode => Object.hash(code, message);
@override
String toString() => 'AltApiError(code: $code, message: $message)';
}
/// Common result envelope that ALT client repositories return for an API call.
///
/// success payload, mapped [AltApiError], transport failure를
/// socket state / market repository / backtest repository가 .
sealed class AltApiResult<T> {
const AltApiResult();
/// Successful response carrying the decoded [value].
const factory AltApiResult.success(T value) = AltApiSuccess<T>;
/// Response that decoded but carried an ALT [AltApiError].
const factory AltApiResult.apiError(AltApiError error) = AltApiFailure<T>;
/// Transport-level failure where no ALT [ErrorInfo] is available.
const factory AltApiResult.transportFailure(
AltTransportKind kind, {
String? detail,
}) = AltTransportFailure<T>;
}
/// Successful [AltApiResult] holding the decoded value.
final class AltApiSuccess<T> extends AltApiResult<T> {
const AltApiSuccess(this.value);
final T value;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AltApiSuccess<T> &&
runtimeType == other.runtimeType &&
value == other.value;
@override
int get hashCode => Object.hash(runtimeType, value);
@override
String toString() => 'AltApiSuccess<$T>($value)';
}
/// [AltApiResult] that decoded a response carrying an ALT [AltApiError].
final class AltApiFailure<T> extends AltApiResult<T> {
const AltApiFailure(this.error);
final AltApiError error;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AltApiFailure<T> &&
runtimeType == other.runtimeType &&
error == other.error;
@override
int get hashCode => Object.hash(runtimeType, error);
@override
String toString() => 'AltApiFailure<$T>($error)';
}
/// [AltApiResult] for transport-level failures with no ALT [ErrorInfo].
final class AltTransportFailure<T> extends AltApiResult<T> {
const AltTransportFailure(this.kind, {this.detail});
/// Stable transport failure classification.
final AltTransportKind kind;
/// Optional non-localized diagnostic detail (not for direct UI display).
final String? detail;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AltTransportFailure<T> &&
runtimeType == other.runtimeType &&
kind == other.kind &&
detail == other.detail;
@override
int get hashCode => Object.hash(runtimeType, kind, detail);
@override
String toString() => 'AltTransportFailure<$T>(kind: $kind, detail: $detail)';
}
/// Extracts a populated [ErrorInfo] from any supported ALT response message.
///
/// market/backtest response가 `error` field를 , client
/// repository가 success/error . error가
/// type이면 `null` success path를 .
ErrorInfo? altResponseError(Object response) {
return switch (response) {
ListInstrumentsResponse() when response.hasError() => response.error,
ListBarsResponse() when response.hasError() => response.error,
StartBacktestResponse() when response.hasError() => response.error,
GetBacktestRunResponse() when response.hasError() => response.error,
GetBacktestResultResponse() when response.hasError() => response.error,
ListBacktestRunsResponse() when response.hasError() => response.error,
GetBacktestRunDetailResponse() when response.hasError() => response.error,
CompareBacktestRunsResponse() when response.hasError() => response.error,
_ => null,
};
}

View file

@ -0,0 +1,138 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:alt_client/src/contracts/alt_api_result.dart';
import 'package:alt_client/src/generated/alt/v1/backtest.pb.dart';
import 'package:alt_client/src/generated/alt/v1/common.pb.dart';
import 'package:alt_client/src/generated/alt/v1/market.pb.dart';
void main() {
group('AltApiError mapping', () {
test('fromErrorInfo preserves stable code and message', () {
final info = ErrorInfo(code: 'NOT_FOUND', message: 'instrument missing');
final error = AltApiError.fromErrorInfo(info);
expect(error.code, equals('NOT_FOUND'));
expect(error.message, equals('instrument missing'));
});
test('keeps empty fields when ErrorInfo is empty', () {
final error = AltApiError.fromErrorInfo(ErrorInfo());
expect(error.code, isEmpty);
expect(error.message, isEmpty);
});
test('value equality is based on code and message', () {
final a = AltApiError.fromErrorInfo(
ErrorInfo(code: 'E1', message: 'm'),
);
final b = const AltApiError(code: 'E1', message: 'm');
expect(a, equals(b));
expect(a.hashCode, equals(b.hashCode));
});
});
group('AltApiResult variants', () {
test('success carries the decoded value', () {
const result = AltApiResult<int>.success(42);
expect(result, isA<AltApiSuccess<int>>());
expect((result as AltApiSuccess<int>).value, equals(42));
});
test('apiError carries the mapped error', () {
final error = AltApiError.fromErrorInfo(
ErrorInfo(code: 'BAD', message: 'rejected'),
);
final result = AltApiResult<int>.apiError(error);
expect(result, isA<AltApiFailure<int>>());
expect((result as AltApiFailure<int>).error, equals(error));
});
test('transportFailure stays a stable state without ErrorInfo', () {
const result = AltApiResult<int>.transportFailure(
AltTransportKind.timeout,
detail: 'no response within 5s',
);
expect(result, isA<AltTransportFailure<int>>());
final failure = result as AltTransportFailure<int>;
expect(failure.kind, equals(AltTransportKind.timeout));
expect(failure.detail, equals('no response within 5s'));
});
test('transportFailure supports a bare kind with no detail', () {
const result =
AltApiResult<int>.transportFailure(AltTransportKind.disconnected);
final failure = result as AltTransportFailure<int>;
expect(failure.kind, equals(AltTransportKind.disconnected));
expect(failure.detail, isNull);
});
test('exhaustive switch covers every variant', () {
String describe(AltApiResult<int> result) {
return switch (result) {
AltApiSuccess<int>() => 'success',
AltApiFailure<int>() => 'apiError',
AltTransportFailure<int>() => 'transport',
};
}
expect(describe(const AltApiResult<int>.success(1)), equals('success'));
expect(
describe(
const AltApiResult<int>.apiError(
AltApiError(code: 'E', message: 'm'),
),
),
equals('apiError'),
);
expect(
describe(
const AltApiResult<int>.transportFailure(AltTransportKind.unknown),
),
equals('transport'),
);
});
});
group('altResponseError extraction', () {
test('reads typed error from each supported response', () {
final error = ErrorInfo(code: 'X', message: 'boom');
final responses = <Object>[
ListInstrumentsResponse(error: error),
ListBarsResponse(error: error),
StartBacktestResponse(error: error),
GetBacktestRunResponse(error: error),
GetBacktestResultResponse(error: error),
ListBacktestRunsResponse(error: error),
GetBacktestRunDetailResponse(error: error),
CompareBacktestRunsResponse(error: error),
];
for (final response in responses) {
final extracted = altResponseError(response);
expect(extracted, isNotNull, reason: '${response.runtimeType}');
expect(extracted!.code, equals('X'));
expect(extracted.message, equals('boom'));
}
});
test('returns null when a supported response has no error set', () {
expect(altResponseError(ListInstrumentsResponse()), isNull);
expect(altResponseError(ListBarsResponse()), isNull);
expect(altResponseError(GetBacktestRunDetailResponse()), isNull);
});
test('returns null for unsupported response types', () {
expect(altResponseError(HelloResponse()), isNull);
expect(altResponseError(ListInstrumentsRequest()), isNull);
expect(altResponseError('not a message'), isNull);
});
});
}