// Copyright (c) 2023, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Verify that debugger can stop on an unhandled exception thrown from async
// function. Regression test for https://dartbug.com/38697.

import 'package:test/test.dart';
import 'package:vm_service/vm_service.dart';

import 'common/service_test_common.dart';
import 'common/test_helper.dart';

// AUTOGENERATED START
//
// Update these constants by running:
//
// dart pkg/vm_service/test/update_line_numbers.dart pkg/vm_service/test/pause_on_unhandled_async_exceptions3_test.dart
//
const LINE_A = 26;
const LINE_B = 31;
const LINE_C = 34;
// AUTOGENERATED END

Future<Never> throwException() async {
  throw 'exception'; // LINE_A
}

Future<void> testeeMain() async {
  try {
    await throwException(); // LINE_B
  } finally {
    try {
      await throwException(); // LINE_C
    } finally {}
  }
}

final tests = <IsolateTest>[
  hasStoppedWithUnhandledException,
  stoppedAtLine(LINE_A),
  (VmService service, IsolateRef isolateRef) async {
    final isolateId = isolateRef.id!;
    final stack = await service.getStack(isolateId);
    expect(stack.frames, isNotEmpty);
    expect(stack.frames![0].function!.name, 'throwException');
    expect(stack.frames![0].location!.line, LINE_A);
  },
  resumeIsolate,
  hasStoppedWithUnhandledException,
  (VmService service, IsolateRef isolateRef) async {
    final isolateId = isolateRef.id!;
    final stack = await service.getStack(isolateId);
    expect(stack.frames, isNotEmpty);
    // await in testeeMain
    expect(stack.frames![0].location!.line, LINE_B);
  },
  resumeIsolate,
  hasStoppedWithUnhandledException,
  stoppedAtLine(LINE_A),
  resumeIsolate,
  hasStoppedWithUnhandledException,
  (VmService service, IsolateRef isolateRef) async {
    final isolateId = isolateRef.id!;
    final stack = await service.getStack(isolateId);
    expect(stack.frames, isNotEmpty);
    expect(stack.frames![0].location!.line, LINE_C);
  }
];

void main([args = const <String>[]]) => runIsolateTests(
      args,
      tests,
      'pause_on_unhandled_async_exceptions3_test.dart',
      pauseOnUnhandledExceptions: true,
      testeeConcurrent: testeeMain,
    );
