Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add e2e test for iOS/Android #1516

Merged
merged 16 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 83 additions & 2 deletions flutter/example/integration_test/integration_test.dart
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
import 'dart:convert';

import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:sentry_flutter_example/main.dart';
import 'package:http/http.dart';

void main() {
const org = 'sentry-sdks';
const slug = 'sentry-flutter';
const authToken = String.fromEnvironment('SENTRY_AUTH_TOKEN');
const fakeDsn = 'https://abc@def.ingest.sentry.io/1234567';

TestWidgetsFlutterBinding.ensureInitialized();

setUp(() async {
await Sentry.close();
});

// Using fake DSN for testing purposes.
Future<void> setupSentryAndApp(WidgetTester tester) async {
Future<void> setupSentryAndApp(WidgetTester tester, {String? dsn}) async {
await setupSentry(() async {
await tester.pumpWidget(SentryScreenshotWidget(
child: DefaultAssetBundle(
bundle: SentryAssetBundle(enableStructuredDataTracing: true),
child: const MyApp(),
)));
await tester.pumpAndSettle();
}, 'https://abc@def.ingest.sentry.io/1234567');
}, dsn ?? fakeDsn, isIntegrationTest: true);
}

// Tests
Expand Down Expand Up @@ -124,4 +132,77 @@ void main() {
final transaction = Sentry.startTransactionWithContext(context);
await transaction.finish();
});

group('e2e', () {
var output = find.byKey(const Key('output'));
late Fixture fixture;

setUp(() {
fixture = Fixture();
});

testWidgets('captureException', (tester) async {
await setupSentryAndApp(tester, dsn: exampleDsn);

await tester.tap(find.text('captureException'));
await tester.pumpAndSettle();

final text = output.evaluate().single.widget as Text;
final id = text.data!;

final uri = Uri.parse(
'https://sentry.io/api/0/projects/$org/$slug/events/$id/',
);

final event = await fixture.poll(uri, authToken);
expect(event, isNotNull);
expect(fixture.validate(event!), isTrue);
});
});
}

class Fixture {
Future<Map<String, dynamic>?> poll(Uri url, String authToken) async {
final client = Client();

const maxRetries = 10;
const initialDelay = Duration(seconds: 2);
const factor = 2;

var retries = 0;
var delay = initialDelay;

while (retries < maxRetries) {
try {
final response = await client.get(
url,
headers: <String, String>{'Authorization': 'Bearer $authToken'},
);
if (response.statusCode == 200) {
return jsonDecode(utf8.decode(response.bodyBytes));
}
} catch (e) {
// Do nothing
} finally {
retries++;
await Future.delayed(delay);
delay *= factor;
}
}
return null;
}

bool validate(Map<String, dynamic> event) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we actually validate more properties in the event?
I know this is a copy of https://github.com/getsentry/sentry-dart/blob/main/e2e_test/bin/e2e_test.dart
Maybe we should improve that test as well.
The goal is that we assert every property that is static and not dependent on the host platform, so it wont fail in different devices, etc.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I check fro the same properties than getsentry/sentry-kotlin-multiplatform#78 now. Do we need more? If not, i will update the dart only test as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's start with the current approach and expand as we go.
Ideally, we'd check every property that is static, does not change depending on the device, etc.

final tags = event['tags'] as List<dynamic>;
final dist = tags.firstWhere((element) => element['key'] == 'dist');
if (dist['value'] != '1') {
return false;
}
final environment =
tags.firstWhere((element) => element['key'] == 'environment');
if (environment['value'] != 'integration') {
return false;
}
return true;
}
}
65 changes: 61 additions & 4 deletions flutter/example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
Expand All @@ -21,10 +22,11 @@ import 'package:sentry_dio/sentry_dio.dart';
import 'package:sentry_logging/sentry_logging.dart';

// ATTENTION: Change the DSN below with your own to see the events in Sentry. Get one at sentry.io
const String _exampleDsn =
const String exampleDsn =
'https://e85b375ffb9f43cf8bdf9787768149e0@o447951.ingest.sentry.io/5428562';

const _channel = MethodChannel('example.flutter.sentry.io');
var _isIntegrationTest = false;

Future<void> main() async {
await setupSentry(
Expand All @@ -38,12 +40,13 @@ Future<void> main() async {
),
),
),
_exampleDsn);
exampleDsn);
}

Future<void> setupSentry(AppRunner appRunner, String dsn) async {
Future<void> setupSentry(AppRunner appRunner, String dsn,
{bool isIntegrationTest = false}) async {
await SentryFlutter.init((options) {
options.dsn = _exampleDsn;
options.dsn = exampleDsn;
options.tracesSampleRate = 1.0;
options.reportPackages = false;
options.addInAppInclude('sentry_flutter_example');
Expand All @@ -63,6 +66,12 @@ Future<void> setupSentry(AppRunner appRunner, String dsn) async {

options.maxRequestBodySize = MaxRequestBodySize.always;
options.maxResponseBodySize = MaxResponseBodySize.always;

_isIntegrationTest = isIntegrationTest;
if (_isIntegrationTest) {
options.dist = '1';
options.environment = 'integration';
}
},
// Init your App.
appRunner: appRunner);
Expand Down Expand Up @@ -136,6 +145,7 @@ class MainScaffold extends StatelessWidget {
body: SingleChildScrollView(
child: Column(
children: [
if (_isIntegrationTest) const IntegrationTestWidget(),
const Center(child: Text('Trigger an action:\n')),
ElevatedButton(
onPressed: () => sqfliteTest(),
Expand Down Expand Up @@ -527,6 +537,53 @@ Future<void> asyncThrows() async {
throw StateError('async throws');
}

class IntegrationTestWidget extends StatefulWidget {
const IntegrationTestWidget({super.key});

@override
State<StatefulWidget> createState() {
return _IntegrationTestWidgetState();
}
}

class _IntegrationTestWidgetState extends State<IntegrationTestWidget> {
_IntegrationTestWidgetState();

var _output = "--";
var _isLoading = false;

@override
Widget build(BuildContext context) {
return Column(children: [
Text(
_output,
key: const Key('output'),
),
_isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: () async => await _captureException(),
child: const Text('captureException'),
)
]);
}

Future<void> _captureException() async {
setState(() {
_isLoading = true;
});
try {
throw Exception('captureException');
} catch (error, stackTrace) {
final id = await Sentry.captureException(error, stackTrace: stackTrace);
setState(() {
_output = id.toString();
_isLoading = false;
});
}
}
}

class CocoaExample extends StatelessWidget {
const CocoaExample({Key? key}) : super(key: key);

Expand Down
1 change: 1 addition & 0 deletions flutter/example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ dependencies:
path_provider: ^2.0.0
#sqflite_common_ffi: ^2.0.0
#sqflite_common_ffi_web: ^0.3.0
http: ^0.13.0
denrase marked this conversation as resolved.
Show resolved Hide resolved

dev_dependencies:
flutter_lints: ^2.0.0
Expand Down