Files
buzz/mobile/test/shared/push/push_bridge_test.dart
Tom Brow 8f3f4e266a test(mobile): run push tests without a gateway dart-define (#9423)
A plain `cd mobile && flutter test` failed 11 push and notification
tests on a clean checkout of main, while CI passed. Agents running the
full suite kept reporting them as "pre-existing, also fails on main",
which hides real regressions in the same files.

### Root cause

Push is gated on the compile-time `BUZZ_PUSH_GATEWAY_URL` define
(`Env.pushGatewayConfigured`, since [#7261 configurable
gateway](https://github.com/block/buzz/pull/7261) made the gateway
optional). Without it the app is a push-less build:
`readBuzzPushEndpointGrants()` returns no grants and
`buzzPushLifecycleEnabled()` is false. CI's mobile shards, `just
mobile-test` and the lefthook pre-push lane (which runs `just
mobile-test`) all pass
`--dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example`; a bare
`flutter test` passes nothing. Each of the 11 was checked against that:

- `notification_toggle_test` (5 cases) and
`push_lease_revocation_outbox_test` "hosted relay assertion": no
endpoint grants without a gateway (`Bad state: No element` at the grant
lookup, `No endpoint grant exists for push lease tombstone`).
- `push_bridge_test` "reads and exposes persisted endpoint grants" and
"debug enrollment carries the configured relay and gateway URLs": the
bridge returns `[]` before calling native (`Expected: an object with
length of <1>, Actual: []`).
- `push_bootstrap_test` "default push requires relay capability" and
"new community starts registration": the lifecycle is disabled, so
registration never starts (`Expected <1>, Actual <0>`).
- `push_bridge_test` "development push gateway matches the compiled
configuration": a stale test. It expected a `https://push.buzz.xyz`
default that [#7261 configurable
gateway](https://github.com/block/buzz/pull/7261) removed from the app;
under CI's define both sides equal `push.example`, so it could never
fail there.

The same files pass on the same Mac with the define, so nothing is
environmental. The `Unexpected native call
takePendingNotificationResponse` log is unrelated noise: the toggle
test's native mock didn't answer that call, which logs (and is caught)
in CI too.

### Fix

Tests get the gateway from a test hook instead of the define.
`Env.pushGatewayUrl` becomes a getter over the compiled value with a
`@visibleForTesting` `debugPushGatewayUrlOverride` (the same pattern as
`debugUriStreamOverride`), and `test/flutter_test_config.dart` sets it
for every test file. `push_unconfigured_build_test` sets it to `''`, so
it runs in the main suite instead of being skipped there and run
separately. CI, the Justfile, `scripts/flake-check.mjs` and the
AGENTS/README check commands drop the define, so CI, `just mobile-test`,
pre-push and a bare `flutter test` run the same thing.

I chose this over documenting a canonical command because the define
can't be made automatic: `flutter test` has no config file for defines,
so any doc fix still leaves the obvious command red. A test hook makes
every invocation agree.

The stale test is replaced by one in the push-less file that binds the
production read: with the override cleared, `Env.pushGatewayUrl` must
equal the compiled `BUZZ_PUSH_GATEWAY_URL`. Now that CI compiles without
the define, it fails if the app regains a built-in gateway default,
which the old test never could. The toggle test's mock answers
`takePendingNotificationResponse` with no pending response.

What gets better: one test mode everywhere, and the push-less tests run
in every run. Nothing gets worse: production reads the same compiled
value (the override is never set outside tests, and an `aot-snapshot`
probe shows AOT still folds the getter to the compiled constant and
drops push-only code when the define is absent), and every test still
runs in the push-capable mode CI used before.

### Validation

- On a fresh origin/main worktree with the Hermit toolchain, a bare
`flutter test` failed exactly these 11; the same files passed on the
same machine with the define.
- After the fix, the pre-push `just mobile-check` and `just mobile-test`
(now a bare `flutter test` plus the recipe and secp256k1 checks) pass,
with the push-less tests running instead of skipped.
`scripts/flake-check.test.mjs` passes.
- Falsifiability: re-adding a `defaultValue` to the compiled gateway
fails the new no-default test, and removing `flutter_test_config.dart`
brings back the other 10 failures.
- Unrelated: an earlier full run also failed `community_provider_test`
"discard orphan snapshots and image caches", which waits 500 ms for a
background directory delete. The Mac was running other full suites at
the time; the file passed 8 of 8 runs alone, with and without the
define. It is not touched here.

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-12 16:19:10 -08:00

426 lines
14 KiB
Dart

import 'dart:async';
import 'package:buzz/shared/community/community.dart';
import 'package:buzz/shared/deeplink/deep_link.dart';
import 'package:buzz/shared/hosted/hosted_environment.dart';
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
import 'package:buzz/shared/push/push_bridge.dart';
import 'package:buzz/shared/relay/relay_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
const _channel = MethodChannel('buzz/push');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
apnsDeviceToken.value = null;
apnsRegistrationError.value = null;
pushEndpointGrants.value = const [];
pushEndpointGrantError.value = null;
pushCommunitySnapshotError.value = null;
pendingPushNotificationLink.value = null;
installBuzzPushMethodHandler();
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, null);
debugDefaultTargetPlatformOverride = null;
});
test('captures APNs token success and clears the previous error', () async {
apnsRegistrationError.value = 'old error';
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('apnsTokenChanged', {'token': '01ab'}),
),
(_) {},
);
expect(apnsDeviceToken.value, '01ab');
expect(apnsRegistrationError.value, isNull);
});
test(
'starts native permission and APNs registration without a result gate',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'startRegistration');
return null;
});
await startBuzzPushRegistration();
},
);
test('purges notifications delivered before age restriction', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'purgeAgeRestrictedNotifications');
expect(call.arguments, isNull);
return null;
});
await purgeAgeRestrictedBuzzNotifications();
});
test('reads and exposes persisted endpoint grants on iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'endpointGrants');
expect(call.arguments, {'gatewayUrl': Env.pushGatewayUrl});
return [_grantMap('opaque-grant')];
});
final grants = await readBuzzPushEndpointGrants();
expect(grants, hasLength(1));
expect(grants.single.relayOrigin, 'wss://relay.example');
expect(grants.single.relayPubkey, 'a' * 64);
expect(grants.single.installationId, 'c' * 32);
expect(grants.single.endpointGrant, 'opaque-grant');
expect(grants.single.endpointHash, 'b' * 64);
expect(grants.single.endpointEpoch, 1);
expect(grants.single.generation, 1);
expect(grants.single.expiresAt, 1752624000);
expect(pushEndpointGrants.value.single.endpointGrant, 'opaque-grant');
expect(pushEndpointGrantError.value, isNull);
});
test(
'debug enrollment carries the configured relay and gateway URLs',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final methods = <String>[];
final enrollmentArguments = <Object?>[];
final snapshotArguments = <Object?>[];
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(_channel, (call) async {
methods.add(call.method);
if (call.method == 'enrollPush') {
enrollmentArguments.add(call.arguments);
return _grantMap('new-grant');
}
if (call.method == 'endpointGrants') {
return [_grantMap('new-grant')];
}
if (call.method == 'syncPushSnapshot') {
snapshotArguments.add(call.arguments);
return null;
}
fail('Unexpected method ${call.method}');
});
final firstGrant = await enrollBuzzPush(
'wss://relay.example/',
'https://gateway-one.example/',
);
final secondGrant = await enrollBuzzPush(
'wss://relay.example/',
'https://gateway-two.example/',
communitiesForSnapshotRefresh: [
Community(
id: 'community-id',
name: 'Community',
relayUrl: 'wss://relay.example/',
pubkey: 'd' * 64,
pushNotificationsEnabled: true,
addedAt: DateTime.fromMillisecondsSinceEpoch(0),
),
],
);
expect(firstGrant.endpointGrant, 'new-grant');
expect(secondGrant.endpointGrant, 'new-grant');
expect(enrollmentArguments, [
{
'relayUrl': 'wss://relay.example/',
'gatewayUrl': 'https://gateway-one.example/',
},
{
'relayUrl': 'wss://relay.example/',
'gatewayUrl': 'https://gateway-two.example/',
},
]);
expect(methods, [
'enrollPush',
'endpointGrants',
'enrollPush',
'endpointGrants',
'syncPushSnapshot',
]);
expect(snapshotArguments, [
{
'section': 'communities',
'communities': [
{
'id': 'community-id',
'name': 'Community',
'relayUrl': 'wss://relay.example/',
'pubkey': 'd' * 64,
'policies': <Object?>[],
},
],
'signingKeys': <String, String>{},
},
]);
expect(pushEndpointGrants.value.single.endpointGrant, 'new-grant');
},
);
test('shares and clears the hosted session with the extension', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final shared = <Object?>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'syncPushSnapshot');
shared.add(call.arguments);
return null;
});
for (final credential in ['session-credential', null]) {
await shareHostedSessionWithNotifications(
origin: Uri.parse('https://app.example'),
credential: credential,
relayDomains: const ['communities.example'],
communityDomain: 'communities.example',
);
}
expect(shared, [
for (final credential in ['session-credential', null])
{
'section': 'hostedSession',
'origin': 'https://app.example',
'credential': credential,
'relayDomains': ['communities.example'],
'communityDomain': 'communities.example',
},
]);
});
test(
'a build without hosted relay auth clears a shared hosted session',
() async {
expect(HostedRelayAuth.configured && HostedEnvironment.enabled, isFalse);
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final shared = <Object?>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
shared.add((call.arguments as Map)['credential']);
return null;
});
final container = ProviderContainer();
addTearDown(container.dispose);
// A copy an earlier flag-on build shared is removed instead of kept.
await container.read(builderlabAccountProvider).onSessionChanged!('live');
expect(shared, [null]);
},
);
test('exposes APNs registration failure', () async {
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('apnsRegistrationFailed', {'message': 'denied'}),
),
(_) {},
);
expect(apnsRegistrationError.value, 'denied');
});
test('routes a warm notification response with opaque IDs', () async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
MethodCall('notificationOpened', {
'eventId': 'MESSAGE-ID',
'communityId': 'community-id',
'channelId': 'CHANNEL/GENERAL',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'handled');
expect(
pendingPushNotificationLink.value,
MessageDeepLink(
communityId: 'community-id',
channelId: 'CHANNEL/GENERAL',
messageId: 'MESSAGE-ID',
),
);
});
test(
'preserves the exact reply and containing thread on a warm tap',
() async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('notificationOpened', {
'eventId': 'older-reply',
'communityId': 'community-id',
'channelId': 'channel-id',
'threadRootId': 'direct-parent',
}),
),
response.complete,
);
expect(
_channel.codec.decodeEnvelope((await response.future)!),
'handled',
);
expect(
pendingPushNotificationLink.value,
const MessageDeepLink(
communityId: 'community-id',
channelId: 'channel-id',
messageId: 'older-reply',
threadRootId: 'direct-parent',
),
);
},
);
for (final invalidThread in ['', 42]) {
test('rejects malformed thread ID $invalidThread', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
_channel,
(_) async => {
'eventId': 'reply',
'communityId': 'community',
'channelId': 'channel',
'threadRootId': invalidThread,
},
);
await syncPendingBuzzPushNotificationResponse();
expect(pendingPushNotificationLink.value, isNull);
});
}
test('rejects a notification response with an empty channel ID', () async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
MethodCall('notificationOpened', {
'eventId': 'message-id',
'communityId': 'community-id',
'channelId': '',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'ignored');
expect(pendingPushNotificationLink.value, isNull);
});
test(
'rejects a notification response with a non-string message ID',
() async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
MethodCall('notificationOpened', {
'eventId': 42,
'communityId': 'community-id',
'channelId': 'channel-id',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'ignored');
expect(pendingPushNotificationLink.value, isNull);
},
);
test('rejects a notification response with an absent message ID', () async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('notificationOpened', {
'communityId': 'community-id',
'channelId': 'channel-id',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'ignored');
expect(pendingPushNotificationLink.value, isNull);
});
test('pulls a cold-start notification response from native iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'takePendingNotificationResponse');
return {
'eventId': 'b' * 64,
'threadRootId': 'a' * 64,
'communityId': 'community-id',
'channelId': '123e4567-e89b-42d3-a456-426614174000',
};
});
await syncPendingBuzzPushNotificationResponse();
expect(
pendingPushNotificationLink.value,
MessageDeepLink(
communityId: 'community-id',
channelId: '123e4567-e89b-42d3-a456-426614174000',
messageId: 'b' * 64,
threadRootId: 'a' * 64,
),
);
});
}
Map<String, Object> _grantMap(String endpointGrant) => {
'relayOrigin': 'wss://relay.example',
'relayPubkey': 'a' * 64,
'installationId': 'c' * 32,
'endpointGrant': endpointGrant,
'endpointHash': 'b' * 64,
'endpointEpoch': 1,
'generation': 1,
'expiresAt': 1752624000,
};