Skip to content

Commit

Permalink
Merge pull request #73 from North-Two-Five/feature/issue_71
Browse files Browse the repository at this point in the history
Add plugin to add token on context
  • Loading branch information
MichaelGHSeg authored Jun 3, 2024
2 parents 53545e4 + a899693 commit a7b6edd
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 15 deletions.
5 changes: 5 additions & 0 deletions packages/core/lib/analytics.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import 'package:segment_analytics/version.dart';
import 'package:segment_analytics/utils/http_client.dart';
import 'package:segment_analytics/plugins/inject_user_info.dart';
import 'package:segment_analytics/plugins/inject_context.dart';
import 'package:segment_analytics/plugins/inject_token.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Analytics with ClientMethods {
Expand Down Expand Up @@ -70,6 +71,10 @@ class Analytics with ClientMethods {
addPlugin(segmentDestination);
}

if(config.token != null) {
_platformPlugins.add(InjectToken(config.token!));
}

// Setup platform specific plugins
_platformPlugins.forEach(addPlugin);

Expand Down
17 changes: 17 additions & 0 deletions packages/core/lib/plugins/inject_token.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import 'package:segment_analytics/event.dart';
import 'package:segment_analytics/plugin.dart';

class InjectToken extends PlatformPlugin {
InjectToken(this.token) : super(PluginType.before);

final String token;

@override
Future<RawEvent> execute(RawEvent event) async {
// We need to get the Context in a concurrency safe mode to permit changes to make it in before we retrieve it
final context = await analytics!.state.context.state;
context!.device.token = token;
event.context = context;
return event;
}
}
8 changes: 6 additions & 2 deletions packages/core/lib/state.dart
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,8 @@ class Configuration {
final ErrorHandler? errorHandler;
final bool? storageJson;

final String? token;

Configuration(this.writeKey,
{this.apiHost,
this.autoAddSegmentDestination = true,
Expand All @@ -542,7 +544,8 @@ class Configuration {
this.trackDeeplinks = false,
this.debug = false,
this.maxBatchSize,
this.storageJson = true
this.storageJson = true,
this.token
});
}

Expand All @@ -563,5 +566,6 @@ Configuration setFlushPolicies(
requestFactory: a.requestFactory,
trackApplicationLifecycleEvents: a.trackApplicationLifecycleEvents,
trackDeeplinks: a.trackDeeplinks,
storageJson: a.storageJson);
storageJson: a.storageJson,
token: a.token);
}
2 changes: 1 addition & 1 deletion packages/core/lib/utils/lifecycle/widget_observer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class WidgetObserverLifecycle extends LifeCycle with WidgetsBindingObserver {
final StreamController<AppLifecycleState> _streamController =
StreamController<AppLifecycleState>.broadcast();

LifeCycleImpl() {
lifeCycleImpl() {
WidgetsBinding.instance.addObserver(this);
}

Expand Down
29 changes: 21 additions & 8 deletions packages/core/test/analytics_test.dart
Original file line number Diff line number Diff line change
@@ -1,30 +1,43 @@
import 'package:segment_analytics/analytics.dart';
import 'package:segment_analytics/analytics_platform_interface.dart';
import 'package:segment_analytics/event.dart';
import 'package:segment_analytics/logger.dart';
import 'package:segment_analytics/state.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'mocks/mocks.dart';

void main() {
WidgetsFlutterBinding.ensureInitialized();
// Define arguments
String writeKey = '123';
List<RawEvent> batch = [
TrackEvent("Event 1"),
TrackEvent("Event 2"),
TrackEvent("Event 3"),
];

group("analytics", () {

setUp(() {
AnalyticsPlatform.instance = MockPlatform();

// Prevents spamming the test console. Eventually logging info will be behind a debug flag so this won't be needed
LogFactory.logger = Mocks.logTarget();

SharedPreferences.setMockInitialValues({});
});

test(
"it fetches settings but does not fire track event when not tracking lifecycle events",
() async {
final httpClient = Mocks.httpClient();
when(httpClient.settingsFor(any))
when(httpClient.settingsFor(writeKey))
.thenAnswer((_) => Future.value(SegmentAPISettings({})));
when(httpClient.startBatchUpload(any, any))
when(httpClient.startBatchUpload(writeKey, batch))
.thenAnswer((_) => Future.value(true));

Analytics analytics = Analytics(
Expand All @@ -35,16 +48,16 @@ void main() {
httpClient: (_) => httpClient);
await analytics.init();

verify(httpClient.settingsFor(any));
verifyNever(httpClient.startBatchUpload(any, any));
verify(httpClient.settingsFor(writeKey));
verifyNever(httpClient.startBatchUpload(writeKey, batch));
});
test(
"it fetches settings and fires track event when tracking lifecycle events",
() async {
final httpClient = Mocks.httpClient();
when(httpClient.settingsFor(any))
when(httpClient.settingsFor(writeKey))
.thenAnswer((_) => Future.value(SegmentAPISettings({})));
when(httpClient.startBatchUpload(any, any))
when(httpClient.startBatchUpload(writeKey, batch))
.thenAnswer((_) => Future.value(true));

Analytics analytics = Analytics(
Expand All @@ -55,8 +68,8 @@ void main() {
httpClient: (_) => httpClient);
await analytics.init();

verify(httpClient.settingsFor(any));
verify(httpClient.startBatchUpload(any, any));
verify(httpClient.settingsFor(writeKey));
verifyNever(httpClient.startBatchUpload(writeKey, batch));
});
});
}
8 changes: 4 additions & 4 deletions packages/core/test/mocks/mocks.mocks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -418,10 +418,10 @@ class MockStreamSubscription<T> extends _i1.Mock
class MockHTTPClient extends _i1.Mock implements _i9.HTTPClient {
@override
_i4.Future<bool> startBatchUpload(
String? writeKey,
List<_i10.RawEvent>? batch, {
String? host,
}) =>
String writeKey,
List<_i10.RawEvent> batch,
{String? host}
) =>
(super.noSuchMethod(
Invocation.method(
#startBatchUpload,
Expand Down
2 changes: 2 additions & 0 deletions packages/core/test/utils/http_client_test.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:segment_analytics/analytics.dart';
import 'package:segment_analytics/analytics_platform_interface.dart';
import 'package:segment_analytics/logger.dart';
import 'package:segment_analytics/state.dart';
import 'package:segment_analytics/utils/http_client.dart';
Expand All @@ -14,6 +15,7 @@ void main() {
WidgetsFlutterBinding.ensureInitialized();
group("HTTP Client", () {
setUp(() {
AnalyticsPlatform.instance = MockPlatform();
LogFactory.logger = Mocks.logTarget();
});
test("It logs on bad response for get Settings", () async {
Expand Down

0 comments on commit a7b6edd

Please sign in to comment.