diff --git a/AGENTS.md b/AGENTS.md index 900ff6d5b..6580a9d47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -110,7 +110,7 @@ dart test test/specific_test.dart -n "test name pattern" Build tests on the `supabase_test` package instead of writing mocks by hand: -- Answer HTTP calls with `MockSupabaseHttpClient` and its `stub`, `stubHandler`, `stubError` and `stubTable`/`stubRpc`/`stubStorage*` helpers. Do not subclass `BaseClient` in a test. Match methods with `HttpMethod.post.value` and friends rather than raw strings. +- Answer HTTP calls with `MockSupabaseHttpClient` and its `stub`, `stubHandler`, `stubError` and `stubTable`/`stubRpc`/`stubStorage*` helpers. Do not subclass `BaseClient` in a test. Match methods with `HttpMethod.post` and friends. - Assert on what was sent with `requests` and `requestsTo(path, method:)`. - Put a client into a signed-in state with `signInTestUser`, and build server payloads with `testUserJson`, `testSessionResponseJson` and `unsignedTestJwt`. Do not hand-assemble JWTs or session JSON. - Construct clients with `testSupabaseClient` where a whole `SupabaseClient` is needed. diff --git a/MIGRATION.md b/MIGRATION.md index 775a9c6cf..d8732a653 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -21,8 +21,8 @@ it also takes care of several of the database changes further down. After it com [the changes the compiler will not catch](#changes-the-compiler-will-not-catch), and then every breaking change grouped by area: [packages and setup](#packages-and-setup), [database](#database), [auth](#auth), [realtime](#realtime), [storage](#storage), -[errors](#errors), [requests, retries and tokens](#requests-retries-and-tokens) and -[shared types](#shared-types). +[errors](#errors), [requests, retries and tokens](#requests-retries-and-tokens), +[shared types](#shared-types) and [testing](#testing). ### Install the package skills @@ -2048,3 +2048,21 @@ unaffected. For `functions.invoke`, two things changed: (3 to 5). This is not a compile error, so replace any persisted `index` with `name`. The enum also exposes `value`, the uppercase wire form, in place of `method.name.toUpperCase()`. + +### Testing + +#### `supabase_test` matches methods with `HttpMethod` and takes the `initializeTestSupabase` names + +The `method` parameter of `MockSupabaseHttpClient.requestsTo` and of every `stub*` method is an +`HttpMethod` instead of a `String`. `testSupabaseClient` takes the same parameter names as +`initializeTestSupabase` from `package:supabase_flutter/testing.dart`. + +| Before | After | +| ---------------------------------------- | ------------------------------------------------------ | +| `method: 'POST'` | `method: HttpMethod.post` | +| `testSupabaseClient(apiKey: key)` | `testSupabaseClient(publishableKey: key)` | +| `testSupabaseClient(realtime: realtime)` | `testSupabaseClient(realtimeTransport: realtime.call)` | + +Both helpers now default to an `sb_publishable_` key instead of an unsigned anon JWT. A signed-out +edge function call therefore no longer sends an `Authorization` header, as with a production +publishable key. Pass a JWT as `publishableKey` if a test relies on the old headers. diff --git a/packages/supabase/test/client_authorization_test.dart b/packages/supabase/test/client_authorization_test.dart index 78548ebb0..197061d17 100644 --- a/packages/supabase/test/client_authorization_test.dart +++ b/packages/supabase/test/client_authorization_test.dart @@ -55,7 +55,7 @@ void main() { ); final signIn = httpClient - .requestsTo('/auth/v1/token', method: HttpMethod.post.value) + .requestsTo('/auth/v1/token', method: HttpMethod.post) .single; expect( signIn.headers[HttpHeader.authorization], @@ -92,7 +92,7 @@ void main() { await supabase.auth.getUser(); final request = httpClient - .requestsTo('/auth/v1/user', method: HttpMethod.get.value) + .requestsTo('/auth/v1/user', method: HttpMethod.get) .single; expect( request.headers[HttpHeader.authorization], diff --git a/packages/supabase/test/realtime_access_token_test.dart b/packages/supabase/test/realtime_access_token_test.dart index 39ba06c94..7e718fc45 100644 --- a/packages/supabase/test/realtime_access_token_test.dart +++ b/packages/supabase/test/realtime_access_token_test.dart @@ -11,7 +11,10 @@ void main() { setUp(() { httpClient = MockSupabaseHttpClient(); - supabase = testSupabaseClient(httpClient: httpClient, apiKey: apiKey); + supabase = testSupabaseClient( + httpClient: httpClient, + publishableKey: apiKey, + ); }); tearDown(() => supabase.dispose()); @@ -64,7 +67,7 @@ void main() { final aal2Token = accessTokenWith({'aal': 'aal2'}); httpClient.stub( testSessionResponseJson(accessToken: aal2Token), - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/auth/v1/factors/factor-id/verify', ); diff --git a/packages/supabase/test/stream_insert_test.dart b/packages/supabase/test/stream_insert_test.dart index 8d1194e49..56dce6301 100644 --- a/packages/supabase/test/stream_insert_test.dart +++ b/packages/supabase/test/stream_insert_test.dart @@ -10,7 +10,10 @@ void main() { setUp(() { httpClient = MockSupabaseHttpClient(); realtime = MockRealtimeTransport(); - supabase = testSupabaseClient(httpClient: httpClient, realtime: realtime); + supabase = testSupabaseClient( + httpClient: httpClient, + realtimeTransport: realtime.call, + ); }); tearDown(() async { diff --git a/packages/supabase/test/stream_order_test.dart b/packages/supabase/test/stream_order_test.dart index 18338c39d..f1f297f1e 100644 --- a/packages/supabase/test/stream_order_test.dart +++ b/packages/supabase/test/stream_order_test.dart @@ -13,7 +13,10 @@ void main() { setUp(() { httpClient = MockSupabaseHttpClient(); realtime = MockRealtimeTransport(); - supabase = testSupabaseClient(httpClient: httpClient, realtime: realtime); + supabase = testSupabaseClient( + httpClient: httpClient, + realtimeTransport: realtime.call, + ); }); tearDown(() async { diff --git a/packages/supabase/test/stream_select_test.dart b/packages/supabase/test/stream_select_test.dart index 79d260dfa..757524fdb 100644 --- a/packages/supabase/test/stream_select_test.dart +++ b/packages/supabase/test/stream_select_test.dart @@ -33,7 +33,10 @@ void main() { setUp(() { httpClient = MockSupabaseHttpClient(); realtime = MockRealtimeTransport(); - supabase = testSupabaseClient(httpClient: httpClient, realtime: realtime); + supabase = testSupabaseClient( + httpClient: httpClient, + realtimeTransport: realtime.call, + ); }); tearDown(() async { diff --git a/packages/supabase/test/typed_postgres_changes_test.dart b/packages/supabase/test/typed_postgres_changes_test.dart index 0a24fcb78..c666b7463 100644 --- a/packages/supabase/test/typed_postgres_changes_test.dart +++ b/packages/supabase/test/typed_postgres_changes_test.dart @@ -40,7 +40,7 @@ void main() { setUp(() { realtime = MockRealtimeTransport(); - supabase = testSupabaseClient(realtime: realtime); + supabase = testSupabaseClient(realtimeTransport: realtime.call); channel = supabase.channel('todos'); }); diff --git a/packages/supabase/test/typed_table_schema_test.dart b/packages/supabase/test/typed_table_schema_test.dart index 03233cae6..1f2aec005 100644 --- a/packages/supabase/test/typed_table_schema_test.dart +++ b/packages/supabase/test/typed_table_schema_test.dart @@ -34,7 +34,10 @@ void main() { setUp(() { httpClient = MockSupabaseHttpClient(); realtime = MockRealtimeTransport(); - supabase = testSupabaseClient(httpClient: httpClient, realtime: realtime); + supabase = testSupabaseClient( + httpClient: httpClient, + realtimeTransport: realtime.call, + ); }); tearDown(() async { diff --git a/packages/supabase_auth/test/admin_sso_test.dart b/packages/supabase_auth/test/admin_sso_test.dart index 110fd316d..54005a1c3 100644 --- a/packages/supabase_auth/test/admin_sso_test.dart +++ b/packages/supabase_auth/test/admin_sso_test.dart @@ -1,5 +1,4 @@ import 'package:supabase_auth/supabase_auth.dart'; -import 'package:supabase_common/supabase_common.dart'; import 'package:test/test.dart'; import 'utils.dart'; @@ -229,7 +228,7 @@ void main() { final request = mockClient .requestsTo( '/admin/sso/providers', - method: HttpMethod.get.value, + method: HttpMethod.get, ) .single; expect(request.queryParameters, {'resource_id_prefix': 'ac'}); @@ -250,7 +249,7 @@ void main() { final request = mockClient .requestsTo( '/admin/sso/providers', - method: HttpMethod.post.value, + method: HttpMethod.post, ) .single; expect(request.jsonBody, { @@ -268,7 +267,7 @@ void main() { expect( mockClient.requestsTo( '/admin/sso/providers/resource_acme', - method: HttpMethod.get.value, + method: HttpMethod.get, ), hasLength(1), ); @@ -288,7 +287,7 @@ void main() { final request = mockClient .requestsTo( '/admin/sso/providers/$_providerId', - method: HttpMethod.put.value, + method: HttpMethod.put, ) .single; expect(request.jsonBody, { @@ -306,7 +305,7 @@ void main() { expect( mockClient.requestsTo( '/admin/sso/providers/$_providerId', - method: HttpMethod.delete.value, + method: HttpMethod.delete, ), hasLength(1), ); diff --git a/packages/supabase_auth/test/admin_update_factor_test.dart b/packages/supabase_auth/test/admin_update_factor_test.dart index c71c897e1..ec45c104e 100644 --- a/packages/supabase_auth/test/admin_update_factor_test.dart +++ b/packages/supabase_auth/test/admin_update_factor_test.dart @@ -1,5 +1,4 @@ import 'package:supabase_auth/supabase_auth.dart'; -import 'package:supabase_common/supabase_common.dart'; import 'package:test/test.dart'; import 'utils.dart'; @@ -38,7 +37,7 @@ void main() { final requests = httpClient.requestsTo( '/admin/users/$userId/factors/$factorId', - method: HttpMethod.put.value, + method: HttpMethod.put, ); expect(requests, hasLength(1)); expect(requests.single.jsonBody, { diff --git a/packages/supabase_auth/test/refresh_token_ownership_test.dart b/packages/supabase_auth/test/refresh_token_ownership_test.dart index 45a79dc28..ab14069b5 100644 --- a/packages/supabase_auth/test/refresh_token_ownership_test.dart +++ b/packages/supabase_auth/test/refresh_token_ownership_test.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'package:supabase_auth/supabase_auth.dart'; -import 'package:supabase_common/supabase_common.dart'; import 'package:test/test.dart'; import 'utils.dart'; @@ -28,7 +27,7 @@ void main() { void stubRefreshRejection(String code) { httpClient.stub( rejection(code), - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/token', query: {'grant_type': 'refresh_token'}, statusCode: 400, @@ -152,7 +151,7 @@ void main() { headers: apiVersionHeaders, ); }, - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/token', query: {'grant_type': 'refresh_token'}, ); diff --git a/packages/supabase_auth/test/refresh_transient_failure_test.dart b/packages/supabase_auth/test/refresh_transient_failure_test.dart index a59932b34..c3ea658df 100644 --- a/packages/supabase_auth/test/refresh_transient_failure_test.dart +++ b/packages/supabase_auth/test/refresh_transient_failure_test.dart @@ -68,7 +68,7 @@ void main() { }) { httpClient.stub( body, - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/token', query: refreshQuery, statusCode: statusCode, @@ -80,7 +80,7 @@ void main() { void stubRefreshHtml(int statusCode, {int? times}) { httpClient.stubText( htmlPage, - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/token', query: refreshQuery, statusCode: statusCode, diff --git a/packages/supabase_auth/test/update_user_race_test.dart b/packages/supabase_auth/test/update_user_race_test.dart index 01d4ab530..5d6eab435 100644 --- a/packages/supabase_auth/test/update_user_race_test.dart +++ b/packages/supabase_auth/test/update_user_race_test.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'package:supabase_auth/supabase_auth.dart'; -import 'package:supabase_common/supabase_common.dart'; import 'package:test/test.dart'; import 'utils.dart'; @@ -24,7 +23,7 @@ void main() { testUserJson(email: 'updated@email.com'), ); }, - method: HttpMethod.put.value, + method: HttpMethod.put, path: '/user', ); client = AuthClient( diff --git a/packages/supabase_flutter/lib/testing.dart b/packages/supabase_flutter/lib/testing.dart index 097ea2d8e..eca954884 100644 --- a/packages/supabase_flutter/lib/testing.dart +++ b/packages/supabase_flutter/lib/testing.dart @@ -3,7 +3,7 @@ /// /// [initializeTestSupabase] initializes [Supabase] the way a test needs it: /// in-memory persistence, no token auto refresh, no deep link detection, and -/// an unsigned test key. Answer the HTTP traffic with a +/// a test publishable key. Answer the HTTP traffic with a /// `MockSupabaseHttpClient` from `package:supabase_test`, and realtime with /// its `MockRealtimeTransport`: /// @@ -25,20 +25,17 @@ /// ``` library; -import 'dart:convert'; - import 'package:http/http.dart'; import 'package:meta/meta.dart'; import 'supabase_flutter.dart'; -/// The publishable key [initializeTestSupabase] uses by default: an unsigned -/// JWT carrying the `anon` role, which the mocked services never verify. +/// The publishable key [initializeTestSupabase] uses by default. +/// +/// It carries the `sb_publishable_` prefix, so signed-out requests carry the +/// headers a production publishable key produces. @visibleForTesting -final String testPublishableKey = _unsignedJwt({ - 'role': 'anon', - 'iss': 'supabase_flutter_testing', -}); +const testPublishableKey = 'sb_publishable_supabase_flutter_testing'; /// Initializes [Supabase] for a test and returns the instance. /// @@ -49,7 +46,7 @@ final String testPublishableKey = _unsignedJwt({ /// touched, and defaults [publishableKey] to [testPublishableKey]. Pass a /// `MockSupabaseHttpClient` as [httpClient] to answer the requests, and the /// `call` method of a `MockRealtimeTransport` as [realtimeTransport] to -/// answer the realtime traffic. +/// answer the realtime traffic, the same way `testSupabaseClient` takes them. /// /// Dispose the instance when the test ends, for example with /// `addTearDown(supabase.dispose)`, so the next test can initialize again. @@ -76,11 +73,3 @@ Future initializeTestSupabase({ ), ); } - -String _unsignedJwt(Map claims) { - final header = base64Url.encode( - utf8.encode(jsonEncode({'alg': 'HS256', 'typ': 'JWT'})), - ); - final payload = base64Url.encode(utf8.encode(jsonEncode(claims))); - return '$header.$payload.AAAA'; -} diff --git a/packages/supabase_flutter/test/restore_credential_test.dart b/packages/supabase_flutter/test/restore_credential_test.dart index e4e919812..d634195c7 100644 --- a/packages/supabase_flutter/test/restore_credential_test.dart +++ b/packages/supabase_flutter/test/restore_credential_test.dart @@ -107,12 +107,12 @@ void main() { httpClient = MockSupabaseHttpClient() ..stub( _registrationOptions(), - method: HttpMethod.post.value, + method: HttpMethod.post, path: _registrationOptionsPath, ) ..stub( _passkeyJson('Google Password Manager'), - method: HttpMethod.post.value, + method: HttpMethod.post, path: _registrationVerifyPath, ) ..stubHandler( @@ -120,12 +120,12 @@ void main() { final body = request.jsonBody as Map; return jsonResponse(_passkeyJson(body['friendly_name'] as String)); }, - method: HttpMethod.patch.value, + method: HttpMethod.patch, path: _passkeyPath, ) ..stub( _authenticationOptions, - method: HttpMethod.post.value, + method: HttpMethod.post, path: _authenticationOptionsPath, ) ..stub( @@ -135,7 +135,7 @@ void main() { 'role': 'authenticated', }), ), - method: HttpMethod.post.value, + method: HttpMethod.post, path: _authenticationVerifyPath, ); client = AuthClient( @@ -186,7 +186,7 @@ void main() { test('uses a custom friendly name for the key and account label', () async { httpClient.stub( _registrationOptions(withUserName: false), - method: HttpMethod.post.value, + method: HttpMethod.post, path: _registrationOptionsPath, ); final restore = _FakeRestoreCredential(); @@ -224,7 +224,7 @@ void main() { 'error_code': 'validation_failed', 'msg': 'Invalid credential', }, - method: HttpMethod.post.value, + method: HttpMethod.post, path: _registrationVerifyPath, statusCode: 400, ); @@ -249,7 +249,7 @@ void main() { 'error_code': 'unexpected_failure', 'msg': 'Database error', }, - method: HttpMethod.patch.value, + method: HttpMethod.patch, path: _passkeyPath, statusCode: 500, ); diff --git a/packages/supabase_flutter/test/supabase_flutter_test.dart b/packages/supabase_flutter/test/supabase_flutter_test.dart index 873ddcc07..dca62e787 100644 --- a/packages/supabase_flutter/test/supabase_flutter_test.dart +++ b/packages/supabase_flutter/test/supabase_flutter_test.dart @@ -73,12 +73,12 @@ void main() { final httpClient = MockSupabaseHttpClient() ..stub( null, - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/storage/v1/upload/resumable', statusCode: 201, headers: {'location': uploadUrl}, ) - ..stubStall(method: HttpMethod.patch.value); + ..stubStall(method: HttpMethod.patch); final supabase = await Supabase.initialize( url: 'https://project.supabase.co', publishableKey: supabaseKey, diff --git a/packages/supabase_flutter/test/testing_test.dart b/packages/supabase_flutter/test/testing_test.dart index f4162deaf..b47c77d71 100644 --- a/packages/supabase_flutter/test/testing_test.dart +++ b/packages/supabase_flutter/test/testing_test.dart @@ -96,8 +96,17 @@ void main() { expect(urls.single, startsWith('ws://localhost:54321/realtime/v1')); }); - test('the publishable key carries the anon role', () { - expect(decodeTestJwtClaims(testPublishableKey)['role'], 'anon'); + test('a signed-out function call sends the key only as apikey', () async { + httpClient.stubEdgeFunction('hello'); + final supabase = await initializeTestSupabase(httpClient: httpClient); + addTearDown(supabase.dispose); + + await supabase.client.functions.invoke('hello'); + + final headers = httpClient.requests.single.headers; + expect(testPublishableKey, startsWith('sb_publishable_')); + expect(headers['apikey'], testPublishableKey); + expect(headers['Authorization'], isNull); }); test('a custom key, url and headers are passed through', () async { diff --git a/packages/supabase_storage/test/basic_test.dart b/packages/supabase_storage/test/basic_test.dart index fd3845a99..ea192b3a1 100644 --- a/packages/supabase_storage/test/basic_test.dart +++ b/packages/supabase_storage/test/basic_test.dart @@ -3,7 +3,6 @@ import 'dart:io'; import 'dart:typed_data'; import 'package:http/http.dart' show ClientException; -import 'package:supabase_common/supabase_common.dart' show HttpMethod; import 'package:supabase_storage/supabase_storage.dart'; import 'package:supabase_test/internal.dart'; import 'package:supabase_test/supabase_test.dart'; diff --git a/packages/supabase_storage/test/fetch_test.dart b/packages/supabase_storage/test/fetch_test.dart index 9c14407b0..4104d82eb 100644 --- a/packages/supabase_storage/test/fetch_test.dart +++ b/packages/supabase_storage/test/fetch_test.dart @@ -5,7 +5,6 @@ import 'dart:typed_data'; import 'package:http/http.dart'; import 'package:http/testing.dart'; -import 'package:supabase_common/supabase_common.dart' show HttpMethod; import 'package:supabase_storage/supabase_storage.dart'; import 'package:supabase_test/supabase_test.dart'; import 'package:test/test.dart'; diff --git a/packages/supabase_storage/test/resumable_upload_test.dart b/packages/supabase_storage/test/resumable_upload_test.dart index 9913f247b..179293792 100644 --- a/packages/supabase_storage/test/resumable_upload_test.dart +++ b/packages/supabase_storage/test/resumable_upload_test.dart @@ -4,7 +4,6 @@ import 'dart:io'; import 'dart:typed_data'; import 'package:http/http.dart'; -import 'package:supabase_common/supabase_common.dart' show HttpMethod; import 'package:supabase_storage/supabase_storage.dart'; import 'package:supabase_test/supabase_test.dart'; import 'package:test/test.dart'; @@ -19,18 +18,18 @@ class FakeTusServer { httpClient ..stubHandler( _create, - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/upload/resumable', ) ..stubHandler( _create, - method: HttpMethod.post.value, + method: HttpMethod.post, path: '/upload/resumable/sign', ) - ..stubHandler(_head, method: HttpMethod.head.value, path: uploadUrlPath) + ..stubHandler(_head, method: HttpMethod.head, path: uploadUrlPath) ..stubHandler( _append, - method: HttpMethod.patch.value, + method: HttpMethod.patch, path: uploadUrlPath, ) ..stubHandler( @@ -38,7 +37,7 @@ class FakeTusServer { length = null; return Response('', 204); }, - method: HttpMethod.delete.value, + method: HttpMethod.delete, path: uploadUrlPath, ); } @@ -124,10 +123,10 @@ void main() { ); List patches() => - httpClient.requestsTo(uploadUrlPath, method: HttpMethod.patch.value); + httpClient.requestsTo(uploadUrlPath, method: HttpMethod.patch); List heads() => - httpClient.requestsTo(uploadUrlPath, method: HttpMethod.head.value); + httpClient.requestsTo(uploadUrlPath, method: HttpMethod.head); setUp(() { httpClient = MockSupabaseHttpClient(); @@ -159,7 +158,7 @@ void main() { expect(server.received.toBytes(), data); final create = httpClient - .requestsTo('/upload/resumable', method: HttpMethod.post.value) + .requestsTo('/upload/resumable', method: HttpMethod.post) .single; expect(create.headers['tus-resumable'], '1.0.0'); expect(create.headers['upload-length'], '10'); @@ -209,7 +208,7 @@ void main() { expect(server.received.toBytes(), data); final create = httpClient - .requestsTo('/upload/resumable', method: HttpMethod.post.value) + .requestsTo('/upload/resumable', method: HttpMethod.post) .single; expect( decodeUploadMetadata(create.headers['upload-metadata']!)['contentType'], @@ -218,7 +217,7 @@ void main() { }); test('records the upload before the first chunk is sent', () async { - httpClient.stubStall(method: HttpMethod.patch.value, times: 1); + httpClient.stubStall(method: HttpMethod.patch, times: 1); final upload = storage .from('videos') @@ -248,7 +247,7 @@ void main() { test( 'pauses the chunk in flight and resumes from the server offset', () async { - httpClient.stubStall(method: HttpMethod.patch.value, times: 1); + httpClient.stubStall(method: HttpMethod.patch, times: 1); final upload = storage .from('videos') .resumableUploadBinary('clip.mp4', data); @@ -277,7 +276,7 @@ void main() { server.received.add(data.sublist(0, 4)); return Response('Upload-Offset conflict', 409); }, - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 1, ); @@ -290,7 +289,7 @@ void main() { test('retries a chunk that failed on the network', () async { httpClient.stubError( ClientException('Offline'), - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 2, ); @@ -303,7 +302,7 @@ void main() { test('retries a chunk the server answered with a 5xx', () async { httpClient.stubHandler( (_) => Response('Service Unavailable', 503), - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 1, ); @@ -315,7 +314,7 @@ void main() { test('keeps the record once the retries run out, to resume later', () async { httpClient.stubError( ClientException('Offline'), - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 3, ); final upload = storage @@ -339,7 +338,7 @@ void main() { test('resumes a failed upload through the same handle', () async { httpClient.stubError( ClientException('Offline'), - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 3, ); final upload = storage @@ -362,7 +361,7 @@ void main() { httpClient.stubText( 'Forbidden', statusCode: 403, - method: HttpMethod.patch.value, + method: HttpMethod.patch, ); final upload = storage .from('videos') @@ -386,7 +385,7 @@ void main() { server.length = null; return Response('Not Found', 404); }, - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 1, ); final upload = storage @@ -397,7 +396,7 @@ void main() { await upload.done; expect( - httpClient.requestsTo('/upload/resumable', method: HttpMethod.post.value), + httpClient.requestsTo('/upload/resumable', method: HttpMethod.post), hasLength(2), ); expect(server.received.toBytes(), data); @@ -413,7 +412,7 @@ void main() { httpClient.stubText( 'Not Found', statusCode: 404, - method: HttpMethod.patch.value, + method: HttpMethod.patch, ); final upload = storage .from('videos') @@ -432,7 +431,7 @@ void main() { expect( httpClient.requestsTo( '/upload/resumable', - method: HttpMethod.post.value, + method: HttpMethod.post, ), hasLength(2), ); @@ -444,7 +443,7 @@ void main() { httpClient.stubText( 'The resource already exists', statusCode: 409, - method: HttpMethod.post.value, + method: HttpMethod.post, ); final upload = storage .from('videos') @@ -475,7 +474,7 @@ void main() { expect( httpClient - .requestsTo('/upload/resumable', method: HttpMethod.post.value) + .requestsTo('/upload/resumable', method: HttpMethod.post) .single .headers['x-upsert'], 'true', @@ -487,7 +486,7 @@ void main() { }); test('cancels the upload on the server and forgets it', () async { - httpClient.stubStall(method: HttpMethod.patch.value, times: 1); + httpClient.stubStall(method: HttpMethod.patch, times: 1); final upload = storage .from('videos') .resumableUploadBinary('clip.mp4', data); @@ -509,7 +508,7 @@ void main() { ), ); expect( - httpClient.requestsTo(uploadUrlPath, method: HttpMethod.delete.value), + httpClient.requestsTo(uploadUrlPath, method: HttpMethod.delete), hasLength(1), ); expect(await storage.resumableUploads(), isEmpty); @@ -535,7 +534,7 @@ void main() { }, ); }, - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 1, ); final upload = storage @@ -551,7 +550,7 @@ void main() { expect(upload.status, ResumableUploadStatus.completed); expect((await upload.done).id, 'object-1'); expect( - httpClient.requestsTo(uploadUrlPath, method: HttpMethod.delete.value), + httpClient.requestsTo(uploadUrlPath, method: HttpMethod.delete), isEmpty, ); }); @@ -560,7 +559,7 @@ void main() { const key = 'sb-localhost-resumable-uploads'; const unreadable = {'future-upload': 'from a newer version'}; await recordStorage.setItem(key, jsonEncode(unreadable)); - httpClient.stubStall(method: HttpMethod.patch.value, times: 1); + httpClient.stubStall(method: HttpMethod.patch, times: 1); final upload = storage .from('videos') @@ -592,7 +591,7 @@ void main() { .done; final create = httpClient - .requestsTo('/upload/resumable/sign', method: HttpMethod.post.value) + .requestsTo('/upload/resumable/sign', method: HttpMethod.post) .single; expect(create.headers['x-signature'], 'signed-token'); expect(create.headers.containsKey('x-upsert'), isFalse); @@ -618,7 +617,7 @@ void main() { }); test('fails when the bytes arrived but no object was stored', () async { - httpClient.stubStall(method: HttpMethod.patch.value, times: 1); + httpClient.stubStall(method: HttpMethod.patch, times: 1); final upload = storage .from('videos') .resumableUploadBinary('clip.mp4', data); @@ -631,7 +630,7 @@ void main() { 200, headers: {'upload-offset': '10', 'upload-length': '10'}, ), - method: HttpMethod.head.value, + method: HttpMethod.head, times: 1, ); @@ -648,10 +647,10 @@ void main() { server.received.add(request.bodyBytes); return Response('', 204, headers: {'upload-offset': '4'}); }, - method: HttpMethod.patch.value, + method: HttpMethod.patch, times: 1, ); - httpClient.stubStall(method: HttpMethod.patch.value, times: 1); + httpClient.stubStall(method: HttpMethod.patch, times: 1); final upload = storage .from('videos') .resumableUploadBinary('clip.mp4', data); @@ -678,7 +677,7 @@ void main() { expect( httpClient.requestsTo( '/upload/resumable', - method: HttpMethod.post.value, + method: HttpMethod.post, ), hasLength(1), ); @@ -709,7 +708,7 @@ void main() { expect(await restarted.resumableUploads(), isEmpty); expect( - httpClient.requestsTo(uploadUrlPath, method: HttpMethod.delete.value), + httpClient.requestsTo(uploadUrlPath, method: HttpMethod.delete), hasLength(1), ); }); diff --git a/packages/supabase_test/README.md b/packages/supabase_test/README.md index 3ad63e99b..8560ff62a 100644 --- a/packages/supabase_test/README.md +++ b/packages/supabase_test/README.md @@ -73,9 +73,10 @@ same stubs. `testSupabaseClient` is a regular `SupabaseClient` wired for tests: it configures the in-memory storage the PKCE flow requires, turns off the token -auto refresh so no timer outlives the test, and defaults the API key to an -unsigned test JWT. Dispose it when the test ends, for example with -`addTearDown(supabase.dispose)`. +auto refresh so no timer outlives the test, and defaults the publishable key +to an `sb_publishable_` test key, so signed-out requests carry the headers a +production publishable key produces. Dispose +it when the test ends, for example with `addTearDown(supabase.dispose)`. ## Stubbing endpoints @@ -135,7 +136,7 @@ a path prefix: final httpClient = MockSupabaseHttpClient() ..stub( {'name': 'avatars', 'id': 'avatars', 'public': true}, - method: HttpMethod.get.value, + method: HttpMethod.get, path: '/storage/v1/bucket/avatars', ); ``` @@ -359,12 +360,12 @@ await supabase .insert(BooksInsert(authorId: 2, title: 'Dune')); final select = httpClient - .requestsTo('/rest/v1/books', method: HttpMethod.get.value) + .requestsTo('/rest/v1/books', method: HttpMethod.get) .single; expect(select.queryParameters['in_print'], 'is.true'); final insert = httpClient - .requestsTo('/rest/v1/books', method: HttpMethod.post.value) + .requestsTo('/rest/v1/books', method: HttpMethod.post) .single; expect(insert.jsonBody, {'author_id': 2, 'title': 'Dune'}); ``` @@ -441,7 +442,7 @@ events: final realtime = MockRealtimeTransport(); final supabase = testSupabaseClient( httpClient: MockSupabaseHttpClient(), - realtime: realtime, + realtimeTransport: realtime.call, ); addTearDown(supabase.dispose); @@ -477,7 +478,8 @@ is recorded in `sent`, and `joinedTopics` lists what it subscribed to. Widget tests initialize `supabase_flutter` through `initializeTestSupabase` from `package:supabase_flutter/testing.dart`, which applies the same test -defaults as `testSupabaseClient` and takes the same mock HTTP client: +defaults as `testSupabaseClient` and takes the same `httpClient`, `url`, +`publishableKey` and `realtimeTransport` parameters: ```dart skip import 'package:supabase_flutter/testing.dart'; diff --git a/packages/supabase_test/example/supabase_test_example.dart b/packages/supabase_test/example/supabase_test_example.dart index e9216c733..f9c6d6053 100644 --- a/packages/supabase_test/example/supabase_test_example.dart +++ b/packages/supabase_test/example/supabase_test_example.dart @@ -54,11 +54,14 @@ void main() { }); test('sends the new todo to the table', () async { - httpClient.stubTable('todos', method: 'POST', statusCode: 201); + httpClient.stubTable('todos', method: HttpMethod.post, statusCode: 201); await repository.add('Release'); - final insert = httpClient.requestsTo('/rest/v1/todos', method: 'POST'); + final insert = httpClient.requestsTo( + '/rest/v1/todos', + method: HttpMethod.post, + ); expect(insert.single.jsonBody, {'task': 'Release', 'status': false}); }); diff --git a/packages/supabase_test/lib/src/mock_realtime_transport.dart b/packages/supabase_test/lib/src/mock_realtime_transport.dart index 45e73970e..95bc132a8 100644 --- a/packages/supabase_test/lib/src/mock_realtime_transport.dart +++ b/packages/supabase_test/lib/src/mock_realtime_transport.dart @@ -25,7 +25,7 @@ import 'realtime_frames.dart'; /// final realtime = MockRealtimeTransport(); /// final supabase = testSupabaseClient( /// httpClient: httpClient, -/// realtime: realtime, +/// realtimeTransport: realtime.call, /// ); /// /// final channel = supabase.channel('todos'); diff --git a/packages/supabase_test/lib/src/mock_supabase_http_client.dart b/packages/supabase_test/lib/src/mock_supabase_http_client.dart index 5d68c1e89..511d7a64e 100644 --- a/packages/supabase_test/lib/src/mock_supabase_http_client.dart +++ b/packages/supabase_test/lib/src/mock_supabase_http_client.dart @@ -10,6 +10,7 @@ import 'dart:typed_data'; import 'package:http/http.dart'; import 'package:meta/meta.dart'; +import 'package:supabase/supabase.dart' show HttpMethod; import 'internal_http_clients.dart'; import 'mock_http_clients.dart'; @@ -73,7 +74,7 @@ class _Stub { this.bareEndpoint, }); - final String? method; + final HttpMethod? method; final String? path; /// The path this stub also answers when it is matched exactly, so a @@ -93,8 +94,7 @@ class _Stub { if (remaining == 0) { return false; } - if (method != null && - method!.toUpperCase() != request.method.toUpperCase()) { + if (!_methodMatches(request.method, method)) { return false; } if (path != null && @@ -122,7 +122,8 @@ class _Stub { /// either targets `public`. static String _requestSchema(BaseRequest request) { final method = request.method.toUpperCase(); - final header = method == 'GET' || method == 'HEAD' + final header = + method == HttpMethod.get.value || method == HttpMethod.head.value ? 'Accept-Profile' : 'Content-Profile'; return request.headers[header] ?? 'public'; @@ -135,7 +136,7 @@ class _Stub { ? '' : '?${Uri(queryParameters: query).query}'; final schemaSuffix = schema == null ? '' : ' (schema $schema)'; - return '${method ?? '(any method)'} ${path ?? '(any path)'}' + return '${method?.value ?? '(any method)'} ${path ?? '(any path)'}' '$querySuffix$schemaSuffix'; } } @@ -154,6 +155,10 @@ bool _pathMatches(String requestPath, String stubPath) { return stubPath.startsWith('/') || requestPath[boundary - 1] == '/'; } +bool _methodMatches(String requestMethod, HttpMethod? method) { + return method == null || method.value == requestMethod.toUpperCase(); +} + const _singleObjectAccept = 'application/vnd.pgrst.object+json'; /// A mock HTTP client that answers Supabase requests from stubs registered @@ -196,16 +201,18 @@ class MockSupabaseHttpClient extends BaseClient { /// narrowed to [method], oldest first. /// /// ```dart - /// final inserts = httpClient.requestsTo('/rest/v1/todos', method: 'POST'); + /// final inserts = httpClient.requestsTo( + /// '/rest/v1/todos', + /// method: HttpMethod.post, + /// ); /// expect(inserts.single.jsonBody, {'task': 'Write tests'}); /// ``` - List requestsTo(String path, {String? method}) { + List requestsTo(String path, {HttpMethod? method}) { return requests .where( (request) => _pathMatches(request.url.path, path) && - (method == null || - method.toUpperCase() == request.method.toUpperCase()), + _methodMatches(request.method, method), ) .toList(); } @@ -234,7 +241,7 @@ class MockSupabaseHttpClient extends BaseClient { /// state that changes between calls. void stub( Object? body, { - String? method, + HttpMethod? method, String? path, Map? query, int statusCode = 200, @@ -254,7 +261,7 @@ class MockSupabaseHttpClient extends BaseClient { void _stub( Object? body, { - String? method, + HttpMethod? method, String? path, String? bareEndpoint, Map? query, @@ -288,7 +295,7 @@ class MockSupabaseHttpClient extends BaseClient { /// do for [stub]. void stubText( String body, { - String? method, + HttpMethod? method, String? path, Map? query, int statusCode = 200, @@ -333,7 +340,7 @@ class MockSupabaseHttpClient extends BaseClient { /// [method], [path] and [query] match as they do for [stub]. void stubError( Object error, { - String? method, + HttpMethod? method, String? path, Map? query, int? times, @@ -357,7 +364,7 @@ class MockSupabaseHttpClient extends BaseClient { /// code under test a timeout. [method], [path], [query] and [times] match /// as they do for [stub]. void stubStall({ - String? method, + HttpMethod? method, String? path, Map? query, int? times, @@ -388,7 +395,7 @@ class MockSupabaseHttpClient extends BaseClient { void stubStatuses( List statuses, { Object? body, - String? method, + HttpMethod? method, String? path, Map? query, Map headers = const {}, @@ -439,7 +446,7 @@ class MockSupabaseHttpClient extends BaseClient { /// [method], [path], [query] and [times] match as they do for [stub]. void stubHandler( StubHandler handler, { - String? method, + HttpMethod? method, String? path, Map? query, int? times, @@ -470,12 +477,13 @@ class MockSupabaseHttpClient extends BaseClient { /// /// Stubs the PostgREST endpoint `/rest/v1/[table]` that `select`, `insert`, /// `update`, `upsert` and `delete` are served through. A null [method] - /// matches all of them; pass `'GET'` or `'POST'` to answer reads and writes - /// differently. [query] narrows the stub to queries carrying the given - /// PostgREST filters, `{'id': 'eq.1'}` for example, so differently filtered - /// reads of one table receive different rows. [schema] narrows it to - /// requests addressing that schema, so tables of the same name in different - /// schemas receive different rows; a null [schema] matches every schema. + /// matches all of them; pass [HttpMethod.get] or [HttpMethod.post] to answer + /// reads and writes differently. [query] narrows the stub to queries + /// carrying the given PostgREST filters, `{'id': 'eq.1'}` for example, so + /// differently filtered reads of one table receive different rows. [schema] + /// narrows it to requests addressing that schema, so tables of the same + /// name in different schemas receive different rows; a null [schema] + /// matches every schema. /// /// The response is shaped the way PostgREST shapes it for the request: a /// query ending in `single()` receives the only row of a one-row list, or @@ -485,7 +493,7 @@ class MockSupabaseHttpClient extends BaseClient { void stubTable( String table, { Object? rows, - String? method, + HttpMethod? method, Map? query, String? schema, int statusCode = 200, @@ -561,7 +569,7 @@ class MockSupabaseHttpClient extends BaseClient { }) { _stub( _sessionJson(user: user, expiresAt: expiresAt), - method: 'POST', + method: HttpMethod.post, path: '/auth/v1/token', bareEndpoint: '/token', times: times, @@ -578,7 +586,7 @@ class MockSupabaseHttpClient extends BaseClient { }) { _stub( _sessionJson(user: user, expiresAt: expiresAt), - method: 'POST', + method: HttpMethod.post, path: '/auth/v1/signup', bareEndpoint: '/signup', times: times, @@ -589,7 +597,7 @@ class MockSupabaseHttpClient extends BaseClient { void stubSignOut({int? times}) { _stub( null, - method: 'POST', + method: HttpMethod.post, path: '/auth/v1/logout', bareEndpoint: '/logout', statusCode: 204, @@ -619,7 +627,7 @@ class MockSupabaseHttpClient extends BaseClient { int? times, }) { final objectPath = _storageObjectPath(bucket, path); - for (final method in ['POST', 'PUT']) { + for (final method in [HttpMethod.post, HttpMethod.put]) { stub( {'Key': '$bucket/${_cleanStoragePath(path)}', 'Id': id}, method: method, @@ -644,7 +652,7 @@ class MockSupabaseHttpClient extends BaseClient { for (final endpoint in ['object', 'render/image/authenticated']) { stub( bytes, - method: 'GET', + method: HttpMethod.get, path: '/storage/v1/$endpoint/$objectPath', statusCode: statusCode, headers: {'content-type': contentType}, @@ -666,7 +674,7 @@ class MockSupabaseHttpClient extends BaseClient { final objectPath = _storageObjectPath(bucket, path); stub( {'signedURL': '/object/sign/$objectPath?token=$token'}, - method: 'POST', + method: HttpMethod.post, path: '/storage/v1/object/sign/$objectPath', statusCode: statusCode, times: times, @@ -683,7 +691,7 @@ class MockSupabaseHttpClient extends BaseClient { }) { stub( objects, - method: 'POST', + method: HttpMethod.post, path: '/storage/v1/object/list/$bucket', statusCode: statusCode, times: times, @@ -703,7 +711,7 @@ class MockSupabaseHttpClient extends BaseClient { for (final path in paths) storageObjectJson(_cleanStoragePath(path), bucketId: bucket), ], - method: 'DELETE', + method: HttpMethod.delete, path: '/storage/v1/object/$bucket', statusCode: statusCode, times: times, @@ -721,7 +729,7 @@ class MockSupabaseHttpClient extends BaseClient { int? times, }) { final path = '/storage/v1/bucket/$bucket/lifecycle'; - for (final method in ['GET', 'PUT']) { + for (final method in [HttpMethod.get, HttpMethod.put]) { stub( {'rules': rules}, method: method, @@ -732,7 +740,7 @@ class MockSupabaseHttpClient extends BaseClient { } stub( {'message': 'Successfully deleted'}, - method: 'DELETE', + method: HttpMethod.delete, path: path, statusCode: statusCode, times: times, @@ -768,7 +776,7 @@ class MockSupabaseHttpClient extends BaseClient { Object? body, { required String path, required int statusCode, - String? method, + HttpMethod? method, Map? query, String? schema, int? count, @@ -815,7 +823,7 @@ class MockSupabaseHttpClient extends BaseClient { : '*'; headers['content-range'] = '$range/$rowCount'; } - if (request.method.toUpperCase() == 'HEAD') { + if (request.method.toUpperCase() == HttpMethod.head.value) { return _response( null, request: request, diff --git a/packages/supabase_test/lib/src/test_supabase_client.dart b/packages/supabase_test/lib/src/test_supabase_client.dart index 829c21711..ea6749f14 100644 --- a/packages/supabase_test/lib/src/test_supabase_client.dart +++ b/packages/supabase_test/lib/src/test_supabase_client.dart @@ -12,14 +12,18 @@ import 'mock_realtime_transport.dart'; import 'session_fixture.dart'; import 'test_jwt.dart'; +const _testPublishableKey = 'sb_publishable_supabase_test'; + /// A [SupabaseClient] wired for tests. /// /// Compared to constructing one directly, this configures the in-memory /// storage the pkce flow requires, turns off the token auto refresh so no -/// timer outlives the test, and defaults the API key to an unsigned anon JWT. -/// Answer its requests by passing a `MockSupabaseHttpClient` as [httpClient], -/// and its realtime traffic by passing a [MockRealtimeTransport] as -/// [realtime]: +/// timer outlives the test, and defaults [publishableKey] to an +/// `sb_publishable_` key, so signed-out requests carry the headers a +/// production publishable key produces. Answer its requests by passing a +/// `MockSupabaseHttpClient` as [httpClient], and its realtime traffic by +/// passing the `call` method of a [MockRealtimeTransport] as +/// [realtimeTransport]: /// /// ```dart /// final httpClient = MockSupabaseHttpClient() @@ -37,20 +41,20 @@ import 'test_jwt.dart'; @visibleForTesting SupabaseClient testSupabaseClient({ Client? httpClient, - MockRealtimeTransport? realtime, String url = 'http://localhost:54321', - String? apiKey, + String? publishableKey, + WebSocketTransport? realtimeTransport, bool autoRefreshToken = false, }) { return SupabaseClient( url, - apiKey ?? unsignedTestJwt({'role': 'anon', 'iss': 'supabase_test'}), + publishableKey ?? _testPublishableKey, httpClient: httpClient, authOptions: AuthClientOptions( autoRefreshToken: autoRefreshToken, asyncStorage: MemoryAuthAsyncStorage(), ), - realtimeClientOptions: RealtimeClientOptions(transport: realtime?.call), + realtimeClientOptions: RealtimeClientOptions(transport: realtimeTransport), ); } diff --git a/packages/supabase_test/lib/supabase_test.dart b/packages/supabase_test/lib/supabase_test.dart index 0ee5147fc..fc8e75a25 100644 --- a/packages/supabase_test/lib/supabase_test.dart +++ b/packages/supabase_test/lib/supabase_test.dart @@ -10,6 +10,8 @@ /// warns when a helper leaks outside of test code. library; +export 'package:supabase/supabase.dart' show HttpMethod; + export 'src/mock_http_clients.dart'; export 'src/mock_realtime_transport.dart'; export 'src/mock_supabase_http_client.dart'; diff --git a/packages/supabase_test/skills/supabase-test-testing/SKILL.md b/packages/supabase_test/skills/supabase-test-testing/SKILL.md index 35f018230..03b2041d0 100644 --- a/packages/supabase_test/skills/supabase-test-testing/SKILL.md +++ b/packages/supabase_test/skills/supabase-test-testing/SKILL.md @@ -25,7 +25,7 @@ description: >- - Assert on what was sent with `requests` and `requestsTo`, not by wrapping the client. - Dispose every client at the end of the test. -- Match methods with `HttpMethod.post.value` and friends, not raw strings. +- Match methods with `HttpMethod.post` and friends. ## Setup @@ -85,7 +85,7 @@ needs every non-nullable column in each row. | An edge function | `stubEdgeFunction('hello', body: {...})` | | Sign in, sign up, sign out, the user | `stubSignIn()`, `stubSignUp()`, `stubSignOut()`, `stubUser()` | | Storage | `stubStorageUpload`, `stubStorageDownload`, `stubStorageSignedUrl`, `stubStorageList`, `stubStorageRemove` | -| Any other path | `stub(body, method: HttpMethod.get.value, path: '/storage/v1/bucket/avatars')` | +| Any other path | `stub(body, method: HttpMethod.get, path: '/storage/v1/bucket/avatars')` | | A response computed from the request | `stubHandler((request) => jsonResponse(...), path: ...)` | | No network | `stubError(ClientException('Offline'))` | | A request that never answers | `stubStall(path: ...)` | @@ -130,7 +130,7 @@ await supabase .insert(BooksInsert(authorId: 2, title: 'Dune')); final insert = httpClient - .requestsTo('/rest/v1/books', method: HttpMethod.post.value) + .requestsTo('/rest/v1/books', method: HttpMethod.post) .single; expect(insert.jsonBody, {'author_id': 2, 'title': 'Dune'}); ``` @@ -183,7 +183,7 @@ events from the test: final realtime = MockRealtimeTransport(); final supabase = testSupabaseClient( httpClient: MockSupabaseHttpClient(), - realtime: realtime, + realtimeTransport: realtime.call, ); final channel = supabase.channel('books'); diff --git a/packages/supabase_test/test/exports_test.dart b/packages/supabase_test/test/exports_test.dart new file mode 100644 index 000000000..c226ab43e --- /dev/null +++ b/packages/supabase_test/test/exports_test.dart @@ -0,0 +1,16 @@ +import 'package:supabase_test/supabase_test.dart'; +import 'package:test/test.dart'; + +void main() { + test('HttpMethod is usable with only supabase_test imported', () async { + final httpClient = MockSupabaseHttpClient() + ..stub(null, method: HttpMethod.patch, path: '/rest/v1/todos'); + + await httpClient.patch(Uri.parse('http://localhost:54321/rest/v1/todos')); + + expect( + httpClient.requestsTo('/rest/v1/todos', method: HttpMethod.patch), + hasLength(1), + ); + }); +} diff --git a/packages/supabase_test/test/mock_realtime_transport_test.dart b/packages/supabase_test/test/mock_realtime_transport_test.dart index 333476f79..a96a8e0f3 100644 --- a/packages/supabase_test/test/mock_realtime_transport_test.dart +++ b/packages/supabase_test/test/mock_realtime_transport_test.dart @@ -10,7 +10,10 @@ void main() { setUp(() { httpClient = MockSupabaseHttpClient(); realtime = MockRealtimeTransport(); - supabase = testSupabaseClient(httpClient: httpClient, realtime: realtime); + supabase = testSupabaseClient( + httpClient: httpClient, + realtimeTransport: realtime.call, + ); addTearDown(supabase.dispose); }); diff --git a/packages/supabase_test/test/mock_supabase_http_client_test.dart b/packages/supabase_test/test/mock_supabase_http_client_test.dart index 4948e1ec8..d2888f72e 100644 --- a/packages/supabase_test/test/mock_supabase_http_client_test.dart +++ b/packages/supabase_test/test/mock_supabase_http_client_test.dart @@ -32,7 +32,7 @@ void main() { }); test('records the payload an insert sent', () async { - httpClient.stubTable('todos', method: 'POST', statusCode: 201); + httpClient.stubTable('todos', method: HttpMethod.post, statusCode: 201); await supabase.from('todos').insert({'task': 'Write tests'}); @@ -109,6 +109,23 @@ void main() { ); }); + test('a stub for one method does not answer another', () async { + httpClient.stubTable('todos', method: HttpMethod.post, statusCode: 201); + + await supabase.from('todos').insert({'task': 'Write tests'}); + + await expectLater( + () => supabase.from('todos').select(), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf(contains('No stub matches GET'), contains('POST /rest/v1')), + ), + ), + ); + }); + test('a null body produces an empty response', () async { httpClient.stub(null, statusCode: 204); @@ -227,7 +244,7 @@ void main() { test('single after an insert returns the inserted row', () async { httpClient.stubTable( 'todos', - method: 'POST', + method: HttpMethod.post, statusCode: 201, rows: [ {'id': 1, 'task': 'Write tests'}, @@ -404,7 +421,7 @@ void main() { } return jsonResponse([row], statusCode: 201); }, - method: 'POST', + method: HttpMethod.post, path: '/rest/v1/users', ); @@ -655,7 +672,10 @@ void main() { await supabase.from('todos').insert({'task': 'Write tests'}); expect(httpClient.requestsTo('/rest/v1/todos'), hasLength(2)); - final inserts = httpClient.requestsTo('/rest/v1/todos', method: 'POST'); + final inserts = httpClient.requestsTo( + '/rest/v1/todos', + method: HttpMethod.post, + ); expect(inserts.single.jsonBody, {'task': 'Write tests'}); }); @@ -1035,7 +1055,7 @@ void main() { ); test('writes are matched on their schema too', () async { - httpClient.stubTable('todos', schema: 'archive', method: 'POST'); + httpClient.stubTable('todos', schema: 'archive', method: HttpMethod.post); await supabase.schema('archive').from('todos').insert({'id': 1}); diff --git a/packages/supabase_test/test/test_supabase_client_test.dart b/packages/supabase_test/test/test_supabase_client_test.dart index e2cf4dfea..4d0025c93 100644 --- a/packages/supabase_test/test/test_supabase_client_test.dart +++ b/packages/supabase_test/test/test_supabase_client_test.dart @@ -10,6 +10,56 @@ void main() { expect(supabase.auth.currentSession, isNull); }); + test('a signed-out request carries a publishable key', () async { + final httpClient = MockSupabaseHttpClient() + ..stubTable('todos', rows: []) + ..stubEdgeFunction('hello'); + final supabase = testSupabaseClient(httpClient: httpClient); + addTearDown(supabase.dispose); + + await supabase.from('todos').select(); + await supabase.functions.invoke('hello'); + + final [rest, function] = httpClient.requests; + final key = rest.headers['apikey']; + expect(key, startsWith('sb_publishable_')); + expect(rest.headers['Authorization'], 'Bearer $key'); + expect(function.headers['apikey'], key); + expect(function.headers['Authorization'], isNull); + }); + + test('a custom publishable key is passed through', () async { + final httpClient = MockSupabaseHttpClient()..stubTable('todos', rows: []); + final supabase = testSupabaseClient( + httpClient: httpClient, + publishableKey: 'sb_publishable_custom', + ); + addTearDown(supabase.dispose); + + await supabase.from('todos').select(); + + expect( + httpClient.requests.single.headers['apikey'], + 'sb_publishable_custom', + ); + }); + + test('a realtime transport is wired into the client', () async { + final urls = []; + final supabase = testSupabaseClient( + realtimeTransport: (url, headers) { + urls.add(url); + throw StateError('no socket in this test'); + }, + ); + addTearDown(supabase.dispose); + + supabase.channel('room').subscribe(); + await pumpEventQueue(); + + expect(urls.single, startsWith('ws://localhost:54321/realtime/v1')); + }); + group('signInTestUser', () { late MockSupabaseHttpClient httpClient; late SupabaseClient supabase; diff --git a/packages/supabase_test/test/typed_api_test.dart b/packages/supabase_test/test/typed_api_test.dart index 8eaa69424..79b7c56ad 100644 --- a/packages/supabase_test/test/typed_api_test.dart +++ b/packages/supabase_test/test/typed_api_test.dart @@ -43,7 +43,10 @@ void main() { setUp(() { httpClient = MockSupabaseHttpClient(); realtime = MockRealtimeTransport(); - supabase = testSupabaseClient(httpClient: httpClient, realtime: realtime); + supabase = testSupabaseClient( + httpClient: httpClient, + realtimeTransport: realtime.call, + ); addTearDown(supabase.dispose); }); @@ -137,7 +140,7 @@ void main() { test('a typed insert sends the row and returns it through select', () async { httpClient.stubTable( 'todos', - method: 'POST', + method: HttpMethod.post, statusCode: 201, rows: [ {'id': 7, 'task': 'Write tests', 'status': false}, diff --git a/skills_src/testing/SKILL.md.tmpl b/skills_src/testing/SKILL.md.tmpl index eab62f903..8ef93a739 100644 --- a/skills_src/testing/SKILL.md.tmpl +++ b/skills_src/testing/SKILL.md.tmpl @@ -25,7 +25,7 @@ description: >- - Assert on what was sent with `requests` and `requestsTo`, not by wrapping the client. - Dispose every client at the end of the test. -- Match methods with `HttpMethod.post.value` and friends, not raw strings. +- Match methods with `HttpMethod.post` and friends. ## Setup @@ -85,7 +85,7 @@ needs every non-nullable column in each row. | An edge function | `stubEdgeFunction('hello', body: {...})` | | Sign in, sign up, sign out, the user | `stubSignIn()`, `stubSignUp()`, `stubSignOut()`, `stubUser()` | | Storage | `stubStorageUpload`, `stubStorageDownload`, `stubStorageSignedUrl`, `stubStorageList`, `stubStorageRemove` | -| Any other path | `stub(body, method: HttpMethod.get.value, path: '/storage/v1/bucket/avatars')` | +| Any other path | `stub(body, method: HttpMethod.get, path: '/storage/v1/bucket/avatars')` | | A response computed from the request | `stubHandler((request) => jsonResponse(...), path: ...)` | | No network | `stubError(ClientException('Offline'))` | | A request that never answers | `stubStall(path: ...)` | @@ -130,7 +130,7 @@ await supabase .insert(BooksInsert(authorId: 2, title: 'Dune')); final insert = httpClient - .requestsTo('/rest/v1/books', method: HttpMethod.post.value) + .requestsTo('/rest/v1/books', method: HttpMethod.post) .single; expect(insert.jsonBody, {'author_id': 2, 'title': 'Dune'}); ``` @@ -183,7 +183,7 @@ events from the test: final realtime = MockRealtimeTransport(); final supabase = testSupabaseClient( httpClient: MockSupabaseHttpClient(), - realtime: realtime, + realtimeTransport: realtime.call, ); final channel = supabase.channel('books');