code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:html'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_web/webview_flutter_web.dart'; import 'web_webview_controller_test.mocks.dart'; @GenerateMocks(<Type>[], customMocks: <MockSpec<Object>>[ MockSpec<HttpRequest>(onMissingStub: OnMissingStub.returnDefault), MockSpec<HttpRequestFactory>(onMissingStub: OnMissingStub.returnDefault), ]) void main() { WidgetsFlutterBinding.ensureInitialized(); group('WebWebViewController', () { group('WebWebViewControllerCreationParams', () { test('sets iFrame fields', () { final WebWebViewControllerCreationParams params = WebWebViewControllerCreationParams(); expect(params.iFrame.id, contains('webView')); expect(params.iFrame.style.width, '100%'); expect(params.iFrame.style.height, '100%'); expect(params.iFrame.style.border, 'none'); }); }); group('loadHtmlString', () { test('loadHtmlString loads html into iframe', () async { final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams()); await controller.loadHtmlString('test html'); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, 'data:text/html;charset=utf-8,${Uri.encodeFull('test html')}', ); }); test('loadHtmlString escapes "#" correctly', () async { final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams()); await controller.loadHtmlString('#'); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, contains('%23'), ); }); }); group('loadRequest', () { test('throws ArgumentError on missing scheme', () async { final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams()); await expectLater( () async => controller.loadRequest( LoadRequestParams(uri: Uri.parse('flutter.dev')), ), throwsA(const TypeMatcher<ArgumentError>())); }); test('skips XHR for simple GETs (no headers, no data)', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams( httpRequestFactory: mockHttpRequestFactory, )); when(mockHttpRequestFactory.request( any, method: anyNamed('method'), requestHeaders: anyNamed('requestHeaders'), sendData: anyNamed('sendData'), )).thenThrow( StateError('The `request` method should not have been called.')); await controller.loadRequest(LoadRequestParams( uri: Uri.parse('https://flutter.dev'), )); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, 'https://flutter.dev/', ); }); test('makes request and loads response into iframe', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams( httpRequestFactory: mockHttpRequestFactory, )); final MockHttpRequest mockHttpRequest = MockHttpRequest(); when(mockHttpRequest.getResponseHeader('content-type')) .thenReturn('text/plain'); when(mockHttpRequest.responseText).thenReturn('test data'); when(mockHttpRequestFactory.request( any, method: anyNamed('method'), requestHeaders: anyNamed('requestHeaders'), sendData: anyNamed('sendData'), )).thenAnswer((_) => Future<HttpRequest>.value(mockHttpRequest)); await controller.loadRequest(LoadRequestParams( uri: Uri.parse('https://flutter.dev'), method: LoadRequestMethod.post, body: Uint8List.fromList('test body'.codeUnits), headers: const <String, String>{'Foo': 'Bar'}, )); verify(mockHttpRequestFactory.request( 'https://flutter.dev', method: 'post', requestHeaders: <String, String>{'Foo': 'Bar'}, sendData: Uint8List.fromList('test body'.codeUnits), )); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, 'data:;charset=utf-8,${Uri.encodeFull('test data')}', ); }); test('parses content-type response header correctly', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams( httpRequestFactory: mockHttpRequestFactory, )); final Encoding iso = Encoding.getByName('latin1')!; final MockHttpRequest mockHttpRequest = MockHttpRequest(); when(mockHttpRequest.responseText) .thenReturn(String.fromCharCodes(iso.encode('España'))); when(mockHttpRequest.getResponseHeader('content-type')) .thenReturn('Text/HTmL; charset=latin1'); when(mockHttpRequestFactory.request( any, method: anyNamed('method'), requestHeaders: anyNamed('requestHeaders'), sendData: anyNamed('sendData'), )).thenAnswer((_) => Future<HttpRequest>.value(mockHttpRequest)); await controller.loadRequest(LoadRequestParams( uri: Uri.parse('https://flutter.dev'), method: LoadRequestMethod.post, )); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, 'data:text/html;charset=iso-8859-1,Espa%F1a', ); }); test('escapes "#" correctly', () async { final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams( httpRequestFactory: mockHttpRequestFactory, )); final MockHttpRequest mockHttpRequest = MockHttpRequest(); when(mockHttpRequest.getResponseHeader('content-type')) .thenReturn('text/html'); when(mockHttpRequest.responseText).thenReturn('#'); when(mockHttpRequestFactory.request( any, method: anyNamed('method'), requestHeaders: anyNamed('requestHeaders'), sendData: anyNamed('sendData'), )).thenAnswer((_) => Future<HttpRequest>.value(mockHttpRequest)); await controller.loadRequest(LoadRequestParams( uri: Uri.parse('https://flutter.dev'), method: LoadRequestMethod.post, body: Uint8List.fromList('test body'.codeUnits), headers: const <String, String>{'Foo': 'Bar'}, )); expect( (controller.params as WebWebViewControllerCreationParams).iFrame.src, contains('%23'), ); }); }); }); }
packages/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.dart/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.dart', 'repo_id': 'packages', 'token_count': 3140}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'webkit_webview_controller.dart'; import 'webkit_webview_cookie_manager.dart'; /// Implementation of [WebViewPlatform] using the WebKit API. class WebKitWebViewPlatform extends WebViewPlatform { /// Registers this class as the default instance of [WebViewPlatform]. static void registerWith() { WebViewPlatform.instance = WebKitWebViewPlatform(); } @override WebKitWebViewController createPlatformWebViewController( PlatformWebViewControllerCreationParams params, ) { return WebKitWebViewController(params); } @override WebKitNavigationDelegate createPlatformNavigationDelegate( PlatformNavigationDelegateCreationParams params, ) { return WebKitNavigationDelegate(params); } @override WebKitWebViewWidget createPlatformWebViewWidget( PlatformWebViewWidgetCreationParams params, ) { return WebKitWebViewWidget(params); } @override WebKitWebViewCookieManager createPlatformCookieManager( PlatformWebViewCookieManagerCreationParams params, ) { return WebKitWebViewCookieManager(params); } }
packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_platform.dart/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_platform.dart', 'repo_id': 'packages', 'token_count': 391}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart'; import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart'; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit_api_impls.dart'; import '../common/test_web_kit.g.dart'; import 'web_kit_test.mocks.dart'; @GenerateMocks(<Type>[ TestWKHttpCookieStoreHostApi, TestWKNavigationDelegateHostApi, TestWKPreferencesHostApi, TestWKScriptMessageHandlerHostApi, TestWKUIDelegateHostApi, TestWKUserContentControllerHostApi, TestWKWebViewConfigurationHostApi, TestWKWebViewHostApi, TestWKWebsiteDataStoreHostApi, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebKit', () { late InstanceManager instanceManager; late WebKitFlutterApis flutterApis; setUp(() { instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {}); flutterApis = WebKitFlutterApis(instanceManager: instanceManager); WebKitFlutterApis.instance = flutterApis; }); group('WKWebsiteDataStore', () { late MockTestWKWebsiteDataStoreHostApi mockPlatformHostApi; late WKWebsiteDataStore websiteDataStore; late WKWebViewConfiguration webViewConfiguration; setUp(() { mockPlatformHostApi = MockTestWKWebsiteDataStoreHostApi(); TestWKWebsiteDataStoreHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); websiteDataStore = WKWebsiteDataStore.fromWebViewConfiguration( webViewConfiguration, instanceManager: instanceManager, ); }); tearDown(() { TestWKWebsiteDataStoreHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('WKWebViewConfigurationFlutterApi.create', () { final WebKitFlutterApis flutterApis = WebKitFlutterApis( instanceManager: instanceManager, ); flutterApis.webViewConfiguration.create(2); expect(instanceManager.containsIdentifier(2), isTrue); expect( instanceManager.getInstanceWithWeakReference(2), isA<WKWebViewConfiguration>(), ); }); test('createFromWebViewConfiguration', () { verify(mockPlatformHostApi.createFromWebViewConfiguration( instanceManager.getIdentifier(websiteDataStore), instanceManager.getIdentifier(webViewConfiguration), )); }); test('createDefaultDataStore', () { final WKWebsiteDataStore defaultDataStore = WKWebsiteDataStore.defaultDataStore; verify( mockPlatformHostApi.createDefaultDataStore( NSObject.globalInstanceManager.getIdentifier(defaultDataStore), ), ); }); test('removeDataOfTypes', () { when(mockPlatformHostApi.removeDataOfTypes( any, any, any, )).thenAnswer((_) => Future<bool>.value(true)); expect( websiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{WKWebsiteDataType.cookies}, DateTime.fromMillisecondsSinceEpoch(5000), ), completion(true), ); final List<dynamic> capturedArgs = verify(mockPlatformHostApi.removeDataOfTypes( instanceManager.getIdentifier(websiteDataStore), captureAny, 5.0, )).captured; final List<WKWebsiteDataTypeEnumData> typeData = (capturedArgs.single as List<Object?>) .cast<WKWebsiteDataTypeEnumData>(); expect(typeData.single.value, WKWebsiteDataTypeEnum.cookies); }); }); group('WKHttpCookieStore', () { late MockTestWKHttpCookieStoreHostApi mockPlatformHostApi; late WKHttpCookieStore httpCookieStore; late WKWebsiteDataStore websiteDataStore; setUp(() { mockPlatformHostApi = MockTestWKHttpCookieStoreHostApi(); TestWKHttpCookieStoreHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); TestWKWebsiteDataStoreHostApi.setup( MockTestWKWebsiteDataStoreHostApi(), ); websiteDataStore = WKWebsiteDataStore.fromWebViewConfiguration( WKWebViewConfiguration(instanceManager: instanceManager), instanceManager: instanceManager, ); httpCookieStore = WKHttpCookieStore.fromWebsiteDataStore( websiteDataStore, instanceManager: instanceManager, ); }); tearDown(() { TestWKHttpCookieStoreHostApi.setup(null); TestWKWebsiteDataStoreHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('createFromWebsiteDataStore', () { verify(mockPlatformHostApi.createFromWebsiteDataStore( instanceManager.getIdentifier(httpCookieStore), instanceManager.getIdentifier(websiteDataStore), )); }); test('setCookie', () async { await httpCookieStore.setCookie( const NSHttpCookie.withProperties(<NSHttpCookiePropertyKey, Object>{ NSHttpCookiePropertyKey.comment: 'aComment', })); final NSHttpCookieData cookie = verify( mockPlatformHostApi.setCookie( instanceManager.getIdentifier(httpCookieStore), captureAny, ), ).captured.single as NSHttpCookieData; expect( cookie.propertyKeys.single!.value, NSHttpCookiePropertyKeyEnum.comment, ); expect(cookie.propertyValues.single, 'aComment'); }); }); group('WKScriptMessageHandler', () { late MockTestWKScriptMessageHandlerHostApi mockPlatformHostApi; late WKScriptMessageHandler scriptMessageHandler; setUp(() async { mockPlatformHostApi = MockTestWKScriptMessageHandlerHostApi(); TestWKScriptMessageHandlerHostApi.setup(mockPlatformHostApi); scriptMessageHandler = WKScriptMessageHandler( didReceiveScriptMessage: (_, __) {}, instanceManager: instanceManager, ); }); tearDown(() { TestWKScriptMessageHandlerHostApi.setup(null); }); test('create', () async { verify(mockPlatformHostApi.create( instanceManager.getIdentifier(scriptMessageHandler), )); }); test('didReceiveScriptMessage', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); scriptMessageHandler = WKScriptMessageHandler( instanceManager: instanceManager, didReceiveScriptMessage: ( WKUserContentController userContentController, WKScriptMessage message, ) { argsCompleter.complete(<Object?>[userContentController, message]); }, ); final WKUserContentController userContentController = WKUserContentController.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(userContentController, 2); WebKitFlutterApis.instance.scriptMessageHandler.didReceiveScriptMessage( instanceManager.getIdentifier(scriptMessageHandler)!, 2, WKScriptMessageData(name: 'name'), ); expect( argsCompleter.future, completion(<Object?>[userContentController, isA<WKScriptMessage>()]), ); }); }); group('WKPreferences', () { late MockTestWKPreferencesHostApi mockPlatformHostApi; late WKPreferences preferences; late WKWebViewConfiguration webViewConfiguration; setUp(() { mockPlatformHostApi = MockTestWKPreferencesHostApi(); TestWKPreferencesHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); preferences = WKPreferences.fromWebViewConfiguration( webViewConfiguration, instanceManager: instanceManager, ); }); tearDown(() { TestWKPreferencesHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('createFromWebViewConfiguration', () async { verify(mockPlatformHostApi.createFromWebViewConfiguration( instanceManager.getIdentifier(preferences), instanceManager.getIdentifier(webViewConfiguration), )); }); test('setJavaScriptEnabled', () async { await preferences.setJavaScriptEnabled(true); verify(mockPlatformHostApi.setJavaScriptEnabled( instanceManager.getIdentifier(preferences), true, )); }); }); group('WKUserContentController', () { late MockTestWKUserContentControllerHostApi mockPlatformHostApi; late WKUserContentController userContentController; late WKWebViewConfiguration webViewConfiguration; setUp(() { mockPlatformHostApi = MockTestWKUserContentControllerHostApi(); TestWKUserContentControllerHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); userContentController = WKUserContentController.fromWebViewConfiguration( webViewConfiguration, instanceManager: instanceManager, ); }); tearDown(() { TestWKUserContentControllerHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('createFromWebViewConfiguration', () async { verify(mockPlatformHostApi.createFromWebViewConfiguration( instanceManager.getIdentifier(userContentController), instanceManager.getIdentifier(webViewConfiguration), )); }); test('addScriptMessageHandler', () async { TestWKScriptMessageHandlerHostApi.setup( MockTestWKScriptMessageHandlerHostApi(), ); final WKScriptMessageHandler handler = WKScriptMessageHandler( didReceiveScriptMessage: (_, __) {}, instanceManager: instanceManager, ); await userContentController.addScriptMessageHandler( handler, 'handlerName'); verify(mockPlatformHostApi.addScriptMessageHandler( instanceManager.getIdentifier(userContentController), instanceManager.getIdentifier(handler), 'handlerName', )); }); test('removeScriptMessageHandler', () async { await userContentController.removeScriptMessageHandler('handlerName'); verify(mockPlatformHostApi.removeScriptMessageHandler( instanceManager.getIdentifier(userContentController), 'handlerName', )); }); test('removeAllScriptMessageHandlers', () async { await userContentController.removeAllScriptMessageHandlers(); verify(mockPlatformHostApi.removeAllScriptMessageHandlers( instanceManager.getIdentifier(userContentController), )); }); test('addUserScript', () { userContentController.addUserScript(const WKUserScript( 'aScript', WKUserScriptInjectionTime.atDocumentEnd, isMainFrameOnly: false, )); verify(mockPlatformHostApi.addUserScript( instanceManager.getIdentifier(userContentController), argThat(isA<WKUserScriptData>()), )); }); test('removeAllUserScripts', () { userContentController.removeAllUserScripts(); verify(mockPlatformHostApi.removeAllUserScripts( instanceManager.getIdentifier(userContentController), )); }); }); group('WKWebViewConfiguration', () { late MockTestWKWebViewConfigurationHostApi mockPlatformHostApi; late WKWebViewConfiguration webViewConfiguration; setUp(() async { mockPlatformHostApi = MockTestWKWebViewConfigurationHostApi(); TestWKWebViewConfigurationHostApi.setup(mockPlatformHostApi); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); }); tearDown(() { TestWKWebViewConfigurationHostApi.setup(null); }); test('create', () async { verify( mockPlatformHostApi.create(instanceManager.getIdentifier( webViewConfiguration, )), ); }); test('createFromWebView', () async { TestWKWebViewHostApi.setup(MockTestWKWebViewHostApi()); final WKWebView webView = WKWebView( webViewConfiguration, instanceManager: instanceManager, ); final WKWebViewConfiguration configurationFromWebView = WKWebViewConfiguration.fromWebView( webView, instanceManager: instanceManager, ); verify(mockPlatformHostApi.createFromWebView( instanceManager.getIdentifier(configurationFromWebView), instanceManager.getIdentifier(webView), )); }); test('allowsInlineMediaPlayback', () { webViewConfiguration.setAllowsInlineMediaPlayback(true); verify(mockPlatformHostApi.setAllowsInlineMediaPlayback( instanceManager.getIdentifier(webViewConfiguration), true, )); }); test('limitsNavigationsToAppBoundDomains', () { webViewConfiguration.setLimitsNavigationsToAppBoundDomains(true); verify(mockPlatformHostApi.setLimitsNavigationsToAppBoundDomains( instanceManager.getIdentifier(webViewConfiguration), true, )); }); test('mediaTypesRequiringUserActionForPlayback', () { webViewConfiguration.setMediaTypesRequiringUserActionForPlayback( <WKAudiovisualMediaType>{ WKAudiovisualMediaType.audio, WKAudiovisualMediaType.video, }, ); final List<WKAudiovisualMediaTypeEnumData?> typeData = verify( mockPlatformHostApi.setMediaTypesRequiringUserActionForPlayback( instanceManager.getIdentifier(webViewConfiguration), captureAny, )).captured.single as List<WKAudiovisualMediaTypeEnumData?>; expect(typeData, hasLength(2)); expect(typeData[0]!.value, WKAudiovisualMediaTypeEnum.audio); expect(typeData[1]!.value, WKAudiovisualMediaTypeEnum.video); }); }); group('WKNavigationDelegate', () { late MockTestWKNavigationDelegateHostApi mockPlatformHostApi; late WKWebView webView; late WKNavigationDelegate navigationDelegate; setUp(() async { mockPlatformHostApi = MockTestWKNavigationDelegateHostApi(); TestWKNavigationDelegateHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi(), ); TestWKWebViewHostApi.setup(MockTestWKWebViewHostApi()); webView = WKWebView( WKWebViewConfiguration(instanceManager: instanceManager), instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, ); }); tearDown(() { TestWKNavigationDelegateHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); TestWKWebViewHostApi.setup(null); }); test('create', () async { navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, ); verify(mockPlatformHostApi.create( instanceManager.getIdentifier(navigationDelegate), )); }); test('didFinishNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didFinishNavigation: (WKWebView webView, String? url) { argsCompleter.complete(<Object?>[webView, url]); }, ); WebKitFlutterApis.instance.navigationDelegate.didFinishNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, 'url', ); expect(argsCompleter.future, completion(<Object?>[webView, 'url'])); }); test('didStartProvisionalNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didStartProvisionalNavigation: (WKWebView webView, String? url) { argsCompleter.complete(<Object?>[webView, url]); }, ); WebKitFlutterApis.instance.navigationDelegate .didStartProvisionalNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, 'url', ); expect(argsCompleter.future, completion(<Object?>[webView, 'url'])); }); test('decidePolicyForNavigationAction', () async { WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, decidePolicyForNavigationAction: ( WKWebView webView, WKNavigationAction navigationAction, ) async { return WKNavigationActionPolicy.cancel; }, ); final WKNavigationActionPolicyEnumData policyData = await WebKitFlutterApis.instance.navigationDelegate .decidePolicyForNavigationAction( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, WKNavigationActionData( request: NSUrlRequestData( url: 'url', allHttpHeaderFields: <String, String>{}, ), targetFrame: WKFrameInfoData( isMainFrame: false, request: NSUrlRequestData( url: 'url', allHttpHeaderFields: <String, String>{}, )), navigationType: WKNavigationType.linkActivated, ), ); expect(policyData.value, WKNavigationActionPolicyEnum.cancel); }); test('didFailNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didFailNavigation: (WKWebView webView, NSError error) { argsCompleter.complete(<Object?>[webView, error]); }, ); WebKitFlutterApis.instance.navigationDelegate.didFailNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, NSErrorData( code: 23, domain: 'Hello', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); expect( argsCompleter.future, completion(<Object?>[webView, isA<NSError>()]), ); }); test('didFailProvisionalNavigation', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didFailProvisionalNavigation: (WKWebView webView, NSError error) { argsCompleter.complete(<Object?>[webView, error]); }, ); WebKitFlutterApis.instance.navigationDelegate .didFailProvisionalNavigation( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, NSErrorData( code: 23, domain: 'Hello', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); expect( argsCompleter.future, completion(<Object?>[webView, isA<NSError>()]), ); }); test('webViewWebContentProcessDidTerminate', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, webViewWebContentProcessDidTerminate: (WKWebView webView) { argsCompleter.complete(<Object?>[webView]); }, ); WebKitFlutterApis.instance.navigationDelegate .webViewWebContentProcessDidTerminate( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, ); expect(argsCompleter.future, completion(<Object?>[webView])); }); test('didReceiveAuthenticationChallenge', () async { WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); const int credentialIdentifier = 3; final NSUrlCredential credential = NSUrlCredential.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( credential, credentialIdentifier, ); navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, didReceiveAuthenticationChallenge: ( WKWebView webView, NSUrlAuthenticationChallenge challenge, void Function( NSUrlSessionAuthChallengeDisposition disposition, NSUrlCredential? credential, ) completionHandler, ) { completionHandler( NSUrlSessionAuthChallengeDisposition.useCredential, credential, ); }, ); const int challengeIdentifier = 27; instanceManager.addHostCreatedInstance( NSUrlAuthenticationChallenge.detached( protectionSpace: NSUrlProtectionSpace.detached( host: null, realm: null, authenticationMethod: null, ), instanceManager: instanceManager, ), challengeIdentifier, ); final AuthenticationChallengeResponse response = await WebKitFlutterApis .instance.navigationDelegate .didReceiveAuthenticationChallenge( instanceManager.getIdentifier(navigationDelegate)!, instanceManager.getIdentifier(webView)!, challengeIdentifier, ); expect(response.disposition, NSUrlSessionAuthChallengeDisposition.useCredential); expect(response.credentialIdentifier, credentialIdentifier); }); }); group('WKWebView', () { late MockTestWKWebViewHostApi mockPlatformHostApi; late WKWebViewConfiguration webViewConfiguration; late WKWebView webView; late int webViewInstanceId; setUp(() { mockPlatformHostApi = MockTestWKWebViewHostApi(); TestWKWebViewHostApi.setup(mockPlatformHostApi); TestWKWebViewConfigurationHostApi.setup( MockTestWKWebViewConfigurationHostApi()); webViewConfiguration = WKWebViewConfiguration( instanceManager: instanceManager, ); webView = WKWebView( webViewConfiguration, instanceManager: instanceManager, ); webViewInstanceId = instanceManager.getIdentifier(webView)!; }); tearDown(() { TestWKWebViewHostApi.setup(null); TestWKWebViewConfigurationHostApi.setup(null); }); test('create', () async { verify(mockPlatformHostApi.create( instanceManager.getIdentifier(webView), instanceManager.getIdentifier( webViewConfiguration, ), )); }); test('setUIDelegate', () async { TestWKUIDelegateHostApi.setup(MockTestWKUIDelegateHostApi()); final WKUIDelegate uiDelegate = WKUIDelegate( instanceManager: instanceManager, ); await webView.setUIDelegate(uiDelegate); verify(mockPlatformHostApi.setUIDelegate( webViewInstanceId, instanceManager.getIdentifier(uiDelegate), )); TestWKUIDelegateHostApi.setup(null); }); test('setNavigationDelegate', () async { TestWKNavigationDelegateHostApi.setup( MockTestWKNavigationDelegateHostApi(), ); final WKNavigationDelegate navigationDelegate = WKNavigationDelegate( instanceManager: instanceManager, ); await webView.setNavigationDelegate(navigationDelegate); verify(mockPlatformHostApi.setNavigationDelegate( webViewInstanceId, instanceManager.getIdentifier(navigationDelegate), )); TestWKNavigationDelegateHostApi.setup(null); }); test('getUrl', () { when( mockPlatformHostApi.getUrl(webViewInstanceId), ).thenReturn('www.flutter.dev'); expect(webView.getUrl(), completion('www.flutter.dev')); }); test('getEstimatedProgress', () { when( mockPlatformHostApi.getEstimatedProgress(webViewInstanceId), ).thenReturn(54.5); expect(webView.getEstimatedProgress(), completion(54.5)); }); test('loadRequest', () { webView.loadRequest(const NSUrlRequest(url: 'www.flutter.dev')); verify(mockPlatformHostApi.loadRequest( webViewInstanceId, argThat(isA<NSUrlRequestData>()), )); }); test('loadHtmlString', () { webView.loadHtmlString('a', baseUrl: 'b'); verify(mockPlatformHostApi.loadHtmlString(webViewInstanceId, 'a', 'b')); }); test('loadFileUrl', () { webView.loadFileUrl('a', readAccessUrl: 'b'); verify(mockPlatformHostApi.loadFileUrl(webViewInstanceId, 'a', 'b')); }); test('loadFlutterAsset', () { webView.loadFlutterAsset('a'); verify(mockPlatformHostApi.loadFlutterAsset(webViewInstanceId, 'a')); }); test('canGoBack', () { when(mockPlatformHostApi.canGoBack(webViewInstanceId)).thenReturn(true); expect(webView.canGoBack(), completion(isTrue)); }); test('canGoForward', () { when(mockPlatformHostApi.canGoForward(webViewInstanceId)) .thenReturn(false); expect(webView.canGoForward(), completion(isFalse)); }); test('goBack', () { webView.goBack(); verify(mockPlatformHostApi.goBack(webViewInstanceId)); }); test('goForward', () { webView.goForward(); verify(mockPlatformHostApi.goForward(webViewInstanceId)); }); test('reload', () { webView.reload(); verify(mockPlatformHostApi.reload(webViewInstanceId)); }); test('getTitle', () { when(mockPlatformHostApi.getTitle(webViewInstanceId)) .thenReturn('MyTitle'); expect(webView.getTitle(), completion('MyTitle')); }); test('setAllowsBackForwardNavigationGestures', () { webView.setAllowsBackForwardNavigationGestures(false); verify(mockPlatformHostApi.setAllowsBackForwardNavigationGestures( webViewInstanceId, false, )); }); test('setCustomUserAgent', () { webView.setCustomUserAgent('hello'); verify(mockPlatformHostApi.setCustomUserAgent( webViewInstanceId, 'hello', )); }); test('getCustomUserAgent', () { const String userAgent = 'str'; when( mockPlatformHostApi.getCustomUserAgent(webViewInstanceId), ).thenReturn(userAgent); expect(webView.getCustomUserAgent(), completion(userAgent)); }); test('evaluateJavaScript', () { when(mockPlatformHostApi.evaluateJavaScript(webViewInstanceId, 'gogo')) .thenAnswer((_) => Future<String>.value('stopstop')); expect(webView.evaluateJavaScript('gogo'), completion('stopstop')); }); test('evaluateJavaScript returns NSError', () { when(mockPlatformHostApi.evaluateJavaScript(webViewInstanceId, 'gogo')) .thenThrow( PlatformException( code: '', details: NSErrorData( code: 0, domain: 'domain', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSLocalizedDescription: 'desc', }, ), ), ); expect( webView.evaluateJavaScript('gogo'), throwsA( isA<PlatformException>().having( (PlatformException exception) => exception.details, 'details', isA<NSError>(), ), ), ); }); }); group('WKUIDelegate', () { late MockTestWKUIDelegateHostApi mockPlatformHostApi; late WKUIDelegate uiDelegate; setUp(() async { mockPlatformHostApi = MockTestWKUIDelegateHostApi(); TestWKUIDelegateHostApi.setup(mockPlatformHostApi); uiDelegate = WKUIDelegate(instanceManager: instanceManager); }); tearDown(() { TestWKUIDelegateHostApi.setup(null); }); test('create', () async { verify(mockPlatformHostApi.create( instanceManager.getIdentifier(uiDelegate), )); }); test('onCreateWebView', () async { final Completer<List<Object?>> argsCompleter = Completer<List<Object?>>(); WebKitFlutterApis.instance = WebKitFlutterApis( instanceManager: instanceManager, ); uiDelegate = WKUIDelegate( instanceManager: instanceManager, onCreateWebView: ( WKWebView webView, WKWebViewConfiguration configuration, WKNavigationAction navigationAction, ) { argsCompleter.complete(<Object?>[ webView, configuration, navigationAction, ]); }, ); final WKWebView webView = WKWebView.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(webView, 2); final WKWebViewConfiguration configuration = WKWebViewConfiguration.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(configuration, 3); WebKitFlutterApis.instance.uiDelegate.onCreateWebView( instanceManager.getIdentifier(uiDelegate)!, 2, 3, WKNavigationActionData( request: NSUrlRequestData( url: 'url', allHttpHeaderFields: <String, String>{}, ), targetFrame: WKFrameInfoData( isMainFrame: false, request: NSUrlRequestData( url: 'url', allHttpHeaderFields: <String, String>{}, )), navigationType: WKNavigationType.linkActivated, ), ); expect( argsCompleter.future, completion(<Object?>[ webView, configuration, isA<WKNavigationAction>(), ]), ); }); test('requestMediaCapturePermission', () { final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int instanceIdentifier = 0; late final List<Object?> callbackParameters; final WKUIDelegate instance = WKUIDelegate.detached( requestMediaCapturePermission: ( WKUIDelegate instance, WKWebView webView, WKSecurityOrigin origin, WKFrameInfo frame, WKMediaCaptureType type, ) async { callbackParameters = <Object?>[ instance, webView, origin, frame, type, ]; return WKPermissionDecision.grant; }, instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance(instance, instanceIdentifier); final WKUIDelegateFlutterApiImpl flutterApi = WKUIDelegateFlutterApiImpl( instanceManager: instanceManager, ); final WKWebView webView = WKWebView.detached( instanceManager: instanceManager, ); const int webViewIdentifier = 42; instanceManager.addHostCreatedInstance( webView, webViewIdentifier, ); const WKSecurityOrigin origin = WKSecurityOrigin(host: 'host', port: 12, protocol: 'protocol'); const WKFrameInfo frame = WKFrameInfo(isMainFrame: false, request: NSUrlRequest(url: 'url')); const WKMediaCaptureType type = WKMediaCaptureType.microphone; flutterApi.requestMediaCapturePermission( instanceIdentifier, webViewIdentifier, WKSecurityOriginData( host: origin.host, port: origin.port, protocol: origin.protocol, ), WKFrameInfoData( isMainFrame: frame.isMainFrame, request: NSUrlRequestData( url: 'url', allHttpHeaderFields: <String, String>{})), WKMediaCaptureTypeData(value: type), ); expect(callbackParameters, <Object>[ instance, webView, isA<WKSecurityOrigin>(), isA<WKFrameInfo>(), type, ]); }); }); }); }
packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/web_kit/web_kit_test.dart/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/web_kit/web_kit_test.dart', 'repo_id': 'packages', 'token_count': 15606}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as path; import 'package:test/fake.dart'; import 'package:test/test.dart'; import 'package:xdg_directories/xdg_directories.dart' as xdg; void main() { final Map<String, String> fakeEnv = <String, String>{}; late Directory tmpDir; String testRootPath() { final String basePath = tmpDir.path; return Platform.isWindows // Strip the drive specifier when running tests on Windows since // environment variables use : as a path list separator. ? basePath.substring(basePath.indexOf(':') + 1) : basePath; } String testPath(String subdir) => path.join(testRootPath(), subdir); setUp(() { xdg.xdgProcessRunner = FakeProcessRunner(<String, String>{}, canRunExecutable: false); tmpDir = Directory.systemTemp.createTempSync('xdg_test'); fakeEnv.clear(); fakeEnv['HOME'] = testRootPath(); fakeEnv['XDG_CACHE_HOME'] = testPath('.test_cache'); fakeEnv['XDG_CONFIG_DIRS'] = testPath('etc/test_xdg'); fakeEnv['XDG_CONFIG_HOME'] = testPath('.test_config'); fakeEnv['XDG_DATA_DIRS'] = '${testPath('usr/local/test_share')}:${testPath('usr/test_share')}'; fakeEnv['XDG_DATA_HOME'] = testPath('.local/test_share'); fakeEnv['XDG_RUNTIME_DIR'] = testPath('.local/test_runtime'); Directory(fakeEnv['XDG_CONFIG_HOME']!).createSync(recursive: true); Directory(fakeEnv['XDG_CACHE_HOME']!).createSync(recursive: true); Directory(fakeEnv['XDG_DATA_HOME']!).createSync(recursive: true); Directory(fakeEnv['XDG_RUNTIME_DIR']!).createSync(recursive: true); File(path.join(fakeEnv['XDG_CONFIG_HOME']!, 'user-dirs.dirs')) .writeAsStringSync(r''' XDG_DESKTOP_DIR="$HOME/Desktop" XDG_DOCUMENTS_DIR="$HOME/Documents" XDG_DOWNLOAD_DIR="$HOME/Downloads" XDG_MUSIC_DIR="$HOME/Music" XDG_PICTURES_DIR="$HOME/Pictures" XDG_PUBLICSHARE_DIR="$HOME/Public" XDG_TEMPLATES_DIR="$HOME/Templates" XDG_VIDEOS_DIR="$HOME/Videos" '''); xdg.xdgEnvironmentOverride = (String key) => fakeEnv[key]; }); tearDown(() { tmpDir.deleteSync(recursive: true); // Stop overriding the environment accessor. xdg.xdgEnvironmentOverride = null; }); void expectDirList(List<Directory> values, List<String> expected) { final List<String> valueStr = values.map<String>((Directory directory) => directory.path).toList(); expect(valueStr, orderedEquals(expected)); } test('Default fallback values work', () { fakeEnv.clear(); fakeEnv['HOME'] = testRootPath(); expect(xdg.cacheHome.path, equals(testPath('.cache'))); expect(xdg.configHome.path, equals(testPath('.config'))); expect(xdg.dataHome.path, equals(testPath('.local/share'))); expect(xdg.runtimeDir, isNull); expectDirList(xdg.configDirs, <String>['/etc/xdg']); expectDirList(xdg.dataDirs, <String>['/usr/local/share', '/usr/share']); }); test('Values pull from environment', () { expect(xdg.cacheHome.path, equals(testPath('.test_cache'))); expect(xdg.configHome.path, equals(testPath('.test_config'))); expect(xdg.dataHome.path, equals(testPath('.local/test_share'))); expect(xdg.runtimeDir, isNotNull); expect(xdg.runtimeDir!.path, equals(testPath('.local/test_runtime'))); expectDirList(xdg.configDirs, <String>[testPath('etc/test_xdg')]); expectDirList(xdg.dataDirs, <String>[ testPath('usr/local/test_share'), testPath('usr/test_share'), ]); }); test('Can get userDirs', () { final Map<String, String> expected = <String, String>{ 'DESKTOP': testPath('Desktop'), 'DOCUMENTS': testPath('Documents'), 'DOWNLOAD': testPath('Downloads'), 'MUSIC': testPath('Music'), 'PICTURES': testPath('Pictures'), 'PUBLICSHARE': testPath('Public'), 'TEMPLATES': testPath('Templates'), 'VIDEOS': testPath('Videos'), }; xdg.xdgProcessRunner = FakeProcessRunner(expected); final Set<String> userDirs = xdg.getUserDirectoryNames(); expect(userDirs, equals(expected.keys.toSet())); for (final String key in userDirs) { expect(xdg.getUserDirectory(key)!.path, equals(expected[key]), reason: 'Path $key value not correct'); } }); test('Returns null when xdg-user-dir executable is not present', () { xdg.xdgProcessRunner = FakeProcessRunner( <String, String>{}, canRunExecutable: false, ); expect(xdg.getUserDirectory('DESKTOP'), isNull, reason: 'Found xdg user directory without access to xdg-user-dir'); }); test('Throws StateError when HOME not set', () { fakeEnv.clear(); expect(() { xdg.configHome; }, throwsStateError); }); } class FakeProcessRunner extends Fake implements xdg.XdgProcessRunner { FakeProcessRunner(this.expected, {this.canRunExecutable = true}); Map<String, String> expected; final bool canRunExecutable; @override ProcessResult runSync( String executable, List<String> arguments, { Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding, }) { if (!canRunExecutable) { throw ProcessException(executable, arguments, 'No such executable', 2); } return ProcessResult(0, 0, expected[arguments.first], ''); } }
packages/packages/xdg_directories/test/xdg_directories_test.dart/0
{'file_path': 'packages/packages/xdg_directories/test/xdg_directories_test.dart', 'repo_id': 'packages', 'token_count': 2105}
# Running the somes tests from these packages on an AVD with Android 34 causes failures. - webview_flutter
packages/script/configs/still_requires_api_33_avd.yaml/0
{'file_path': 'packages/script/configs/still_requires_api_33_avd.yaml', 'repo_id': 'packages', 'token_count': 27}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/repository_package.dart'; /// A command to run Dart's "fix" command on packages. class FixCommand extends PackageLoopingCommand { /// Creates a fix command instance. FixCommand( super.packagesDir, { super.processRunner, super.platform, }); @override final String name = 'fix'; @override final String description = 'Fixes packages using dart fix.\n\n' 'This command requires "dart" and "flutter" to be in your path, and ' 'assumes that dependencies have already been fetched (e.g., by running ' 'the analyze command first).'; @override final bool hasLongOutput = false; @override PackageLoopingType get packageLoopingType => PackageLoopingType.includeAllSubpackages; @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final int exitCode = await processRunner.runAndStream( 'dart', <String>['fix', '--apply'], workingDir: package.directory); if (exitCode != 0) { printError('Unable to automatically fix package.'); return PackageResult.fail(); } return PackageResult.success(); } }
packages/script/tool/lib/src/fix_command.dart/0
{'file_path': 'packages/script/tool/lib/src/fix_command.dart', 'repo_id': 'packages', 'token_count': 443}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/git_version_finder.dart'; import 'package:flutter_plugin_tools/src/common/package_state_utils.dart'; import 'package:test/fake.dart'; import 'package:test/test.dart'; import '../util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); }); group('checkPackageChangeState', () { test('reports version change needed for code changes', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_package/lib/plugin.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_package'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('handles trailing slash on package path', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_package/lib/plugin.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_package/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); expect(state.hasChangelogChange, false); }); test('does not flag version- and changelog-change-exempt changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/CHANGELOG.md', // Analysis. 'packages/a_plugin/example/android/lint-baseline.xml', // Tests. 'packages/a_plugin/example/android/src/androidTest/foo/bar/FooTest.java', 'packages/a_plugin/example/ios/RunnerTests/Foo.m', 'packages/a_plugin/example/ios/RunnerUITests/info.plist', // Pigeon input. 'packages/a_plugin/pigeons/messages.dart', // Test scripts. 'packages/a_plugin/run_tests.sh', 'packages/a_plugin/dart_test.yaml', // Tools. 'packages/a_plugin/tool/a_development_tool.dart', // Example build files. 'packages/a_plugin/example/android/build.gradle', 'packages/a_plugin/example/android/gradle/wrapper/gradle-wrapper.properties', 'packages/a_plugin/example/ios/Runner.xcodeproj/project.pbxproj', 'packages/a_plugin/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme', 'packages/a_plugin/example/linux/flutter/CMakeLists.txt', 'packages/a_plugin/example/macos/Podfile', 'packages/a_plugin/example/macos/Runner.xcodeproj/project.pbxproj', 'packages/a_plugin/example/macos/Runner.xcworkspace/contents.xcworkspacedata', 'packages/a_plugin/example/windows/CMakeLists.txt', 'packages/a_plugin/example/pubspec.yaml', // Pigeon platform tests, which have an unusual structure. 'packages/a_plugin/platform_tests/shared_test_plugin_code/lib/integration_tests.dart', 'packages/a_plugin/platform_tests/test_plugin/windows/test_plugin.cpp', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, false); expect(state.hasChangelogChange, true); }); test('only considers a root "tool" folder to be special', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/foo/tool/tool_thing.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example/lib/main.dart', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/lib/main.dart']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/lib/main.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example/main.dart', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/main.dart']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/main.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example readme.md', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/README.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example/example.md', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/example.md']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/example.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'requires a changelog change but no version change for ' 'lower-priority examples when example.md is present', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/example.md']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/lib/main.dart', 'packages/a_plugin/example/main.dart', 'packages/a_plugin/example/README.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, true); }); test( 'requires a changelog change but no version change for README.md when ' 'code example is present', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/lib/main.dart']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/README.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, true); }); test( 'does not requires changelog or version change for build.gradle ' 'test-dependency-only changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/android/build.gradle': <String>[ "- androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'", "- testImplementation 'junit:junit:4.10.0'", "+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'", "+ testImplementation 'junit:junit:4.13.2'", ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, false); }); test('requires changelog or version change for other build.gradle changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/android/build.gradle': <String>[ "- androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'", "- testImplementation 'junit:junit:4.10.0'", "+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'", "+ testImplementation 'junit:junit:4.13.2'", "- implementation 'com.google.android.gms:play-services-maps:18.0.0'", "+ implementation 'com.google.android.gms:play-services-maps:18.0.2'", ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'does not requires changelog or version change for ' 'non-doc-comment-only changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/a_plugin.dart', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/lib/a_plugin.dart': <String>[ '- // Old comment.', '+ // New comment.', '+ ', // Allow whitespace line changes as part of comment changes. ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, false); }); test('requires changelog or version change for doc comment changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/a_plugin.dart', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/lib/a_plugin.dart': <String>[ '- /// Old doc comment.', '+ /// New doc comment.', ] }); final PackageChangeState state = await checkPackageChangeState( package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git, ); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires changelog or version change for Dart code change', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/a_plugin.dart', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/lib/a_plugin.dart': <String>[ // Include inline comments to ensure the comment check doesn't have // false positives for lines that include comment changes but aren't // only comment changes. '- callOldMethod(); // inline comment', '+ callNewMethod(); // inline comment', ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'requires changelog or version change if build.gradle diffs cannot ' 'be checked', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'requires changelog or version change if build.gradle diffs cannot ' 'be determined', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/android/build.gradle': <String>[] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); }); } class FakeGitVersionFinder extends Fake implements GitVersionFinder { FakeGitVersionFinder(this.fileDiffs); final Map<String, List<String>> fileDiffs; @override Future<List<String>> getDiffContents({ String? targetPath, bool includeUncommitted = false, }) async { return fileDiffs[targetPath]!; } }
packages/script/tool/test/common/package_state_utils_test.dart/0
{'file_path': 'packages/script/tool/test/common/package_state_utils_test.dart', 'repo_id': 'packages', 'token_count': 6081}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/update_min_sdk_command.dart'; import 'package:test/test.dart'; import 'util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; late CommandRunner<void> runner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); final UpdateMinSdkCommand command = UpdateMinSdkCommand( packagesDir, ); runner = CommandRunner<void>( 'update_min_sdk_command', 'Test for update_min_sdk_command'); runner.addCommand(command); }); test('fails if --flutter-min is missing', () async { Error? commandError; await runCapturingPrint(runner, <String>[ 'update-min-sdk', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ArgumentError>()); }); test('updates Dart when only Dart is present, with manual range', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, dartConstraint: '>=3.0.0 <4.0.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; expect(dartVersion, '^3.1.0'); }); test('updates Dart when only Dart is present, with carrot', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, dartConstraint: '^3.0.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; expect(dartVersion, '^3.1.0'); }); test('does not update Dart if it is already higher', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, dartConstraint: '^3.2.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; expect(dartVersion, '^3.2.0'); }); test('updates both Dart and Flutter when both are present', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, isFlutter: true, dartConstraint: '>=3.0.0 <4.0.0', flutterConstraint: '>=3.10.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; final String flutterVersion = package.parsePubspec().environment?['flutter'].toString() ?? ''; expect(dartVersion, '^3.1.0'); expect(flutterVersion, '>=3.13.0'); }); test('does not update Flutter if it is already higher', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, isFlutter: true, dartConstraint: '^3.2.0', flutterConstraint: '>=3.16.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; final String flutterVersion = package.parsePubspec().environment?['flutter'].toString() ?? ''; expect(dartVersion, '^3.2.0'); expect(flutterVersion, '>=3.16.0'); }); }
packages/script/tool/test/update_min_sdk_command_test.dart/0
{'file_path': 'packages/script/tool/test/update_min_sdk_command_test.dart', 'repo_id': 'packages', 'token_count': 1558}
import 'dart:ui'; import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/palette.dart'; import 'package:flutter/material.dart' hide Image, Gradient; import 'game.dart'; class Background extends PositionComponent with HasGameRef<PadRacingGame>, HasPaint { Background() : super(size: PadRacingGame.trackSize, priority: 0); late Rect _backgroundRect; @override Future<void> onLoad() async { paint = BasicPalette.black.paint(); _backgroundRect = toRect(); } @override void render(Canvas canvas) { canvas.drawRect(_backgroundRect, paint); } }
padracing/lib/background.dart/0
{'file_path': 'padracing/lib/background.dart', 'repo_id': 'padracing', 'token_count': 209}
// Copyright (c) 2017, 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. import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import 'package:pana/pana.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart' as shelf; import 'package:shelf/shelf_io.dart'; import 'package:test/test.dart'; import 'golden_file.dart'; final _goldenDir = p.join('test', 'goldens', 'end2end'); final _pubDevUri = Uri.parse('https://pub.dartlang.org/'); void main() { late String tempDir; late PackageAnalyzer analyzer; http.Client? httpClient; late HttpServer httpServer; setUpAll(() async { tempDir = Directory.systemTemp .createTempSync('pana-test') .resolveSymbolicLinksSync(); final pubCacheDir = p.join(tempDir, 'pub-cache'); final goldenDirLastModified = await _detectGoldenLastModified(); Directory(pubCacheDir).createSync(); httpClient = http.Client(); httpServer = await _startLocalProxy( httpClient: httpClient, blockPublishAfter: goldenDirLastModified, ); analyzer = await PackageAnalyzer.create( pubCacheDir: pubCacheDir, pubHostedUrl: 'http://127.0.0.1:${httpServer.port}'); }); tearDownAll(() async { await httpServer.close(force: true); httpClient!.close(); Directory(tempDir).deleteSync(recursive: true); }); void _verifyPackage(String package, String version) { final filename = '$package-$version.json'; group('end2end: $package $version', () { Map<String, dynamic>? actualMap; setUpAll(() async { var summary = await analyzer.inspectPackage( package, version: version, options: InspectOptions( pubHostedUrl: 'http://127.0.0.1:${httpServer.port}', ), ); // Fixed version strings to reduce changes on each upgrades. assert(summary.runtimeInfo.panaVersion == packageVersion); final sdkVersion = summary.runtimeInfo.sdkVersion; final flutterDartVersion = summary.runtimeInfo.flutterInternalDartSdkVersion; summary = summary.change( runtimeInfo: PanaRuntimeInfo( panaVersion: '{{pana-version}}', sdkVersion: '{{sdk-version}}', flutterVersions: {}, )); // summary.toJson contains types which are not directly JSON-able // throwing it through `JSON.encode` does the trick final encoded = json.encode(summary); final updated = encoded .replaceAll( '"sdkVersion":"$sdkVersion"', '"sdkVersion":"{{sdk-version}}"') .replaceAll('The current Dart SDK version is $sdkVersion.', 'The current Dart SDK version is {{sdk-version}}.') .replaceAll(' support current Dart version $sdkVersion.', ' support current Dart version {{sdk-version}}.') .replaceAll( 'the Dart version used by the latest stable Flutter ($flutterDartVersion)', 'the Dart version used by the latest stable Flutter ({{flutter-dart-version}})') .replaceAll(RegExp('that was published [0-9]+ days ago'), 'that was published N days ago'); actualMap = json.decode(updated) as Map<String, dynamic>?; }); test('matches known good', () { void removeDependencyDetails(Map map) { if (map.containsKey('pkgResolution') && (map['pkgResolution'] as Map).containsKey('dependencies')) { final deps = (map['pkgResolution']['dependencies'] as List) .cast<Map<dynamic, dynamic>>(); for (final m in deps) { m.remove('resolved'); m.remove('available'); } } } // Reduce the time-invariability of the tests: resolved and available // versions may change over time or because of SDK version changes. removeDependencyDetails(actualMap!); final json = const JsonEncoder.withIndent(' ').convert(actualMap) + '\n'; // The tempdir creeps in to an error message. final jsonNoTempDir = json.replaceAll( RegExp(r'Error on line 5, column 1 of .*pubspec.yaml'), r'Error on line 5, column 1 of $TEMPDIR/pubspec.yaml'); expectMatchesGoldenFile(jsonNoTempDir, p.join(_goldenDir, filename)); }); test('Report matches known good', () { final jsonReport = actualMap!['report'] as Map<String, dynamic>?; if (jsonReport != null) { final report = Report.fromJson(jsonReport); final renderedSections = report.sections .map( (s) => '## ${s.grantedPoints}/${s.maxPoints} ${s.title}\n\n${s.summary}', ) .join('\n\n'); // For readability we output the report in its own file. expectMatchesGoldenFile( renderedSections, p.join(_goldenDir, '${filename}_report.md')); } }); test('Summary can round-trip', () { var summary = Summary.fromJson(actualMap!); var roundTrip = json.decode(json.encode(summary)); expect(roundTrip, actualMap); }); }, timeout: const Timeout.factor(2)); } // generic, cross-platform package _verifyPackage('async', '2.5.0'); // cross-platform package with platform-specific code _verifyPackage('http', '0.13.0'); // js-only package _verifyPackage('dnd', '2.0.0'); // flutter-only package _verifyPackage('url_launcher', '6.0.3'); // single-platform Flutter plugin without Dart files or assets _verifyPackage('nsd_android', '1.0.2'); // multi-level symlink _verifyPackage('audio_service', '0.17.0'); // mime_type 0.3.2 has no recognized LICENSE file _verifyPackage('mime_type', '0.3.2'); // no dart files, only assets (pre-2.12) _verifyPackage('bulma_min', '0.7.4'); // no dart files, only assets (post-2.12) _verifyPackage('lints', '1.0.0'); // debugging why platforms are not recognized // https://github.com/dart-lang/pana/issues/824 _verifyPackage('webdriver', '3.0.0'); // slightly old package _verifyPackage('sdp_transform', '0.2.0'); // really old package _verifyPackage('skiplist', '0.1.0'); // packages with bad content _verifyPackage('_dummy_pkg', '1.0.0-null-safety.1'); } Future<DateTime> _detectGoldenLastModified() async { final timestampFile = File(p.join(_goldenDir, '__timestamp.txt')); await timestampFile.parent.create(recursive: true); if (timestampFile.existsSync()) { final content = await timestampFile.readAsString(); return DateTime.parse(content.trim()); } else { final now = DateTime.now().toUtc(); await timestampFile.writeAsString('${now.toIso8601String()}\n'); return now; } } Future<HttpServer> _startLocalProxy({ required http.Client? httpClient, required DateTime blockPublishAfter, }) { return serve( (shelf.Request rq) async { final pubDevUri = _pubDevUri.replace(path: rq.requestedUri.path); final rs = await httpClient!.get(pubDevUri); final segments = rq.requestedUri.pathSegments; if (rs.statusCode == 200 && segments.length == 3 && segments[0] == 'api' && segments[1] == 'packages') { final content = json.decode(rs.body) as Map<String, dynamic>; final versions = (content['versions'] as List).cast<Map<String, dynamic>>(); versions.removeWhere((item) { final published = DateTime.parse(item['published'] as String); return published.isAfter(blockPublishAfter); }); return shelf.Response.ok(json.encode(content)); } return shelf.Response( rs.statusCode, body: gzip.encode(rs.bodyBytes), headers: { 'content-encoding': 'gzip', }, ); }, '127.0.0.1', 0, ); }
pana/test/end2end_test.dart/0
{'file_path': 'pana/test/end2end_test.dart', 'repo_id': 'pana', 'token_count': 3321}
import 'package:pana/src/license_detection/license_detector.dart'; import 'package:test/expect.dart'; import 'package:test/scaffolding.dart'; void main() { group('computeGranularity test:', () { test('Expect grnularity 3', () { expect(computeGranularity(0.75), 3); }); test('Expect granularity 10', () { expect(computeGranularity(0.95), 10); }); }); group('sortOnConfidence Tests', () { test('Expect -1 for confidence of A greater than B', () { final matchA = _dummyLicenseMatchInstance(0.9, 'matchA'); final matchB = _dummyLicenseMatchInstance(0.8, 'matchB'); expect(sortOnConfidence(matchA, matchB), -1); }); test('Expect 1 for confidence of matchA lesser than matchB', () { final matchA = _dummyLicenseMatchInstance(0.5, 'matchA'); final matchB = _dummyLicenseMatchInstance(1, 'matchB'); expect(sortOnConfidence(matchA, matchB), 1); }); test('Check token density when both have same matches', () { final matchA = _dummyLicenseMatchInstance(0.9, 'matchA', tokensClaimed: 1); final matchB = _dummyLicenseMatchInstance(0.9, 'matchB', tokensClaimed: 2); // Expect -1 as matchA has more number of tokens claimed and both the matches // have same instance of license detected. expect(sortOnConfidence(matchA, matchB), 1); }); }); group('removeDuplicateMatches tests: ', () { test('No duplicates present', () { final matches = [ _dummyLicenseMatchInstance(0.95, 'matchA'), _dummyLicenseMatchInstance(0.9, 'matchB'), ]; final expected = [ _dummyLicenseMatchInstance(0.95, 'matchA'), _dummyLicenseMatchInstance(0.9, 'matchB'), ]; final actual = removeDuplicates(matches); _testOutput(actual, expected); }); test('duplicates present', () { final matches = [ _dummyLicenseMatchInstance(0.95, 'matchA'), _dummyLicenseMatchInstance(0.9, 'matchB'), _dummyLicenseMatchInstance(0.8, 'matchA'), _dummyLicenseMatchInstance(0.75, 'matchB'), ]; final expected = [ _dummyLicenseMatchInstance(0.95, 'matchA'), _dummyLicenseMatchInstance(0.9, 'matchB'), ]; final actual = removeDuplicates(matches); _testOutput(actual, expected); }); }); group('removeoverLappingMatches tests:', () { _testOverLappingMatches( name: 'No overlaps', input: [ _dummyLicenseMatchInstance(1.0, 'matchA', start: 50, end: 100), _dummyLicenseMatchInstance(0.95, 'matchB', start: 10, end: 40), _dummyLicenseMatchInstance(0.65, 'matchC', start: 140, end: 200), ], expected: [ _dummyLicenseMatchInstance(1.0, 'matchA', start: 50, end: 100), _dummyLicenseMatchInstance(0.95, 'matchB', start: 10, end: 40), _dummyLicenseMatchInstance(0.65, 'matchC', start: 140, end: 200), ], ); _testOverLappingMatches( name: 'discard a match that contains other with in less token density', input: [ _dummyLicenseMatchInstance(1.0, 'matchA', start: 10, end: 70, tokensClaimed: 60), _dummyLicenseMatchInstance(0.7, 'matchB', start: 0, end: 100, tokensClaimed: 80), _dummyLicenseMatchInstance(0.65, 'matchC', start: 140, end: 200), ], expected: [ _dummyLicenseMatchInstance(1.0, 'matchA', start: 10, end: 70, tokensClaimed: 60), _dummyLicenseMatchInstance(0.65, 'matchC', start: 140, end: 200), ], ); _testOverLappingMatches( name: 'Does not discard match contained in other with less token density', input: [ _dummyLicenseMatchInstance(1, 'matchB', start: 5, end: 95, tokensClaimed: 75), _dummyLicenseMatchInstance(0.9, 'matchA', start: 0, end: 100, tokensClaimed: 90), _dummyLicenseMatchInstance(0.65, 'matchC', start: 140, end: 200), ], expected: [ _dummyLicenseMatchInstance(1, 'matchB', start: 5, end: 95, tokensClaimed: 75), _dummyLicenseMatchInstance(0.9, 'matchA', start: 0, end: 100, tokensClaimed: 90), _dummyLicenseMatchInstance(0.65, 'matchC', start: 140, end: 200), ], ); _testOverLappingMatches(name: 'Removes a overlapping match', input: [ _dummyLicenseMatchInstance( 1, 'matchA', start: 0, end: 100, tokensClaimed: 75, ), _dummyLicenseMatchInstance( 0.9, 'matchB', start: 200, end: 300, tokensClaimed: 90, ), _dummyLicenseMatchInstance( 0.8, 'matchC', start: 90, end: 180, ), ], expected: [ _dummyLicenseMatchInstance( 1, 'matchA', start: 0, end: 100, tokensClaimed: 75, ), _dummyLicenseMatchInstance( 0.9, 'matchB', start: 200, end: 300, tokensClaimed: 90, ), ]); }); group(('longestUnclaimedPercentage tests:'), () { _testUnclaimedPercentage( 'Expect 1.0 for no matches found', [], 1, 100, ); _testUnclaimedPercentage( 'Expect 0.5', [_dummyLicenseMatchInstance(0.95, '', tokensClaimed: 50)], 0.5, 100, ); _testUnclaimedPercentage( 'Expect 1,0', [ _dummyLicenseMatchInstance(0.95, '', tokensClaimed: 50), _dummyLicenseMatchInstance(0.9, '', tokensClaimed: 50), ], 0, 100, ); }); group('findLongestUnlaimedTokenRange', () { _testLongestUncliamedTokenRange( 'Expect the unknown license length for no match found', [], 100, 100, ); _testLongestUncliamedTokenRange( 'Longest unclaimed tokens at start of license', [ _dummyLicenseMatchInstance(0.9, '', start: 30, end: 60), _dummyLicenseMatchInstance(0.9, '', start: 70, end: 100), ], 30, 100, ); _testLongestUncliamedTokenRange( 'Longest unclaimed tokens at end of license', [ _dummyLicenseMatchInstance(0.9, '', start: 0, end: 80), ], 20, 100, ); _testLongestUncliamedTokenRange( 'Longest unclaimed range in between', [ _dummyLicenseMatchInstance(0.9, '', start: 30, end: 250), _dummyLicenseMatchInstance(0.89, '', start: 300, end: 550), _dummyLicenseMatchInstance(0.87, '', start: 710, end: 940), ], 160, 1000); }); } void _testUnclaimedPercentage( String name, List<LicenseMatch> result, double expected, int unknownTokensCount, ) { test(name, () { final actual = claculateUnclaimedTokenPercentage(result, unknownTokensCount); expect(actual, expected); }); } void _testLongestUncliamedTokenRange( String name, List<LicenseMatch> matches, int expected, int unknownTokens, ) { test(name, () { final actual = findLongestUnclaimedTokenRange(matches, unknownTokens); expect(actual, expected); }); } void _testOverLappingMatches({ required String name, required List<LicenseMatch> input, required List<LicenseMatch> expected, }) { test(name, () { final actual = removeOverLappingMatches(input); _testOutput(actual, expected); }); } void _testOutput(List<LicenseMatch> actual, List<LicenseMatch> expected) { expect(actual.length, expected.length); for (var i = 0; i < actual.length; i++) { expect(actual[i].identifier, expected[i].identifier); } } LicenseMatch _dummyLicenseMatchInstance( double confidence, String identifier, { Range? diffRange, int tokensClaimed = 5, int start = 0, int end = 3, }) { return LicenseMatch.createInstance( [], confidence, tokensClaimed, diffRange ?? dummyDiffRange, [], LicenseWithNGrams.parse( License.parse(identifier: identifier, content: 'take some text'), 3), Range(start, end)); } final dummyDiffRange = Range(2, 20);
pana/test/license_detector_test.dart/0
{'file_path': 'pana/test/license_detector_test.dart', 'repo_id': 'pana', 'token_count': 3481}
import 'package:flutter/material.dart'; import 'package:photo_view/photo_view.dart'; import 'package:photo_view_example/screens/common/app_bar.dart'; class DialogExample extends StatefulWidget { @override _DialogExampleState createState() => _DialogExampleState(); } class _DialogExampleState extends State<DialogExample> { void openDialog(BuildContext context) => showDialog( context: context, builder: (BuildContext context) { return Dialog( child: Container( child: PhotoView( tightMode: true, imageProvider: const AssetImage("assets/large-image.jpg"), heroAttributes: const PhotoViewHeroAttributes(tag: "someTag"), ), ), ); }, ); void openBottomSheet(BuildContext context) => showBottomSheet( context: context, backgroundColor: Colors.transparent, shape: const ContinuousRectangleBorder(), builder: (BuildContext context) { return PhotoViewGestureDetectorScope( axis: Axis.vertical, child: PhotoView( backgroundDecoration: BoxDecoration( color: Colors.black.withAlpha(240), ), imageProvider: const AssetImage("assets/large-image.jpg"), heroAttributes: const PhotoViewHeroAttributes(tag: "someTag"), ), ); }, ); void openBottomSheetModal(BuildContext context) => showModalBottomSheet( context: context, shape: const ContinuousRectangleBorder(), builder: (BuildContext context) { return SafeArea( child: Container( height: 250, child: PhotoViewGestureDetectorScope( axis: Axis.vertical, child: PhotoView( tightMode: true, imageProvider: const AssetImage("assets/large-image.jpg"), heroAttributes: const PhotoViewHeroAttributes(tag: "someTag"), ), ), ), ); }, ); @override Widget build(BuildContext context) { return ExampleAppBarLayout( title: "Dialogs integration", showGoBack: true, child: Builder( builder: (context) => Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( decoration: const BoxDecoration(color: Colors.red), ), ElevatedButton( child: const Text("Dialog"), onPressed: () => openDialog(context), ), const Divider(), ElevatedButton( child: const Text("Bottom sheet"), onPressed: () => openBottomSheet(context), ), const Divider(), ElevatedButton( child: const Text("Bottom sheet tight mode"), onPressed: () => openBottomSheetModal(context), ), ], ), ), ); } }
photo_view/example/lib/screens/examples/dialog_example.dart/0
{'file_path': 'photo_view/example/lib/screens/examples/dialog_example.dart', 'repo_id': 'photo_view', 'token_count': 1442}
import 'package:flutter/widgets.dart'; import 'package:photo_view/src/controller/photo_view_controller_delegate.dart' show PhotoViewControllerDelegate; mixin HitCornersDetector on PhotoViewControllerDelegate { HitCorners _hitCornersX() { final double childWidth = scaleBoundaries.childSize.width * scale; final double screenWidth = scaleBoundaries.outerSize.width; if (screenWidth >= childWidth) { return const HitCorners(true, true); } final x = -position.dx; final cornersX = this.cornersX(); return HitCorners(x <= cornersX.min, x >= cornersX.max); } HitCorners _hitCornersY() { final double childHeight = scaleBoundaries.childSize.height * scale; final double screenHeight = scaleBoundaries.outerSize.height; if (screenHeight >= childHeight) { return const HitCorners(true, true); } final y = -position.dy; final cornersY = this.cornersY(); return HitCorners(y <= cornersY.min, y >= cornersY.max); } bool _shouldMoveAxis( HitCorners hitCorners, double mainAxisMove, double crossAxisMove) { if (mainAxisMove == 0) { return false; } if (!hitCorners.hasHitAny) { return true; } final axisBlocked = hitCorners.hasHitBoth || (hitCorners.hasHitMax ? mainAxisMove > 0 : mainAxisMove < 0); if (axisBlocked) { return false; } return true; } bool _shouldMoveX(Offset move) { final hitCornersX = _hitCornersX(); final mainAxisMove = move.dx; final crossAxisMove = move.dy; return _shouldMoveAxis(hitCornersX, mainAxisMove, crossAxisMove); } bool _shouldMoveY(Offset move) { final hitCornersY = _hitCornersY(); final mainAxisMove = move.dy; final crossAxisMove = move.dx; return _shouldMoveAxis(hitCornersY, mainAxisMove, crossAxisMove); } bool shouldMove(Offset move, Axis mainAxis) { if (mainAxis == Axis.vertical) { return _shouldMoveY(move); } return _shouldMoveX(move); } } class HitCorners { const HitCorners(this.hasHitMin, this.hasHitMax); final bool hasHitMin; final bool hasHitMax; bool get hasHitAny => hasHitMin || hasHitMax; bool get hasHitBoth => hasHitMin && hasHitMax; }
photo_view/lib/src/core/photo_view_hit_corners.dart/0
{'file_path': 'photo_view/lib/src/core/photo_view_hit_corners.dart', 'repo_id': 'photo_view', 'token_count': 827}
name: platform_helper on: pull_request: paths: - "packages/platform_helper/**" - ".github/workflows/platform_helper.yaml" jobs: build: defaults: run: working-directory: packages/platform_helper runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: subosito/flutter-action@v1.5.0 with: channel: master - name: Install Dependencies run: flutter packages get - name: Format run: dart format --set-exit-if-changed lib test - name: Analyze run: flutter analyze lib test - name: Run tests chrome run: flutter test --platform chrome --no-pub --test-randomize-ordering-seed random - name: Run tests run: flutter test --no-pub --test-randomize-ordering-seed random
photobooth/.github/workflows/platform_helper.yaml/0
{'file_path': 'photobooth/.github/workflows/platform_helper.yaml', 'repo_id': 'photobooth', 'token_count': 345}
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:io_photobooth/external_links/external_links.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class FooterLink extends StatelessWidget { const FooterLink({ required this.text, required this.link, super.key, }); final String text; final String link; @override Widget build(BuildContext context) { return Clickable( onPressed: () => openLink(link), child: Text(text), ); } } class FooterMadeWithLink extends StatelessWidget { const FooterMadeWithLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); final defaultTextStyle = DefaultTextStyle.of(context); return RichText( textAlign: TextAlign.center, text: TextSpan( text: l10n.footerMadeWithText, style: theme.textTheme.bodyLarge?.copyWith( fontWeight: PhotoboothFontWeight.regular, color: defaultTextStyle.style.color, ), children: <TextSpan>[ TextSpan( text: l10n.footerMadeWithFlutterLinkText, recognizer: TapGestureRecognizer()..onTap = launchFlutterDevLink, style: const TextStyle( decoration: TextDecoration.underline, ), ), const TextSpan( text: ' & ', ), TextSpan( text: l10n.footerMadeWithFirebaseLinkText, recognizer: TapGestureRecognizer()..onTap = launchFirebaseLink, style: const TextStyle( decoration: TextDecoration.underline, ), ), ], ), ); } } class FooterGoogleIOLink extends StatelessWidget { const FooterGoogleIOLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: googleIOExternalLink, text: l10n.footerGoogleIOLinkText, ); } } class FooterCodelabLink extends StatelessWidget { const FooterCodelabLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://firebase.google.com/codelabs/firebase-get-to-know-flutter#0', text: l10n.footerCodelabLinkText, ); } } class FooterHowItsMadeLink extends StatelessWidget { const FooterHowItsMadeLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://medium.com/flutter/how-its-made-i-o-photo-booth-3b8355d35883', text: l10n.footerHowItsMadeLinkText, ); } } class FooterTermsOfServiceLink extends StatelessWidget { const FooterTermsOfServiceLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://policies.google.com/terms', text: l10n.footerTermsOfServiceLinkText, ); } } class FooterPrivacyPolicyLink extends StatelessWidget { const FooterPrivacyPolicyLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://policies.google.com/privacy', text: l10n.footerPrivacyPolicyLinkText, ); } }
photobooth/lib/footer/widgets/footer_link.dart/0
{'file_path': 'photobooth/lib/footer/widgets/footer_link.dart', 'repo_id': 'photobooth', 'token_count': 1474}
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class AnimatedDino extends AnimatedSprite { const AnimatedDino({super.key}) : super( loadingIndicatorColor: PhotoboothColors.orange, sprites: const Sprites( asset: 'dino_spritesheet.png', size: Size(648, 757), frames: 25, stepTime: 2 / 25, ), ); }
photobooth/lib/photobooth/widgets/animated_characters/animated_dino.dart/0
{'file_path': 'photobooth/lib/photobooth/widgets/animated_characters/animated_dino.dart', 'repo_id': 'photobooth', 'token_count': 205}
import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class ShareBottomSheet extends StatelessWidget { const ShareBottomSheet({ required this.image, super.key, }); final Uint8List image; @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return Container( margin: const EdgeInsets.only(top: 30), decoration: const BoxDecoration( color: PhotoboothColors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(12)), ), child: Stack( children: [ SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 24, vertical: 32, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 60), SharePreviewPhoto(image: image), const SizedBox(height: 60), SelectableText( l10n.shareDialogHeading, key: const Key('shareBottomSheet_heading'), style: theme.textTheme.displayLarge?.copyWith(fontSize: 32), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.shareDialogSubheading, key: const Key('shareBottomSheet_subheading'), style: theme.textTheme.displaySmall?.copyWith(fontSize: 18), textAlign: TextAlign.center, ), const SizedBox(height: 42), const Column( children: [ TwitterButton(), SizedBox(height: 18), FacebookButton(), ], ), const SizedBox(height: 42), const SocialMediaShareClarificationNote(), ], ), ), ), Positioned( right: 24, top: 24, child: IconButton( icon: const Icon( Icons.clear, color: PhotoboothColors.black54, ), onPressed: () => Navigator.of(context).pop(), ), ), ], ), ); } }
photobooth/lib/share/view/share_bottom_sheet.dart/0
{'file_path': 'photobooth/lib/share/view/share_bottom_sheet.dart', 'repo_id': 'photobooth', 'token_count': 1441}
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; /// Overlay displayed on top of the [SharePage] when [ShareBloc] is /// in the in progress state. class ShareProgressOverlay extends StatelessWidget { const ShareProgressOverlay({ super.key, }); @override Widget build(BuildContext context) { return BlocBuilder<ShareBloc, ShareState>( builder: (context, state) => state.uploadStatus.isLoading || (state.compositeStatus.isLoading && state.isUploadRequested) ? const _ShareProgressOverlay( key: Key('shareProgressOverlay_loading'), ) : const SizedBox(key: Key('shareProgressOverlay_nothing')), ); } } class _ShareProgressOverlay extends StatelessWidget { const _ShareProgressOverlay({super.key}); @override Widget build(BuildContext context) { return ColoredBox( color: PhotoboothColors.black.withOpacity(0.8), child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6), child: Center( child: ResponsiveLayoutBuilder( small: (_, __) => const _MobileShareProgressOverlay( key: Key('shareProgressOverlay_mobile'), ), large: (_, __) => const _DesktopShareProgressOverlay( key: Key('shareProgressOverlay_desktop'), ), ), ), ), ); } } class _DesktopShareProgressOverlay extends StatelessWidget { const _DesktopShareProgressOverlay({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const CircularProgressIndicator( color: PhotoboothColors.orange, ), const SizedBox(height: 28), Padding( padding: const EdgeInsets.symmetric(horizontal: 258), child: Text( l10n.sharePageProgressOverlayHeading, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ), const SizedBox(height: 14), Text( l10n.sharePageProgressOverlaySubheading, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ], ); } } class _MobileShareProgressOverlay extends StatelessWidget { const _MobileShareProgressOverlay({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const AppCircularProgressIndicator(), const SizedBox(height: 24), Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: Text( l10n.sharePageProgressOverlayHeading, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, fontSize: 32, ), textAlign: TextAlign.center, ), ), const SizedBox(height: 15), Text( l10n.sharePageProgressOverlaySubheading, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, fontSize: 18, ), textAlign: TextAlign.center, ), ], ); } }
photobooth/lib/share/widgets/share_progress_overlay.dart/0
{'file_path': 'photobooth/lib/share/widgets/share_progress_overlay.dart', 'repo_id': 'photobooth', 'token_count': 1662}
import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/stickers/stickers.dart'; class ClearStickersDialog extends StatelessWidget { const ClearStickersDialog({ super.key, }); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 30, vertical: 80, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( l10n.clearStickersDialogHeading, key: const Key('clearStickersDialog_heading'), style: theme.textTheme.displayLarge, textAlign: TextAlign.center, ), const SizedBox(height: 24), Text( l10n.clearStickersDialogSubheading, key: const Key('clearStickersDialog_subheading'), style: theme.textTheme.displaySmall, textAlign: TextAlign.center, ), const SizedBox(height: 48), const Wrap( alignment: WrapAlignment.center, spacing: 30, runSpacing: 15, children: [ ClearStickersCancelButton(), ClearStickersConfirmButton(), ], ), ], ), ), ); } }
photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_dialog.dart/0
{'file_path': 'photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_dialog.dart', 'repo_id': 'photobooth', 'token_count': 752}
include: package:very_good_analysis/analysis_options.yaml
photobooth/packages/authentication_repository/analysis_options.yaml/0
{'file_path': 'photobooth/packages/authentication_repository/analysis_options.yaml', 'repo_id': 'photobooth', 'token_count': 16}
include: package:very_good_analysis/analysis_options.yaml analyzer: errors: undefined_prefixed_name: ignore linter: rules: public_member_api_docs: false
photobooth/packages/camera/camera_web/analysis_options.yaml/0
{'file_path': 'photobooth/packages/camera/camera_web/analysis_options.yaml', 'repo_id': 'photobooth', 'token_count': 58}
@TestOn('!chrome') library; import 'package:flutter_test/flutter_test.dart'; import 'package:image_compositor/image_compositor.dart'; void main() { group('ImageCompositor', () { test('is unsupported in other platforms', () { final compositor = ImageCompositor(); expect( () => compositor.composite( data: '', width: 1, height: 1, layers: [], aspectRatio: 1, ), throwsUnsupportedError, ); }); }); }
photobooth/packages/image_compositor/test/io_image_compositor_test.dart/0
{'file_path': 'photobooth/packages/image_compositor/test/io_image_compositor_test.dart', 'repo_id': 'photobooth', 'token_count': 232}
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; /// {@template app_circular_progress_indicator} /// Circular progress indicator /// {@endtemplate} class AppCircularProgressIndicator extends StatelessWidget { /// {@macro app_circular_progress_indicator} const AppCircularProgressIndicator({ super.key, this.color = PhotoboothColors.orange, this.backgroundColor = PhotoboothColors.white, this.strokeWidth = 4.0, }); /// [Color] of the progress indicator final Color color; /// [Color] for the background final Color? backgroundColor; /// Optional stroke width of the progress indicator final double strokeWidth; @override Widget build(BuildContext context) { return CircularProgressIndicator( color: color, backgroundColor: backgroundColor, strokeWidth: strokeWidth, ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/app_circular_progress_indicator.dart/0
{'file_path': 'photobooth/packages/photobooth_ui/lib/src/widgets/app_circular_progress_indicator.dart', 'repo_id': 'photobooth', 'token_count': 280}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import '../helpers/helpers.dart'; class MockPlatformHelper extends Mock implements PlatformHelper {} void main() { late PlatformHelper platformHelper; group('showAppModal', () { setUp(() { platformHelper = MockPlatformHelper(); }); testWidgets('renders without platform helper injected', (tester) async { await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); testWidgets('shows portraitChild on mobile', (tester) async { when(() => platformHelper.isMobile).thenReturn(true); await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, platformHelper: platformHelper, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(find.text('portrait'), findsOneWidget); }); testWidgets('shows portraitChild sheet on portrait', (tester) async { when(() => platformHelper.isMobile).thenReturn(false); tester.setPortraitDisplaySize(); await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, platformHelper: platformHelper, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(find.text('portrait'), findsOneWidget); }); testWidgets('shows landscapeChild when landscape and no mobile', (tester) async { when(() => platformHelper.isMobile).thenReturn(false); tester.setLandscapeDisplaySize(); await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, platformHelper: platformHelper, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(find.text('landscape'), findsOneWidget); }); }); }
photobooth/packages/photobooth_ui/test/src/helpers/modal_helper_test.dart/0
{'file_path': 'photobooth/packages/photobooth_ui/test/src/helpers/modal_helper_test.dart', 'repo_id': 'photobooth', 'token_count': 1614}
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; class MockPlatformHelper extends Mock implements PlatformHelper {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final childKey = UniqueKey(); const size = Size(300, 300); final child = SizedBox(key: childKey, width: 100, height: 100); late PlatformHelper platformHelper; group('DraggableResizable', () { setUp(() { platformHelper = MockPlatformHelper(); when(() => platformHelper.isMobile).thenReturn(true); }); testWidgets('renders child by (default)', (tester) async { await tester.pumpWidget( MaterialApp(home: DraggableResizable(size: size, child: child)), ); expect(find.byKey(childKey), findsOneWidget); }); group('desktop', () { setUp(() { when(() => platformHelper.isMobile).thenReturn(false); }); testWidgets('renders child as draggable point', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_child_draggablePoint')), findsOneWidget, ); }); testWidgets('child is draggable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, size: size, child: child, ), ), ); final firstLocation = tester.getCenter( find.byKey(Key('draggableResizable_child_draggablePoint')), ); await tester.dragFrom(firstLocation, const Offset(200, 300)); await tester.pump(kThemeAnimationDuration); final destination = tester.getCenter( find.byKey(Key('draggableResizable_child_draggablePoint')), ); expect(firstLocation == destination, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'top left corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_topLeft_resizePoint')), findsOneWidget, ); }); testWidgets( 'top left corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_topLeft_resizePoint')), findsNothing, ); }); testWidgets('top left corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_topLeft_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx - 1, firstLocation.dy - 1), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'top right corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_topRight_resizePoint')), findsOneWidget, ); }); testWidgets( 'top right corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_topRight_resizePoint')), findsNothing, ); }); testWidgets('top right corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_topRight_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx + 10, firstLocation.dy + 10), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'bottom right corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomRight_resizePoint')), findsOneWidget, ); }); testWidgets( 'bottom right corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomRight_resizePoint')), findsNothing, ); }); testWidgets('bottom right corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_bottomRight_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx + 10, firstLocation.dy + 10), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'bottom left corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomLeft_resizePoint')), findsOneWidget, ); }); testWidgets( 'bottom left corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomLeft_resizePoint')), findsNothing, ); }); testWidgets('bottom left corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_bottomLeft_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx + 10, firstLocation.dy + 10), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets('delete button does not render when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, onDelete: () {}, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_delete_floatingActionIcon')), findsNothing, ); }); testWidgets( 'delete button does not render when ' 'there is delete callback', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_delete_floatingActionIcon')), findsNothing, ); }); testWidgets( 'delete button renders when canTransform is true and ' 'has delete callback', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, onDelete: () {}, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_delete_floatingActionIcon')), findsOneWidget, ); }); testWidgets('rotate anchor rotates asset', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ), ); final gestureDetector = tester.widget<GestureDetector>( find.byKey(Key('draggableResizable_rotate_gestureDetector')), ); gestureDetector.onScaleStart!( ScaleStartDetails(localFocalPoint: Offset(0, 0)), ); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(localFocalPoint: Offset(1, 1)), ); gestureDetector.onScaleEnd!(ScaleEndDetails()); await tester.pumpAndSettle(); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final transformFinder = find.ancestor( of: childFinder, matching: find.byType(Transform), ); final transformWidget = tester.widget<Transform>(transformFinder); expect( transformWidget.transform, isNot(equals(Matrix4.diagonal3Values(1, 1, 1))), ); }); testWidgets('tapping on rotate icon does nothing', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ), ); await tester.tap( find.byKey(Key('draggableResizable_rotate_floatingActionIcon')), ); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); }); group('mobile', () { setUp(() { when(() => platformHelper.isMobile).thenReturn(true); }); testWidgets('is draggable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final origin = tester.getCenter(childFinder); final offset = Offset(30, 30); await tester.drag(childFinder, offset); await tester.pumpAndSettle(); final destination = tester.getCenter(childFinder); expect(origin == destination, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets('is resizable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final gestureDetectorFinder = find.descendant( of: childFinder, matching: find.byType(GestureDetector), ); final gestureDetector = tester.widget<GestureDetector>(gestureDetectorFinder); gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(scale: 2, pointerCount: 2), ); await tester.pumpAndSettle(); expect(onUpdateCalls, isNotEmpty); }); testWidgets('is rotatable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final gestureDetectorFinder = find.descendant( of: childFinder, matching: find.byType(GestureDetector), ); final gestureDetector = tester.widget<GestureDetector>(gestureDetectorFinder); gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(rotation: 2, pointerCount: 2), ); await tester.pumpAndSettle(); final transformFinder = find.ancestor( of: childFinder, matching: find.byType(Transform), ); final transformWidget = tester.widget<Transform>(transformFinder); expect( transformWidget.transform, isNot(equals(Matrix4.diagonal3Values(1, 1, 1))), ); expect(onUpdateCalls, isNotEmpty); }); testWidgets('rotation is continuous', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final gestureDetectorFinder = find.descendant( of: childFinder, matching: find.byType(GestureDetector), ); final gestureDetector = tester.widget<GestureDetector>(gestureDetectorFinder); gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(rotation: 2, pointerCount: 2), ); await tester.pumpAndSettle(); final transformFinder = find.ancestor( of: childFinder, matching: find.byType(Transform), ); final transformA = tester.widget<Transform>(transformFinder).transform; gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(rotation: 2, pointerCount: 2), ); await tester.pumpAndSettle(); final transformB = tester.widget<Transform>(transformFinder).transform; expect(transformA, isNot(equals(transformB))); }); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/draggable_resizable_test.dart/0
{'file_path': 'photobooth/packages/photobooth_ui/test/src/widgets/draggable_resizable_test.dart', 'repo_id': 'photobooth', 'token_count': 10622}
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:mocktail/mocktail.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import 'package:photos_repository/photos_repository.dart'; class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState> implements PhotoboothBloc {} class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} class MockShareBloc extends MockBloc<ShareEvent, ShareState> implements ShareBloc {} class FakeShareEvent extends Fake implements ShareEvent {} class FakeShareState extends Fake implements ShareState {} class MockPhotosRepository extends Mock implements PhotosRepository {} extension PumpApp on WidgetTester { Future<void> pumpApp( Widget widget, { PhotosRepository? photosRepository, PhotoboothBloc? photoboothBloc, ShareBloc? shareBloc, }) async { registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); registerFallbackValue(FakeShareEvent()); registerFallbackValue(FakeShareState()); return mockNetworkImages(() async { return pumpWidget( RepositoryProvider.value( value: photosRepository ?? MockPhotosRepository(), child: MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc ?? MockPhotoboothBloc()), BlocProvider.value(value: shareBloc ?? MockShareBloc()), ], child: MaterialApp( localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ), ), ); }); } }
photobooth/test/helpers/pump_app.dart/0
{'file_path': 'photobooth/test/helpers/pump_app.dart', 'repo_id': 'photobooth', 'token_count': 838}
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/assets.g.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:mocktail/mocktail.dart'; import '../../../helpers/helpers.dart'; class FakeStickersEvent extends Fake implements StickersEvent {} class FakeStickersState extends Fake implements StickersState {} class MockStickersBloc extends MockBloc<StickersEvent, StickersState> implements StickersBloc {} class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState> implements PhotoboothBloc {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() { registerFallbackValue(FakeStickersEvent()); registerFallbackValue(FakeStickersState()); registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); }); group('StickersDrawerLayer', () { late PhotoboothBloc photoboothBloc; late StickersBloc stickersBloc; setUp(() { photoboothBloc = MockPhotoboothBloc(); stickersBloc = MockStickersBloc(); }); group('DesktopStickersDrawer', () { testWidgets( 'does not render DesktopStickersDrawer when ' 'drawer is inactive', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(), ); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); expect(find.byType(DesktopStickersDrawer), findsNothing); }); testWidgets( 'renders DesktopStickersDrawer when ' 'width greater than mobile breakpoint and it is drawer active', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setLandscapeDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); expect(find.byType(DesktopStickersDrawer), findsOneWidget); }); testWidgets( 'does not render DesktopStickersDrawer when ' 'width smaller than mobile and it is drawer active', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); expect(find.byType(DesktopStickersDrawer), findsNothing); }); testWidgets('adds StickerSelected when StickerChoice tapped', (tester) async { final sticker = Assets.props.first; when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setLandscapeDisplaySize(); when(() => photoboothBloc.state).thenReturn( PhotoboothState(stickers: [PhotoAsset(id: '0', asset: sticker)]), ); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); final stickerChoice = tester.widgetList<StickerChoice>(find.byType(StickerChoice)).first; stickerChoice.onPressed(); await tester.pump(); verify( () => photoboothBloc.add(PhotoStickerTapped(sticker: sticker)), ).called(1); verify(() => stickersBloc.add(StickersDrawerToggled())).called(1); }); testWidgets('adds StickersDrawerTabTapped when tab is selected', (tester) async { final sticker = Assets.props.first; when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setLandscapeDisplaySize(); when(() => photoboothBloc.state).thenReturn( PhotoboothState(stickers: [PhotoAsset(id: '0', asset: sticker)]), ); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); await tester.tap(find.byKey(Key('stickersTabs_eyewearTab'))); verify( () => stickersBloc.add(StickersDrawerTabTapped(index: 2)), ).called(1); }); testWidgets('can be closed', (tester) async { var onCloseTappedCallCount = 0; await tester.pumpApp( Scaffold( body: DesktopStickersDrawer( initialIndex: 0, onTabChanged: (_) {}, onStickerSelected: (_) {}, onCloseTapped: () => onCloseTappedCallCount++, bucket: PageStorageBucket(), ), ), ); await tester .ensureVisible(find.byKey(Key('stickersDrawer_close_iconButton'))); await tester.tap(find.byKey(Key('stickersDrawer_close_iconButton'))); await tester.pump(); expect(onCloseTappedCallCount, equals(1)); }); }); group('MobileStickersDrawer', () { testWidgets( 'opens MobileStickersDrawer when ' 'is active and width smaller than mobile breakpoint', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersDrawerLayer()), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); tester.widget<IconButton>(find.byType(IconButton)).onPressed!(); await tester.pumpAndSettle(); }); testWidgets( 'does not open MobileStickersDrawer when ' 'width greater than mobile breakpoint', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setLandscapeDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsNothing); tester.widget<IconButton>(find.byType(IconButton)).onPressed!(); await tester.pump(); }); testWidgets('can select stickers on MobileStickersDrawer', (tester) async { final sticker = Assets.props.first; whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersDrawerLayer()), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); final stickerChoice = tester.widgetList<StickerChoice>(find.byType(StickerChoice)).first; stickerChoice.onPressed(); await tester.pumpAndSettle(); verify( () => photoboothBloc.add(PhotoStickerTapped(sticker: sticker)), ).called(1); expect(find.byType(MobileStickersDrawer), findsNothing); }); testWidgets('can change tabs on MobileStickersDrawer', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold(body: StickersDrawerLayer()), ), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); final tabBar = tester.widget<TabBar>(find.byType(TabBar)); tabBar.onTap!(4); verify( () => stickersBloc.add(StickersDrawerTabTapped(index: 4)), ).called(1); final closeButtonFinder = find.byKey( Key('stickersDrawer_close_iconButton'), ); tester.widget<IconButton>(closeButtonFinder).onPressed!(); await tester.pumpAndSettle(); }); testWidgets('can close MobileStickersDrawer', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: StickersDrawerLayer(), ), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); final closeButtonFinder = find.byKey( Key('stickersDrawer_close_iconButton'), ); tester.widget<IconButton>(closeButtonFinder).onPressed!(); await tester.pumpAndSettle(); expect(find.byType(MobileStickersDrawer), findsNothing); verify(() => stickersBloc.add(StickersDrawerToggled())).called(1); }); }); }); }
photobooth/test/stickers/widgets/stickers_drawer_layer/stickers_drawer_layer_test.dart/0
{'file_path': 'photobooth/test/stickers/widgets/stickers_drawer_layer/stickers_drawer_layer_test.dart', 'repo_id': 'photobooth', 'token_count': 4798}
name: pinball_flame concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: push: paths: - "packages/pinball_flame/**" - ".github/workflows/pinball_flame.yaml" pull_request: paths: - "packages/pinball_flame/**" - ".github/workflows/pinball_flame.yaml" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: working_directory: packages/pinball_flame coverage_excludes: "lib/gen/*.dart" test_optimization: false
pinball/.github/workflows/pinball_flame.yaml/0
{'file_path': 'pinball/.github/workflows/pinball_flame.yaml', 'repo_id': 'pinball', 'token_count': 233}
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:platform_helper/platform_helper.dart'; /// Updates the [ArcadeBackground] and launch [Ball] to reflect character /// selections. class CharacterSelectionBehavior extends Component with FlameBlocListenable<CharacterThemeCubit, CharacterThemeState>, HasGameRef { @override void onNewState(CharacterThemeState state) { if (!readProvider<PlatformHelper>().isMobile) { gameRef .descendants() .whereType<ArcadeBackground>() .single .bloc .onCharacterSelected(state.characterTheme); } gameRef .descendants() .whereType<Ball>() .single .bloc .onCharacterSelected(state.characterTheme); } }
pinball/lib/game/behaviors/character_selection_behavior.dart/0
{'file_path': 'pinball/lib/game/behaviors/character_selection_behavior.dart', 'repo_id': 'pinball', 'token_count': 380}
import 'dart:async'; import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:pinball/game/components/backbox/bloc/backbox_bloc.dart'; import 'package:pinball/game/components/backbox/displays/displays.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' hide Assets; import 'package:pinball_ui/pinball_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:share_repository/share_repository.dart'; /// {@template backbox} /// The [Backbox] of the pinball machine. /// {@endtemplate} class Backbox extends PositionComponent with ZIndex, HasGameRef { /// {@macro backbox} Backbox({ required LeaderboardRepository leaderboardRepository, required ShareRepository shareRepository, required List<LeaderboardEntryData>? entries, }) : _bloc = BackboxBloc( leaderboardRepository: leaderboardRepository, initialEntries: entries, ), _shareRepository = shareRepository; /// {@macro backbox} @visibleForTesting Backbox.test({ required BackboxBloc bloc, required ShareRepository shareRepository, }) : _bloc = bloc, _shareRepository = shareRepository; final ShareRepository _shareRepository; late final Component _display; final BackboxBloc _bloc; late StreamSubscription<BackboxState> _subscription; @override Future<void> onLoad() async { position = Vector2(0, -87); anchor = Anchor.bottomCenter; zIndex = ZIndexes.backbox; await add(_BackboxSpriteComponent()); await add(_display = Component()); _build(_bloc.state); _subscription = _bloc.stream.listen((state) { _display.children.removeWhere((_) => true); _build(state); }); } @override void onRemove() { super.onRemove(); _subscription.cancel(); } void _build(BackboxState state) { if (state is LoadingState) { _display.add(LoadingDisplay()); } else if (state is LeaderboardSuccessState) { _display.add(LeaderboardDisplay(entries: state.entries)); } else if (state is LeaderboardFailureState) { _display.add(LeaderboardFailureDisplay()); } else if (state is InitialsFormState) { if (readProvider<PlatformHelper>().isMobile) { gameRef.overlays.add(PinballGame.mobileControlsOverlay); } _display.add( InitialsInputDisplay( score: state.score, characterIconPath: state.character.leaderboardIcon.keyName, onSubmit: (initials) { _bloc.add( PlayerInitialsSubmitted( score: state.score, initials: initials, character: state.character, ), ); }, ), ); } else if (state is InitialsSuccessState) { gameRef.overlays.remove(PinballGame.mobileControlsOverlay); _display.add( GameOverInfoDisplay( onShare: () { _bloc.add(ShareScoreRequested(score: state.score)); }, ), ); } else if (state is ShareState) { _display.add( ShareDisplay( onShare: (platform) { final message = readProvider<AppLocalizations>() .iGotScoreAtPinball(state.score.formatScore()); final url = _shareRepository.shareText( value: message, platform: platform, ); openLink(url); }, ), ); } else if (state is InitialsFailureState) { _display.add( InitialsSubmissionFailureDisplay( onDismissed: () { _bloc.add( PlayerInitialsRequested( score: state.score, character: state.character, ), ); }, ), ); } } /// Puts [InitialsInputDisplay] on the [Backbox]. void requestInitials({ required int score, required CharacterTheme character, }) { _bloc.add( PlayerInitialsRequested( score: score, character: character, ), ); } } class _BackboxSpriteComponent extends SpriteComponent with HasGameRef { _BackboxSpriteComponent() : super(anchor: Anchor.bottomCenter); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.backbox.marquee.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 20; } }
pinball/lib/game/components/backbox/backbox.dart/0
{'file_path': 'pinball/lib/game/components/backbox/backbox.dart', 'repo_id': 'pinball', 'token_count': 1980}
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Adds a [GameBonus.dinoChomp] when a [Ball] is chomped by the [ChromeDino]. class ChromeDinoBonusBehavior extends Component with ParentIsA<DinoDesert>, FlameBlocReader<GameBloc, GameState> { @override void onMount() { super.onMount(); final chromeDino = parent.firstChild<ChromeDino>()!; chromeDino.bloc.stream.listen((state) { final listenWhen = state.status == ChromeDinoStatus.chomping; if (!listenWhen) return; bloc.add(const BonusActivated(GameBonus.dinoChomp)); }); } }
pinball/lib/game/components/dino_desert/behaviors/chrome_dino_bonus_behavior.dart/0
{'file_path': 'pinball/lib/game/components/dino_desert/behaviors/chrome_dino_bonus_behavior.dart', 'repo_id': 'pinball', 'token_count': 284}
export 'multipliers_behavior.dart';
pinball/lib/game/components/multipliers/behaviors/behaviors.dart/0
{'file_path': 'pinball/lib/game/components/multipliers/behaviors/behaviors.dart', 'repo_id': 'pinball', 'token_count': 11}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template replay_button_overlay} /// [Widget] that renders the button responsible for restarting the game. /// {@endtemplate} class ReplayButtonOverlay extends StatelessWidget { /// {@macro replay_button_overlay} const ReplayButtonOverlay({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return PinballButton( text: l10n.replay, onTap: () { context.read<GameBloc>().add(const GameStarted()); context.read<StartGameBloc>().add(const ReplayTapped()); }, ); } }
pinball/lib/game/view/widgets/replay_button_overlay.dart/0
{'file_path': 'pinball/lib/game/view/widgets/replay_button_overlay.dart', 'repo_id': 'pinball', 'token_count': 315}
part of 'character_theme_cubit.dart'; class CharacterThemeState extends Equatable { const CharacterThemeState(this.characterTheme); const CharacterThemeState.initial() : characterTheme = const DashTheme(); final CharacterTheme characterTheme; bool get isSparkySelected => characterTheme == const SparkyTheme(); bool get isDashSelected => characterTheme == const DashTheme(); bool get isAndroidSelected => characterTheme == const AndroidTheme(); bool get isDinoSelected => characterTheme == const DinoTheme(); @override List<Object> get props => [characterTheme]; }
pinball/lib/select_character/cubit/character_theme_state.dart/0
{'file_path': 'pinball/lib/select_character/cubit/character_theme_state.dart', 'repo_id': 'pinball', 'token_count': 150}
import 'package:authentication_repository/authentication_repository.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; class _MockFirebaseAuth extends Mock implements FirebaseAuth {} class _MockUserCredential extends Mock implements UserCredential {} void main() { late FirebaseAuth firebaseAuth; late UserCredential userCredential; late AuthenticationRepository authenticationRepository; group('AuthenticationRepository', () { setUp(() { firebaseAuth = _MockFirebaseAuth(); userCredential = _MockUserCredential(); authenticationRepository = AuthenticationRepository(firebaseAuth); }); group('authenticateAnonymously', () { test('completes if no exception is thrown', () async { when(() => firebaseAuth.signInAnonymously()) .thenAnswer((_) async => userCredential); await authenticationRepository.authenticateAnonymously(); verify(() => firebaseAuth.signInAnonymously()).called(1); }); test('throws AuthenticationException when firebase auth fails', () async { when(() => firebaseAuth.signInAnonymously()) .thenThrow(Exception('oops')); expect( () => authenticationRepository.authenticateAnonymously(), throwsA(isA<AuthenticationException>()), ); }); }); }); }
pinball/packages/authentication_repository/test/src/authentication_repository_test.dart/0
{'file_path': 'pinball/packages/authentication_repository/test/src/authentication_repository_test.dart', 'repo_id': 'pinball', 'token_count': 503}
export 'exceptions.dart'; export 'leaderboard_entry_data.dart';
pinball/packages/leaderboard_repository/lib/src/models/models.dart/0
{'file_path': 'pinball/packages/leaderboard_repository/lib/src/models/models.dart', 'repo_id': 'pinball', 'token_count': 22}
import 'package:bloc/bloc.dart'; part 'android_bumper_state.dart'; class AndroidBumperCubit extends Cubit<AndroidBumperState> { AndroidBumperCubit() : super(AndroidBumperState.lit); void onBallContacted() { emit(AndroidBumperState.dimmed); } void onBlinked() { emit(AndroidBumperState.lit); } }
pinball/packages/pinball_components/lib/src/components/android_bumper/cubit/android_bumper_cubit.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/android_bumper/cubit/android_bumper_cubit.dart', 'repo_id': 'pinball', 'token_count': 117}
part of 'ball_cubit.dart'; class BallState extends Equatable { const BallState({required this.characterTheme}); const BallState.initial() : this(characterTheme: const DashTheme()); final CharacterTheme characterTheme; @override List<Object> get props => [characterTheme]; }
pinball/packages/pinball_components/lib/src/components/ball/cubit/ball_state.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/ball/cubit/ball_state.dart', 'repo_id': 'pinball', 'token_count': 80}
export 'android_animatronic/android_animatronic.dart'; export 'android_bumper/android_bumper.dart'; export 'android_spaceship/android_spaceship.dart'; export 'arcade_background/arcade_background.dart'; export 'arrow_icon.dart'; export 'ball/ball.dart'; export 'baseboard.dart'; export 'board_background_sprite_component.dart'; export 'board_dimensions.dart'; export 'board_side.dart'; export 'boundaries.dart'; export 'camera_zoom.dart'; export 'chrome_dino/chrome_dino.dart'; export 'dash_animatronic.dart'; export 'dash_bumper/dash_bumper.dart'; export 'dino_walls.dart'; export 'error_component.dart'; export 'flapper/flapper.dart'; export 'flipper/flipper.dart'; export 'google_letter.dart'; export 'google_rollover/google_rollover.dart'; export 'google_word/google_word.dart'; export 'initial_position.dart'; export 'joint_anchor.dart'; export 'kicker/kicker.dart'; export 'launch_ramp.dart'; export 'layer_sensor/layer_sensor.dart'; export 'multiball/multiball.dart'; export 'multiplier/multiplier.dart'; export 'plunger/plunger.dart'; export 'rocket.dart'; export 'score_component/score_component.dart'; export 'signpost/signpost.dart'; export 'skill_shot/skill_shot.dart'; export 'slingshot.dart'; export 'spaceship_rail.dart'; export 'spaceship_ramp/spaceship_ramp.dart'; export 'sparky_animatronic.dart'; export 'sparky_bumper/sparky_bumper.dart'; export 'sparky_computer/sparky_computer.dart'; export 'z_indexes.dart';
pinball/packages/pinball_components/lib/src/components/components.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/components.dart', 'repo_id': 'pinball', 'token_count': 537}
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class FlipperNoiseBehavior extends Component with FlameBlocListenable<FlipperCubit, FlipperState>, FlameBlocReader<FlipperCubit, FlipperState> { @override void onNewState(FlipperState state) { super.onNewState(state); if (bloc.state.isMovingUp) { readProvider<PinballAudioPlayer>().play(PinballAudio.flipper); } } }
pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_noise_behavior.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_noise_behavior.dart', 'repo_id': 'pinball', 'token_count': 232}
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class KickerBallContactBehavior extends ContactBehavior<Kicker> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; parent.bloc.onBallContacted(); } }
pinball/packages/pinball_components/lib/src/components/kicker/behaviors/kicker_ball_contact_behavior.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/kicker/behaviors/kicker_ball_contact_behavior.dart', 'repo_id': 'pinball', 'token_count': 139}
import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/src/components/multiplier/cubit/multiplier_cubit.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/multiplier_cubit.dart'; /// {@template multiplier} /// Backlit multiplier decal displayed on the board. /// {@endtemplate} class Multiplier extends Component { /// {@macro multiplier} Multiplier._({ required MultiplierValue value, required Vector2 position, required double angle, required this.bloc, }) : _value = value, _position = position, _angle = angle, super(); /// {@macro multiplier} Multiplier.x2({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x2, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x2), ); /// {@macro multiplier} Multiplier.x3({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x3, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x3), ); /// {@macro multiplier} Multiplier.x4({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x4, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x4), ); /// {@macro multiplier} Multiplier.x5({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x5, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x5), ); /// {@macro multiplier} Multiplier.x6({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x6, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x6), ); /// Creates a [Multiplier] without any children. /// /// This can be used for testing [Multiplier]'s behaviors in isolation. @visibleForTesting Multiplier.test({ required MultiplierValue value, required this.bloc, }) : _value = value, _position = Vector2.zero(), _angle = 0; final MultiplierCubit bloc; final MultiplierValue _value; final Vector2 _position; final double _angle; late final MultiplierSpriteGroupComponent _sprite; @override void onRemove() { bloc.close(); super.onRemove(); } @override Future<void> onLoad() async { await super.onLoad(); _sprite = MultiplierSpriteGroupComponent( position: _position, litAssetPath: _value.litAssetPath, dimmedAssetPath: _value.dimmedAssetPath, angle: _angle, current: bloc.state, ); await add(_sprite); } } /// Available multiplier values. enum MultiplierValue { x2, x3, x4, x5, x6, } extension on MultiplierValue { String get litAssetPath { switch (this) { case MultiplierValue.x2: return Assets.images.multiplier.x2.lit.keyName; case MultiplierValue.x3: return Assets.images.multiplier.x3.lit.keyName; case MultiplierValue.x4: return Assets.images.multiplier.x4.lit.keyName; case MultiplierValue.x5: return Assets.images.multiplier.x5.lit.keyName; case MultiplierValue.x6: return Assets.images.multiplier.x6.lit.keyName; } } String get dimmedAssetPath { switch (this) { case MultiplierValue.x2: return Assets.images.multiplier.x2.dimmed.keyName; case MultiplierValue.x3: return Assets.images.multiplier.x3.dimmed.keyName; case MultiplierValue.x4: return Assets.images.multiplier.x4.dimmed.keyName; case MultiplierValue.x5: return Assets.images.multiplier.x5.dimmed.keyName; case MultiplierValue.x6: return Assets.images.multiplier.x6.dimmed.keyName; } } } /// {@template multiplier_sprite_group_component} /// A [SpriteGroupComponent] for a [Multiplier] with lit and dimmed states. /// {@endtemplate} @visibleForTesting class MultiplierSpriteGroupComponent extends SpriteGroupComponent<MultiplierSpriteState> with HasGameRef, ParentIsA<Multiplier> { /// {@macro multiplier_sprite_group_component} MultiplierSpriteGroupComponent({ required Vector2 position, required String litAssetPath, required String dimmedAssetPath, required double angle, required MultiplierState current, }) : _litAssetPath = litAssetPath, _dimmedAssetPath = dimmedAssetPath, super( anchor: Anchor.center, position: position, angle: angle, current: current.spriteState, ); final String _litAssetPath; final String _dimmedAssetPath; @override Future<void> onLoad() async { await super.onLoad(); parent.bloc.stream.listen((state) => current = state.spriteState); final sprites = { MultiplierSpriteState.lit: Sprite(gameRef.images.fromCache(_litAssetPath)), MultiplierSpriteState.dimmed: Sprite(gameRef.images.fromCache(_dimmedAssetPath)), }; this.sprites = sprites; size = sprites[current]!.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/multiplier/multiplier.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/multiplier/multiplier.dart', 'repo_id': 'pinball', 'token_count': 2177}
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/signpost_cubit.dart'; /// {@template signpost} /// A sign, found in the Flutter Forest. /// /// Lights up a new sign whenever all three [DashBumper]s are hit. /// {@endtemplate} class Signpost extends BodyComponent with InitialPosition { /// {@macro signpost} Signpost({ Iterable<Component>? children, }) : super( renderBody: false, children: [ _SignpostSpriteComponent(), ...?children, ], ); @override Future<void> onLoad() async { await super.onLoad(); await add( FlameBlocListener<DashBumpersCubit, DashBumpersState>( listenWhen: (_, state) => state.isFullyActivated, onNewState: (_) { readBloc<SignpostCubit, SignpostState>().onProgressed(); readBloc<DashBumpersCubit, DashBumpersState>().onReset(); }, ), ); } @override Body createBody() { final shape = CircleShape()..radius = 0.25; final bodyDef = BodyDef( position: initialPosition, ); return world.createBody(bodyDef)..createFixtureFromShape(shape); } } class _SignpostSpriteComponent extends SpriteGroupComponent<SignpostState> with HasGameRef, FlameBlocListenable<SignpostCubit, SignpostState> { _SignpostSpriteComponent() : super( anchor: Anchor.bottomCenter, position: Vector2(0.65, 0.45), ); @override void onNewState(SignpostState state) => current = state; @override Future<void> onLoad() async { await super.onLoad(); final sprites = <SignpostState, Sprite>{}; this.sprites = sprites; for (final spriteState in SignpostState.values) { sprites[spriteState] = Sprite( gameRef.images.fromCache(spriteState.path), ); } current = SignpostState.inactive; size = sprites[current]!.originalSize / 10; } } extension on SignpostState { String get path { switch (this) { case SignpostState.inactive: return Assets.images.signpost.inactive.keyName; case SignpostState.active1: return Assets.images.signpost.active1.keyName; case SignpostState.active2: return Assets.images.signpost.active2.keyName; case SignpostState.active3: return Assets.images.signpost.active3.keyName; } } }
pinball/packages/pinball_components/lib/src/components/signpost/signpost.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/signpost/signpost.dart', 'repo_id': 'pinball', 'token_count': 1011}
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/android_acres/android_bumper_a_game.dart'; import 'package:sandbox/stories/android_acres/android_bumper_b_game.dart'; import 'package:sandbox/stories/android_acres/android_bumper_cow_game.dart'; import 'package:sandbox/stories/android_acres/android_spaceship_game.dart'; import 'package:sandbox/stories/android_acres/spaceship_rail_game.dart'; import 'package:sandbox/stories/android_acres/spaceship_ramp_game.dart'; void addAndroidAcresStories(Dashbook dashbook) { dashbook.storiesOf('Android Acres') ..addGame( title: 'Android Bumper A', description: AndroidBumperAGame.description, gameBuilder: (_) => AndroidBumperAGame(), ) ..addGame( title: 'Android Bumper B', description: AndroidBumperBGame.description, gameBuilder: (_) => AndroidBumperBGame(), ) ..addGame( title: 'Android Bumper Cow', description: AndroidBumperCowGame.description, gameBuilder: (_) => AndroidBumperCowGame(), ) ..addGame( title: 'Android Spaceship', description: AndroidSpaceshipGame.description, gameBuilder: (_) => AndroidSpaceshipGame(), ) ..addGame( title: 'Spaceship Rail', description: SpaceshipRailGame.description, gameBuilder: (_) => SpaceshipRailGame(), ) ..addGame( title: 'Spaceship Ramp', description: SpaceshipRampGame.description, gameBuilder: (_) => SpaceshipRampGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/android_acres/stories.dart/0
{'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/android_acres/stories.dart', 'repo_id': 'pinball', 'token_count': 582}
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/dino_desert/chrome_dino_game.dart'; import 'package:sandbox/stories/dino_desert/dino_walls_game.dart'; import 'package:sandbox/stories/dino_desert/slingshots_game.dart'; void addDinoDesertStories(Dashbook dashbook) { dashbook.storiesOf('Dino Desert') ..addGame( title: 'Chrome Dino', description: ChromeDinoGame.description, gameBuilder: (_) => ChromeDinoGame(), ) ..addGame( title: 'Dino Walls', description: DinoWallsGame.description, gameBuilder: (_) => DinoWallsGame(), ) ..addGame( title: 'Slingshots', description: SlingshotsGame.description, gameBuilder: (_) => SlingshotsGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/stories.dart/0
{'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/stories.dart', 'repo_id': 'pinball', 'token_count': 312}
import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class MultiballGame extends BallGame with KeyboardEvents { MultiballGame() : super( imagesFileNames: [ Assets.images.multiball.lit.keyName, Assets.images.multiball.dimmed.keyName, ], ); static const description = ''' Shows how the Multiball are rendered. - Tap anywhere on the screen to spawn a ball into the game. - Press space bar to animate multiballs. '''; final List<Multiball> multiballs = [ Multiball.a(), Multiball.b(), Multiball.c(), Multiball.d(), ]; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); await addAll(multiballs); await traceAllBodies(); } @override KeyEventResult onKeyEvent( RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed, ) { if (event is RawKeyDownEvent && event.logicalKey == LogicalKeyboardKey.space) { for (final multiball in multiballs) { multiball.bloc.onBlink(); } return KeyEventResult.handled; } return KeyEventResult.ignored; } }
pinball/packages/pinball_components/sandbox/lib/stories/multiball/multiball_game.dart/0
{'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/multiball/multiball_game.dart', 'repo_id': 'pinball', 'token_count': 539}
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group( 'ArcadeBackgroundCubit', () { blocTest<ArcadeBackgroundCubit, ArcadeBackgroundState>( 'onCharacterSelected emits new theme', build: ArcadeBackgroundCubit.new, act: (bloc) => bloc.onCharacterSelected(const DinoTheme()), expect: () => [ const ArcadeBackgroundState( characterTheme: DinoTheme(), ), ], ); }, ); }
pinball/packages/pinball_components/test/src/components/arcade_background/cubit/arcade_background_cubit_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/arcade_background/cubit/arcade_background_cubit_test.dart', 'repo_id': 'pinball', 'token_count': 262}
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import '../../helpers/helpers.dart'; void main() { group('CameraZoom', () { final tester = FlameTester(TestGame.new); tester.testGameWidget( 'renders correctly', setUp: (game, tester) async { game.camera.followVector2(Vector2.zero()); game.camera.zoom = 10; final sprite = await game.loadSprite( Assets.images.signpost.inactive.keyName, ); await game.add( SpriteComponent( sprite: sprite, size: Vector2(4, 8), anchor: Anchor.center, ), ); await game.add(CameraZoom(value: 40)); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/camera_zoom/no_zoom.png'), ); game.update(0.2); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/camera_zoom/in_between.png'), ); game.update(0.4); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/camera_zoom/finished.png'), ); game.update(0.1); await tester.pump(); expect(game.firstChild<CameraZoom>(), isNull); }, ); tester.test( 'completes when checked after it is finished', (game) async { await game.add(CameraZoom(value: 40)); game.update(10); final cameraZoom = game.firstChild<CameraZoom>(); final future = cameraZoom!.completed; expect(future, completes); }, ); tester.test( 'completes when checked before it is finished', (game) async { final zoom = CameraZoom(value: 40); final future = zoom.completed; await game.add(zoom); game.update(10); game.update(0); expect(future, completes); }, ); }); }
pinball/packages/pinball_components/test/src/components/camera_zoom_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/camera_zoom_test.dart', 'repo_id': 'pinball', 'token_count': 1018}
// ignore_for_file: cascade_invocations import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import '../../helpers/helpers.dart'; void main() { group('DinoWalls', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.dino.topWall.keyName, Assets.images.dino.topWallTunnel.keyName, Assets.images.dino.bottomWall.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.test('loads correctly', (game) async { final component = DinoWalls(); await game.ensureAdd(component); expect(game.contains(component), isTrue); }); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); await game.ensureAdd(DinoWalls()); game.camera.followVector2(Vector2.zero()); game.camera.zoom = 6.5; await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/dino_walls.png'), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/dino_walls_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/dino_walls_test.dart', 'repo_id': 'pinball', 'token_count': 536}
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.googleWord.letter1.lit.keyName, Assets.images.googleWord.letter1.dimmed.keyName, Assets.images.googleWord.letter2.lit.keyName, Assets.images.googleWord.letter2.dimmed.keyName, Assets.images.googleWord.letter3.lit.keyName, Assets.images.googleWord.letter3.dimmed.keyName, Assets.images.googleWord.letter4.lit.keyName, Assets.images.googleWord.letter4.dimmed.keyName, Assets.images.googleWord.letter5.lit.keyName, Assets.images.googleWord.letter5.dimmed.keyName, Assets.images.googleWord.letter6.lit.keyName, Assets.images.googleWord.letter6.dimmed.keyName, ]); } Future<void> pump(GoogleWord child) async { await ensureAdd( FlameBlocProvider<GoogleWordCubit, GoogleWordState>.value( value: GoogleWordCubit(), children: [child], ), ); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('GoogleWord', () { test('can be instantiated', () { expect(GoogleWord(position: Vector2.zero()), isA<GoogleWord>()); }); flameTester.test( 'loads letters correctly', (game) async { final googleWord = GoogleWord(position: Vector2.zero()); await game.pump(googleWord); expect( googleWord.children.whereType<GoogleLetter>().length, equals(6), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/google_word/google_word_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/google_word/google_word_test.dart', 'repo_id': 'pinball', 'token_count': 744}
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.multiplier.x2.lit.keyName, Assets.images.multiplier.x2.dimmed.keyName, Assets.images.multiplier.x3.lit.keyName, Assets.images.multiplier.x3.dimmed.keyName, Assets.images.multiplier.x4.lit.keyName, Assets.images.multiplier.x4.dimmed.keyName, Assets.images.multiplier.x5.lit.keyName, Assets.images.multiplier.x5.dimmed.keyName, Assets.images.multiplier.x6.lit.keyName, Assets.images.multiplier.x6.dimmed.keyName, ]); } } class _MockMultiplierCubit extends Mock implements MultiplierCubit {} void main() { group('Multiplier', () { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); late MultiplierCubit bloc; setUp(() { bloc = _MockMultiplierCubit(); }); flameTester.test('"x2" loads correctly', (game) async { final multiplier = Multiplier.x2( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x3" loads correctly', (game) async { final multiplier = Multiplier.x3( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x4" loads correctly', (game) async { final multiplier = Multiplier.x4( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x5" loads correctly', (game) async { final multiplier = Multiplier.x5( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x6" loads correctly', (game) async { final multiplier = Multiplier.x6( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); group('renders correctly', () { group('x2', () { const multiplierValue = MultiplierValue.x2; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x2_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x2_dimmed.png'), ); }, ); }); group('x3', () { const multiplierValue = MultiplierValue.x3; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x3_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x3_dimmed.png'), ); }, ); }); group('x4', () { const multiplierValue = MultiplierValue.x4; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x4_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x4_dimmed.png'), ); }, ); }); group('x5', () { const multiplierValue = MultiplierValue.x5; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x5_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x5_dimmed.png'), ); }, ); }); group('x6', () { const multiplierValue = MultiplierValue.x6; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x6_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x6_dimmed.png'), ); }, ); }); }); flameTester.test('closes bloc when removed', (game) async { whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: MultiplierValue.x2, spriteState: MultiplierSpriteState.dimmed, ), ); when(bloc.close).thenAnswer((_) async {}); final multiplier = Multiplier.test(value: MultiplierValue.x2, bloc: bloc); await game.ensureAdd(multiplier); game.remove(multiplier); await game.ready(); verify(bloc.close).called(1); }); }); }
pinball/packages/pinball_components/test/src/components/multiplier/multiplier_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/multiplier/multiplier_test.dart', 'repo_id': 'pinball', 'token_count': 8158}
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group('SkillShotState', () { test('supports value equality', () { expect( SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), equals( const SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), ), ); }); group('constructor', () { test('can be instantiated', () { expect( const SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), isNotNull, ); }); test('initial is dimmed and not blinking', () { const initialState = SkillShotState( spriteState: SkillShotSpriteState.dimmed, isBlinking: false, ); expect(SkillShotState.initial(), equals(initialState)); }); }); group('copyWith', () { test( 'copies correctly ' 'when no argument specified', () { const skillShotState = SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ); expect( skillShotState.copyWith(), equals(skillShotState), ); }, ); test( 'copies correctly ' 'when all arguments specified', () { const skillShotState = SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ); final otherSkillShotState = SkillShotState( spriteState: SkillShotSpriteState.dimmed, isBlinking: false, ); expect(skillShotState, isNot(equals(otherSkillShotState))); expect( skillShotState.copyWith( spriteState: SkillShotSpriteState.dimmed, isBlinking: false, ), equals(otherSkillShotState), ); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/skill_shot/cubit/skill_shot_state_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/skill_shot/cubit/skill_shot_state_test.dart', 'repo_id': 'pinball', 'token_count': 1059}
import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group('ScoreX', () { test('formatScore correctly formats int', () { expect(1000000.formatScore(), '1,000,000'); }); }); }
pinball/packages/pinball_components/test/src/extensions/score_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/extensions/score_test.dart', 'repo_id': 'pinball', 'token_count': 98}
import 'package:flame/components.dart'; /// A mixin that ensures a parent is of the given type [T]. mixin ParentIsA<T extends Component> on Component { @override T get parent => super.parent! as T; @override Future<void>? addToParent(covariant T parent) { return super.addToParent(parent); } }
pinball/packages/pinball_flame/lib/src/parent_is_a.dart/0
{'file_path': 'pinball/packages/pinball_flame/lib/src/parent_is_a.dart', 'repo_id': 'pinball', 'token_count': 105}
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group('SparkyTheme', () { test('can be instantiated', () { expect(SparkyTheme(), isNotNull); }); test('supports value equality', () { expect(SparkyTheme(), equals(SparkyTheme())); }); }); }
pinball/packages/pinball_theme/test/src/themes/sparky_theme_test.dart/0
{'file_path': 'pinball/packages/pinball_theme/test/src/themes/sparky_theme_test.dart', 'repo_id': 'pinball', 'token_count': 147}
library pinball_ui; export 'package:url_launcher/url_launcher.dart'; export 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; export 'src/dialog/dialog.dart'; export 'src/external_links/external_links.dart'; export 'src/theme/theme.dart'; export 'src/widgets/widgets.dart';
pinball/packages/pinball_ui/lib/pinball_ui.dart/0
{'file_path': 'pinball/packages/pinball_ui/lib/pinball_ui.dart', 'repo_id': 'pinball', 'token_count': 109}
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_ui/pinball_ui.dart'; void main() { group('PinballDialog', () { group('with title only', () { testWidgets('renders the title and the body', (tester) async { tester.binding.window.physicalSizeTestValue = const Size(2000, 4000); addTearDown(tester.binding.window.clearPhysicalSizeTestValue); await tester.pumpWidget( const MaterialApp( home: PinballDialog(title: 'title', child: Placeholder()), ), ); expect(find.byType(PixelatedDecoration), findsOneWidget); expect(find.text('title'), findsOneWidget); expect(find.byType(Placeholder), findsOneWidget); }); }); group('with title and subtitle', () { testWidgets('renders the title, subtitle and the body', (tester) async { tester.binding.window.physicalSizeTestValue = const Size(2000, 4000); addTearDown(tester.binding.window.clearPhysicalSizeTestValue); await tester.pumpWidget( MaterialApp( home: PinballDialog( title: 'title', subtitle: 'sub', child: Icon(Icons.home), ), ), ); expect(find.byType(PixelatedDecoration), findsOneWidget); expect(find.text('title'), findsOneWidget); expect(find.text('sub'), findsOneWidget); expect(find.byType(Icon), findsOneWidget); }); }); }); }
pinball/packages/pinball_ui/test/src/dialog/pinball_dialog_test.dart/0
{'file_path': 'pinball/packages/pinball_ui/test/src/dialog/pinball_dialog_test.dart', 'repo_id': 'pinball', 'token_count': 661}
name: platform_helper description: Platform helper for Pinball application. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.16.0 <3.0.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter very_good_analysis: ^2.4.0
pinball/packages/platform_helper/pubspec.yaml/0
{'file_path': 'pinball/packages/platform_helper/pubspec.yaml', 'repo_id': 'pinball', 'token_count': 112}
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/assets_manager/assets_manager.dart'; import 'package:pinball_ui/pinball_ui.dart'; import '../../helpers/helpers.dart'; class _MockAssetsManagerCubit extends Mock implements AssetsManagerCubit {} void main() { late AssetsManagerCubit assetsManagerCubit; setUp(() { const initialAssetsState = AssetsManagerState( assetsCount: 1, loaded: 0, ); assetsManagerCubit = _MockAssetsManagerCubit(); whenListen( assetsManagerCubit, Stream.value(initialAssetsState), initialState: initialAssetsState, ); }); group('AssetsLoadingPage', () { testWidgets('renders an animated text and a pinball loading indicator', (tester) async { await tester.pumpApp( const AssetsLoadingPage(), assetsManagerCubit: assetsManagerCubit, ); expect(find.byType(AnimatedEllipsisText), findsOneWidget); expect(find.byType(PinballLoadingIndicator), findsOneWidget); }); }); }
pinball/test/assets_manager/views/assets_loading_page_test.dart/0
{'file_path': 'pinball/test/assets_manager/views/assets_loading_page_test.dart', 'repo_id': 'pinball', 'token_count': 416}
// ignore_for_file: cascade_invocations import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.android.spaceship.saucer.keyName, Assets.images.android.spaceship.animatronic.keyName, Assets.images.android.spaceship.lightBeam.keyName, Assets.images.android.ramp.boardOpening.keyName, Assets.images.android.ramp.railingForeground.keyName, Assets.images.android.ramp.railingBackground.keyName, Assets.images.android.ramp.main.keyName, Assets.images.android.ramp.arrow.inactive.keyName, Assets.images.android.ramp.arrow.active1.keyName, Assets.images.android.ramp.arrow.active2.keyName, Assets.images.android.ramp.arrow.active3.keyName, Assets.images.android.ramp.arrow.active4.keyName, Assets.images.android.ramp.arrow.active5.keyName, Assets.images.android.rail.main.keyName, Assets.images.android.rail.exit.keyName, Assets.images.android.bumper.a.lit.keyName, Assets.images.android.bumper.a.dimmed.keyName, Assets.images.android.bumper.b.lit.keyName, Assets.images.android.bumper.b.dimmed.keyName, Assets.images.android.bumper.cow.lit.keyName, Assets.images.android.bumper.cow.dimmed.keyName, ]); } Future<void> pump( AndroidAcres child, { required GameBloc gameBloc, required AndroidSpaceshipCubit androidSpaceshipCubit, }) async { // Not needed once https://github.com/flame-engine/flame/issues/1607 // is fixed await onLoad(); await ensureAdd( FlameMultiBlocProvider( providers: [ FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, ), FlameBlocProvider<AndroidSpaceshipCubit, AndroidSpaceshipState>.value( value: androidSpaceshipCubit, ), ], children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockAndroidSpaceshipCubit extends Mock implements AndroidSpaceshipCubit { } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('AndroidSpaceshipBonusBehavior', () { late GameBloc gameBloc; setUp(() { gameBloc = _MockGameBloc(); }); final flameTester = FlameTester(_TestGame.new); flameTester.testGameWidget( 'adds GameBonus.androidSpaceship to the game ' 'when android spaceship has a bonus', setUp: (game, tester) async { final behavior = AndroidSpaceshipBonusBehavior(); final parent = AndroidAcres.test(); final androidSpaceship = AndroidSpaceship(position: Vector2.zero()); final androidSpaceshipCubit = _MockAndroidSpaceshipCubit(); final streamController = StreamController<AndroidSpaceshipState>(); whenListen( androidSpaceshipCubit, streamController.stream, initialState: AndroidSpaceshipState.withoutBonus, ); await parent.add(androidSpaceship); await game.pump( parent, androidSpaceshipCubit: androidSpaceshipCubit, gameBloc: gameBloc, ); await parent.ensureAdd(behavior); streamController.add(AndroidSpaceshipState.withBonus); await tester.pump(); verify( () => gameBloc.add(const BonusActivated(GameBonus.androidSpaceship)), ).called(1); }, ); }); }
pinball/test/game/components/android_acres/behaviors/android_spaceship_bonus_behavior_test.dart/0
{'file_path': 'pinball/test/game/components/android_acres/behaviors/android_spaceship_bonus_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 1596}
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/bloc/game_bloc.dart'; import 'package:pinball/game/components/backbox/displays/loading_display.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends Forge2DGame { Future<void> pump(LoadingDisplay component) { return ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [ FlameProvider.value( _MockAppLocalizations(), children: [component], ), ], ), ); } } class _MockAppLocalizations extends Mock implements AppLocalizations { @override String get loading => 'Loading'; } void main() { group('LoadingDisplay', () { final flameTester = FlameTester(_TestGame.new); flameTester.test('renders correctly', (game) async { await game.pump(LoadingDisplay()); final component = game.descendants().whereType<TextComponent>().first; expect(component, isNotNull); expect(component.text, equals('Loading')); }); flameTester.test('use ellipses as animation', (game) async { await game.pump(LoadingDisplay()); final component = game.descendants().whereType<TextComponent>().first; expect(component.text, equals('Loading')); final timer = component.firstChild<TimerComponent>(); timer?.update(1.1); expect(component.text, equals('Loading.')); timer?.update(1.1); expect(component.text, equals('Loading..')); timer?.update(1.1); expect(component.text, equals('Loading...')); timer?.update(1.1); expect(component.text, equals('Loading')); }); }); }
pinball/test/game/components/backbox/displays/loading_display_test.dart/0
{'file_path': 'pinball/test/game/components/backbox/displays/loading_display_test.dart', 'repo_id': 'pinball', 'token_count': 757}
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/multipliers/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.multiplier.x2.lit.keyName, Assets.images.multiplier.x2.dimmed.keyName, Assets.images.multiplier.x3.lit.keyName, Assets.images.multiplier.x3.dimmed.keyName, Assets.images.multiplier.x4.lit.keyName, Assets.images.multiplier.x4.dimmed.keyName, Assets.images.multiplier.x5.lit.keyName, Assets.images.multiplier.x5.dimmed.keyName, Assets.images.multiplier.x6.lit.keyName, Assets.images.multiplier.x6.dimmed.keyName, ]); } Future<void> pump(Multipliers child) async { await ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockComponent extends Mock implements Component {} class _MockMultiplierCubit extends Mock implements MultiplierCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('MultipliersBehavior', () { late GameBloc gameBloc; setUp(() { registerFallbackValue(_MockComponent()); gameBloc = _MockGameBloc(); whenListen( gameBloc, const Stream<GameState>.empty(), initialState: const GameState.initial(), ); }); final flameBlocTester = FlameTester(_TestGame.new); group('listenWhen', () { test('is true when the multiplier has changed', () { final state = GameState( totalScore: 0, roundScore: 10, multiplier: 2, rounds: 0, status: GameStatus.playing, bonusHistory: const [], ); final previous = GameState.initial(); expect( MultipliersBehavior().listenWhen(previous, state), isTrue, ); }); test('is false when the multiplier state is the same', () { final state = GameState( totalScore: 0, roundScore: 10, multiplier: 1, rounds: 0, status: GameStatus.playing, bonusHistory: const [], ); final previous = GameState.initial(); expect( MultipliersBehavior().listenWhen(previous, state), isFalse, ); }); }); group('onNewState', () { flameBlocTester.testGameWidget( "calls 'next' once per each multiplier when GameBloc emit state", setUp: (game, tester) async { await game.onLoad(); final behavior = MultipliersBehavior(); final parent = Multipliers.test(); final multiplierX2Cubit = _MockMultiplierCubit(); final multiplierX3Cubit = _MockMultiplierCubit(); final multipliers = [ Multiplier.test( value: MultiplierValue.x2, bloc: multiplierX2Cubit, ), Multiplier.test( value: MultiplierValue.x3, bloc: multiplierX3Cubit, ), ]; whenListen( multiplierX2Cubit, const Stream<MultiplierState>.empty(), initialState: MultiplierState.initial(MultiplierValue.x2), ); when(() => multiplierX2Cubit.next(any())).thenAnswer((_) async {}); whenListen( multiplierX3Cubit, const Stream<MultiplierState>.empty(), initialState: MultiplierState.initial(MultiplierValue.x2), ); when(() => multiplierX3Cubit.next(any())).thenAnswer((_) async {}); await parent.addAll(multipliers); await game.pump(parent); await parent.ensureAdd(behavior); await tester.pump(); behavior.onNewState( GameState.initial().copyWith(multiplier: 2), ); for (final multiplier in multipliers) { verify( () => multiplier.bloc.next(any()), ).called(1); } }, ); }); }); }
pinball/test/game/components/multipliers/behaviors/multipliers_behavior_test.dart/0
{'file_path': 'pinball/test/game/components/multipliers/behaviors/multipliers_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 2083}
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/assets_manager/assets_manager.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_ui/pinball_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:share_repository/share_repository.dart'; class _MockAssetsManagerCubit extends Mock implements AssetsManagerCubit {} class _MockLeaderboardRepository extends Mock implements LeaderboardRepository { } class _MockShareRepository extends Mock implements ShareRepository {} class _MockCharacterThemeCubit extends Mock implements CharacterThemeCubit {} class _MockGameBloc extends Mock implements GameBloc {} class _MockStartGameBloc extends Mock implements StartGameBloc {} class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {} class _MockPlatformHelper extends Mock implements PlatformHelper {} PinballAudioPlayer _buildDefaultPinballAudioPlayer() { final audioPlayer = _MockPinballAudioPlayer(); when(audioPlayer.load).thenAnswer((_) => [Future.value]); return audioPlayer; } AssetsManagerCubit _buildDefaultAssetsManagerCubit() { final cubit = _MockAssetsManagerCubit(); const state = AssetsManagerState( assetsCount: 1, loaded: 1, ); whenListen( cubit, Stream.value(state), initialState: state, ); return cubit; } extension PumpApp on WidgetTester { Future<void> pumpApp( Widget widget, { GameBloc? gameBloc, StartGameBloc? startGameBloc, AssetsManagerCubit? assetsManagerCubit, CharacterThemeCubit? characterThemeCubit, LeaderboardRepository? leaderboardRepository, ShareRepository? shareRepository, PinballAudioPlayer? pinballAudioPlayer, PlatformHelper? platformHelper, }) { return runAsync(() { return pumpWidget( MultiRepositoryProvider( providers: [ RepositoryProvider.value( value: leaderboardRepository ?? _MockLeaderboardRepository(), ), RepositoryProvider.value( value: shareRepository ?? _MockShareRepository(), ), RepositoryProvider.value( value: pinballAudioPlayer ?? _buildDefaultPinballAudioPlayer(), ), RepositoryProvider.value( value: platformHelper ?? _MockPlatformHelper(), ), ], child: MultiBlocProvider( providers: [ BlocProvider.value( value: characterThemeCubit ?? _MockCharacterThemeCubit(), ), BlocProvider.value( value: gameBloc ?? _MockGameBloc(), ), BlocProvider.value( value: startGameBloc ?? _MockStartGameBloc(), ), BlocProvider.value( value: assetsManagerCubit ?? _buildDefaultAssetsManagerCubit(), ), ], child: MaterialApp( theme: PinballTheme.standard, localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ), ), ); }); } }
pinball/test/helpers/pump_app.dart/0
{'file_path': 'pinball/test/helpers/pump_app.dart', 'repo_id': 'pinball', 'token_count': 1541}
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh - name: tool unit tests script: .ci/scripts/plugin_tools_tests.sh
plugins/.ci/targets/plugin_tools_tests.yaml/0
{'file_path': 'plugins/.ci/targets/plugin_tools_tests.yaml', 'repo_id': 'plugins', 'token_count': 54}
include: package:pedantic/analysis_options.1.8.0.yaml analyzer: exclude: # Ignore generated files - '**/*.g.dart' - 'lib/src/generated/*.dart' - '**/*.mocks.dart' # Mockito @GenerateMocks - '**/*.pigeon.dart' # Pigeon generated file errors: always_require_non_null_named_parameters: false # not needed with nnbd # TODO(https://github.com/flutter/flutter/issues/74381): # Clean up existing unnecessary imports, and remove line to ignore. unnecessary_import: ignore unnecessary_null_comparison: false # Turned as long as nnbd mix-mode is supported. linter: rules: - public_member_api_docs
plugins/analysis_options_legacy.yaml/0
{'file_path': 'plugins/analysis_options_legacy.yaml', 'repo_id': 'plugins', 'token_count': 239}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_web/src/types/types.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('CameraMetadata', () { testWidgets('supports value equality', (tester) async { expect( CameraMetadata( deviceId: 'deviceId', facingMode: 'environment', ), equals( CameraMetadata( deviceId: 'deviceId', facingMode: 'environment', ), ), ); }); }); }
plugins/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart/0
{'file_path': 'plugins/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart', 'repo_id': 'plugins', 'token_count': 308}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; /// Convert list of XTypeGroups to a comma-separated string String acceptedTypesToString(List<XTypeGroup>? acceptedTypes) { if (acceptedTypes == null) { return ''; } final List<String> allTypes = <String>[]; for (final XTypeGroup group in acceptedTypes) { _assertTypeGroupIsValid(group); if (group.extensions != null) { allTypes.addAll(group.extensions!.map(_normalizeExtension)); } if (group.mimeTypes != null) { allTypes.addAll(group.mimeTypes!); } if (group.webWildCards != null) { allTypes.addAll(group.webWildCards!); } } return allTypes.join(','); } /// Make sure that at least one of its fields is populated. void _assertTypeGroupIsValid(XTypeGroup group) { assert( !((group.extensions == null || group.extensions!.isEmpty) && (group.mimeTypes == null || group.mimeTypes!.isEmpty) && (group.webWildCards == null || group.webWildCards!.isEmpty)), 'At least one of extensions / mimeTypes / webWildCards is required for web.'); } /// Append a dot at the beggining if it is not there png -> .png String _normalizeExtension(String ext) { return ext.isNotEmpty && ext[0] != '.' ? '.' + ext : ext; }
plugins/packages/file_selector/file_selector_web/lib/src/utils.dart/0
{'file_path': 'plugins/packages/file_selector/file_selector_web/lib/src/utils.dart', 'repo_id': 'plugins', 'token_count': 508}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; const CameraPosition _kInitialPosition = CameraPosition(target: LatLng(-33.852, 151.211), zoom: 11.0); class SnapshotPage extends GoogleMapExampleAppPage { SnapshotPage() : super(const Icon(Icons.camera_alt), 'Take a snapshot of the map'); @override Widget build(BuildContext context) { return _SnapshotBody(); } } class _SnapshotBody extends StatefulWidget { @override _SnapshotBodyState createState() => _SnapshotBodyState(); } class _SnapshotBodyState extends State<_SnapshotBody> { GoogleMapController? _mapController; Uint8List? _imageBytes; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( height: 180, child: GoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, ), ), TextButton( child: Text('Take a snapshot'), onPressed: () async { final imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); }, ), Container( decoration: BoxDecoration(color: Colors.blueGrey[50]), height: 180, child: _imageBytes != null ? Image.memory(_imageBytes!) : null, ), ], ), ); } void onMapCreated(GoogleMapController controller) { _mapController = controller; } }
plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart', 'repo_id': 'plugins', 'token_count': 813}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'fake_maps_controllers.dart'; Widget _mapWithPolylines(Set<Polyline> polylines) { return Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), polylines: polylines, ), ); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final FakePlatformViewsController fakePlatformViewsController = FakePlatformViewsController(); setUpAll(() { SystemChannels.platform_views.setMockMethodCallHandler( fakePlatformViewsController.fakePlatformViewsMethodHandler); }); setUp(() { fakePlatformViewsController.reset(); }); testWidgets('Initializing a polyline', (WidgetTester tester) async { final Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToAdd.length, 1); final Polyline initializedPolyline = platformGoogleMap.polylinesToAdd.first; expect(initializedPolyline, equals(p1)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToChange.isEmpty, true); }); testWidgets("Adding a polyline", (WidgetTester tester) async { final Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); final Polyline p2 = Polyline(polylineId: PolylineId("polyline_2")); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToAdd.length, 1); final Polyline addedPolyline = platformGoogleMap.polylinesToAdd.first; expect(addedPolyline, equals(p2)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToChange.isEmpty, true); }); testWidgets("Removing a polyline", (WidgetTester tester) async { final Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylineIdsToRemove.length, 1); expect(platformGoogleMap.polylineIdsToRemove.first, equals(p1.polylineId)); expect(platformGoogleMap.polylinesToChange.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets("Updating a polyline", (WidgetTester tester) async { final Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); final Polyline p2 = Polyline(polylineId: PolylineId("polyline_1"), geodesic: true); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); expect(platformGoogleMap.polylinesToChange.first, equals(p2)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets("Updating a polyline", (WidgetTester tester) async { final Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); final Polyline p2 = Polyline(polylineId: PolylineId("polyline_1"), geodesic: true); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); final Polyline update = platformGoogleMap.polylinesToChange.first; expect(update, equals(p2)); expect(update.geodesic, true); }); testWidgets("Mutate a polyline", (WidgetTester tester) async { final Polyline p1 = Polyline( polylineId: PolylineId("polyline_1"), points: <LatLng>[const LatLng(0.0, 0.0)], ); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); p1.points.add(const LatLng(1.0, 1.0)); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); expect(platformGoogleMap.polylinesToChange.first, equals(p1)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets("Multi Update", (WidgetTester tester) async { Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); Polyline p2 = Polyline(polylineId: PolylineId("polyline_2")); final Set<Polyline> prev = <Polyline>{p1, p2}; p1 = Polyline(polylineId: PolylineId("polyline_1"), visible: false); p2 = Polyline(polylineId: PolylineId("polyline_2"), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange, cur); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets("Multi Update", (WidgetTester tester) async { Polyline p2 = Polyline(polylineId: PolylineId("polyline_2")); final Polyline p3 = Polyline(polylineId: PolylineId("polyline_3")); final Set<Polyline> prev = <Polyline>{p2, p3}; // p1 is added, p2 is updated, p3 is removed. final Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); p2 = Polyline(polylineId: PolylineId("polyline_2"), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); expect(platformGoogleMap.polylinesToAdd.length, 1); expect(platformGoogleMap.polylineIdsToRemove.length, 1); expect(platformGoogleMap.polylinesToChange.first, equals(p2)); expect(platformGoogleMap.polylinesToAdd.first, equals(p1)); expect(platformGoogleMap.polylineIdsToRemove.first, equals(p3.polylineId)); }); testWidgets("Partial Update", (WidgetTester tester) async { final Polyline p1 = Polyline(polylineId: PolylineId("polyline_1")); final Polyline p2 = Polyline(polylineId: PolylineId("polyline_2")); Polyline p3 = Polyline(polylineId: PolylineId("polyline_3")); final Set<Polyline> prev = <Polyline>{p1, p2, p3}; p3 = Polyline(polylineId: PolylineId("polyline_3"), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2, p3}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange, <Polyline>{p3}); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets("Update non platform related attr", (WidgetTester tester) async { Polyline p1 = Polyline(polylineId: PolylineId("polyline_1"), onTap: null); final Set<Polyline> prev = <Polyline>{p1}; p1 = Polyline( polylineId: PolylineId("polyline_1"), onTap: () => print(2 + 2)); final Set<Polyline> cur = <Polyline>{p1}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.isEmpty, true); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); }
plugins/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart', 'repo_id': 'plugins', 'token_count': 3110}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'types.dart'; /// [Circle] update events to be applied to the [GoogleMap]. /// /// Used in [GoogleMapController] when the map is updated. // (Do not re-export) class CircleUpdates extends MapsObjectUpdates<Circle> { /// Computes [CircleUpdates] given previous and current [Circle]s. CircleUpdates.from(Set<Circle> previous, Set<Circle> current) : super.from(previous, current, objectName: 'circle'); /// Set of Circles to be added in this update. Set<Circle> get circlesToAdd => objectsToAdd; /// Set of CircleIds to be removed in this update. Set<CircleId> get circleIdsToRemove => objectIdsToRemove.cast<CircleId>(); /// Set of Circles to be changed in this update. Set<Circle> get circlesToChange => objectsToChange; }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart', 'repo_id': 'plugins', 'token_count': 279}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show hashValues, hashList; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object_updates.dart'; import 'package:google_maps_flutter_platform_interface/src/types/utils/maps_object.dart'; import 'test_maps_object.dart'; class TestMapsObjectUpdate extends MapsObjectUpdates<TestMapsObject> { TestMapsObjectUpdate.from( Set<TestMapsObject> previous, Set<TestMapsObject> current) : super.from(previous, current, objectName: 'testObject'); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('tile overlay updates tests', () { test('Correctly set toRemove, toAdd and toChange', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = Set.from(<TestMapsObject>[to1, to2, to3]); final Set<TestMapsObject> current = Set.from(<TestMapsObject>[to2, to3Changed, to4]); final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); final Set<MapsObjectId<TestMapsObject>> toRemove = Set.from(<MapsObjectId<TestMapsObject>>[ const MapsObjectId<TestMapsObject>('id1') ]); expect(updates.objectIdsToRemove, toRemove); final Set<TestMapsObject> toAdd = Set.from(<TestMapsObject>[to4]); expect(updates.objectsToAdd, toAdd); final Set<TestMapsObject> toChange = Set.from(<TestMapsObject>[to3Changed]); expect(updates.objectsToChange, toChange); }); test('toJson', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = Set.from(<TestMapsObject>[to1, to2, to3]); final Set<TestMapsObject> current = Set.from(<TestMapsObject>[to2, to3Changed, to4]); final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); final Object json = updates.toJson(); expect(json, <String, Object>{ 'testObjectsToAdd': serializeMapsObjectSet(updates.objectsToAdd), 'testObjectsToChange': serializeMapsObjectSet(updates.objectsToChange), 'testObjectIdsToRemove': updates.objectIdsToRemove .map<String>((MapsObjectId<TestMapsObject> m) => m.value) .toList() }); }); test('equality', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = Set.from(<TestMapsObject>[to1, to2, to3]); final Set<TestMapsObject> current1 = Set.from(<TestMapsObject>[to2, to3Changed, to4]); final Set<TestMapsObject> current2 = Set.from(<TestMapsObject>[to2, to3Changed, to4]); final Set<TestMapsObject> current3 = Set.from(<TestMapsObject>[to2, to4]); final TestMapsObjectUpdate updates1 = TestMapsObjectUpdate.from(previous, current1); final TestMapsObjectUpdate updates2 = TestMapsObjectUpdate.from(previous, current2); final TestMapsObjectUpdate updates3 = TestMapsObjectUpdate.from(previous, current3); expect(updates1, updates2); expect(updates1, isNot(updates3)); }); test('hashCode', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = Set.from(<TestMapsObject>[to1, to2, to3]); final Set<TestMapsObject> current = Set.from(<TestMapsObject>[to2, to3Changed, to4]); final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); expect( updates.hashCode, hashValues( hashList(updates.objectsToAdd), hashList(updates.objectIdsToRemove), hashList(updates.objectsToChange))); }); test('toString', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = Set.from(<TestMapsObject>[to1, to2, to3]); final Set<TestMapsObject> current = Set.from(<TestMapsObject>[to2, to3Changed, to4]); final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); expect( updates.toString(), 'TestMapsObjectUpdate(add: ${updates.objectsToAdd}, ' 'remove: ${updates.objectIdsToRemove}, ' 'change: ${updates.objectsToChange})'); }); }); }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart', 'repo_id': 'plugins', 'token_count': 2781}
// Mocks generated by Mockito 5.0.16 from annotations // in google_maps_flutter_web_integration_tests/integration_test/google_maps_plugin_test.dart. // Do not manually edit this file. import 'dart:async' as _i2; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart' as _i3; import 'package:google_maps_flutter_web/google_maps_flutter_web.dart' as _i4; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types class _FakeStreamController_0<T> extends _i1.Fake implements _i2.StreamController<T> {} class _FakeLatLngBounds_1 extends _i1.Fake implements _i3.LatLngBounds {} class _FakeScreenCoordinate_2 extends _i1.Fake implements _i3.ScreenCoordinate { } class _FakeLatLng_3 extends _i1.Fake implements _i3.LatLng {} /// A class which mocks [GoogleMapController]. /// /// See the documentation for Mockito's code generation for more information. class MockGoogleMapController extends _i1.Mock implements _i4.GoogleMapController { @override _i2.StreamController<_i3.MapEvent<dynamic>> get stream => (super.noSuchMethod(Invocation.getter(#stream), returnValue: _FakeStreamController_0<_i3.MapEvent<dynamic>>()) as _i2.StreamController<_i3.MapEvent<dynamic>>); @override _i2.Stream<_i3.MapEvent<dynamic>> get events => (super.noSuchMethod(Invocation.getter(#events), returnValue: Stream<_i3.MapEvent<dynamic>>.empty()) as _i2.Stream<_i3.MapEvent<dynamic>>); @override bool get isInitialized => (super.noSuchMethod(Invocation.getter(#isInitialized), returnValue: false) as bool); @override void debugSetOverrides( {_i4.DebugCreateMapFunction? createMap, _i4.MarkersController? markers, _i4.CirclesController? circles, _i4.PolygonsController? polygons, _i4.PolylinesController? polylines}) => super.noSuchMethod( Invocation.method(#debugSetOverrides, [], { #createMap: createMap, #markers: markers, #circles: circles, #polygons: polygons, #polylines: polylines }), returnValueForMissingStub: null); @override void init() => super.noSuchMethod(Invocation.method(#init, []), returnValueForMissingStub: null); @override void updateRawOptions(Map<String, dynamic>? optionsUpdate) => super.noSuchMethod(Invocation.method(#updateRawOptions, [optionsUpdate]), returnValueForMissingStub: null); @override _i2.Future<_i3.LatLngBounds> getVisibleRegion() => (super.noSuchMethod( Invocation.method(#getVisibleRegion, []), returnValue: Future<_i3.LatLngBounds>.value(_FakeLatLngBounds_1())) as _i2.Future<_i3.LatLngBounds>); @override _i2.Future<_i3.ScreenCoordinate> getScreenCoordinate(_i3.LatLng? latLng) => (super.noSuchMethod(Invocation.method(#getScreenCoordinate, [latLng]), returnValue: Future<_i3.ScreenCoordinate>.value(_FakeScreenCoordinate_2())) as _i2.Future<_i3.ScreenCoordinate>); @override _i2.Future<_i3.LatLng> getLatLng(_i3.ScreenCoordinate? screenCoordinate) => (super.noSuchMethod(Invocation.method(#getLatLng, [screenCoordinate]), returnValue: Future<_i3.LatLng>.value(_FakeLatLng_3())) as _i2.Future<_i3.LatLng>); @override _i2.Future<void> moveCamera(_i3.CameraUpdate? cameraUpdate) => (super.noSuchMethod(Invocation.method(#moveCamera, [cameraUpdate]), returnValue: Future<void>.value(), returnValueForMissingStub: Future<void>.value()) as _i2.Future<void>); @override _i2.Future<double> getZoomLevel() => (super.noSuchMethod(Invocation.method(#getZoomLevel, []), returnValue: Future<double>.value(0.0)) as _i2.Future<double>); @override void updateCircles(_i3.CircleUpdates? updates) => super.noSuchMethod(Invocation.method(#updateCircles, [updates]), returnValueForMissingStub: null); @override void updatePolygons(_i3.PolygonUpdates? updates) => super.noSuchMethod(Invocation.method(#updatePolygons, [updates]), returnValueForMissingStub: null); @override void updatePolylines(_i3.PolylineUpdates? updates) => super.noSuchMethod(Invocation.method(#updatePolylines, [updates]), returnValueForMissingStub: null); @override void updateMarkers(_i3.MarkerUpdates? updates) => super.noSuchMethod(Invocation.method(#updateMarkers, [updates]), returnValueForMissingStub: null); @override void showInfoWindow(_i3.MarkerId? markerId) => super.noSuchMethod(Invocation.method(#showInfoWindow, [markerId]), returnValueForMissingStub: null); @override void hideInfoWindow(_i3.MarkerId? markerId) => super.noSuchMethod(Invocation.method(#hideInfoWindow, [markerId]), returnValueForMissingStub: null); @override bool isInfoWindowShown(_i3.MarkerId? markerId) => (super.noSuchMethod(Invocation.method(#isInfoWindowShown, [markerId]), returnValue: false) as bool); @override void dispose() => super.noSuchMethod(Invocation.method(#dispose, []), returnValueForMissingStub: null); @override String toString() => super.toString(); }
plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart/0
{'file_path': 'plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart', 'repo_id': 'plugins', 'token_count': 2254}
include: ../../../analysis_options_legacy.yaml
plugins/packages/google_sign_in/google_sign_in_web/analysis_options.yaml/0
{'file_path': 'plugins/packages/google_sign_in/google_sign_in_web/analysis_options.yaml', 'repo_id': 'plugins', 'token_count': 16}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:html' as html; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:js/js.dart'; import 'src/generated/gapiauth2.dart' as auth2; import 'src/load_gapi.dart' as gapi; import 'src/utils.dart' show gapiUserToPluginUserData; const String _kClientIdMetaSelector = 'meta[name=google-signin-client_id]'; const String _kClientIdAttributeName = 'content'; /// This is only exposed for testing. It shouldn't be accessed by users of the /// plugin as it could break at any point. @visibleForTesting String gapiUrl = 'https://apis.google.com/js/platform.js'; /// Implementation of the google_sign_in plugin for Web. class GoogleSignInPlugin extends GoogleSignInPlatform { /// Constructs the plugin immediately and begins initializing it in the /// background. /// /// The plugin is completely initialized when [initialized] completed. GoogleSignInPlugin() { _autoDetectedClientId = html .querySelector(_kClientIdMetaSelector) ?.getAttribute(_kClientIdAttributeName); _isGapiInitialized = gapi.inject(gapiUrl).then((_) => gapi.init()); } late Future<void> _isGapiInitialized; late Future<void> _isAuthInitialized; bool _isInitCalled = false; // This method throws if init hasn't been called at some point in the past. // It is used by the [initialized] getter to ensure that users can't await // on a Future that will never resolve. void _assertIsInitCalled() { if (!_isInitCalled) { throw StateError( 'GoogleSignInPlugin::init() must be called before any other method in this plugin.'); } } /// A future that resolves when both GAPI and Auth2 have been correctly initialized. @visibleForTesting Future<void> get initialized { _assertIsInitCalled(); return Future.wait([_isGapiInitialized, _isAuthInitialized]); } String? _autoDetectedClientId; /// Factory method that initializes the plugin with [GoogleSignInPlatform]. static void registerWith(Registrar registrar) { GoogleSignInPlatform.instance = GoogleSignInPlugin(); } @override Future<void> init({ List<String> scopes = const <String>[], SignInOption signInOption = SignInOption.standard, String? hostedDomain, String? clientId, }) async { final String? appClientId = clientId ?? _autoDetectedClientId; assert( appClientId != null, 'ClientID not set. Either set it on a ' '<meta name="google-signin-client_id" content="CLIENT_ID" /> tag,' ' or pass clientId when calling init()'); assert( !scopes.any((String scope) => scope.contains(' ')), 'OAuth 2.0 Scopes for Google APIs can\'t contain spaces.' 'Check https://developers.google.com/identity/protocols/googlescopes ' 'for a list of valid OAuth 2.0 scopes.'); await _isGapiInitialized; final auth2.GoogleAuth auth = auth2.init(auth2.ClientConfig( hosted_domain: hostedDomain, // The js lib wants a space-separated list of values scope: scopes.join(' '), client_id: appClientId!, )); Completer<void> isAuthInitialized = Completer<void>(); _isAuthInitialized = isAuthInitialized.future; _isInitCalled = true; auth.then(allowInterop((auth2.GoogleAuth initializedAuth) { // onSuccess // TODO: https://github.com/flutter/flutter/issues/48528 // This plugin doesn't notify the app of external changes to the // state of the authentication, i.e: if you logout elsewhere... isAuthInitialized.complete(); }), allowInterop((auth2.GoogleAuthInitFailureError reason) { // onError isAuthInitialized.completeError(PlatformException( code: reason.error, message: reason.details, details: 'https://developers.google.com/identity/sign-in/web/reference#error_codes', )); })); return _isAuthInitialized; } @override Future<GoogleSignInUserData?> signInSilently() async { await initialized; return gapiUserToPluginUserData( await auth2.getAuthInstance()?.currentUser?.get()); } @override Future<GoogleSignInUserData?> signIn() async { await initialized; try { return gapiUserToPluginUserData(await auth2.getAuthInstance()?.signIn()); } on auth2.GoogleAuthSignInError catch (reason) { throw PlatformException( code: reason.error, message: 'Exception raised from GoogleAuth.signIn()', details: 'https://developers.google.com/identity/sign-in/web/reference#error_codes_2', ); } } @override Future<GoogleSignInTokenData> getTokens( {required String email, bool? shouldRecoverAuth}) async { await initialized; final auth2.GoogleUser? currentUser = auth2.getAuthInstance()?.currentUser?.get(); final auth2.AuthResponse? response = currentUser?.getAuthResponse(); return GoogleSignInTokenData( idToken: response?.id_token, accessToken: response?.access_token); } @override Future<void> signOut() async { await initialized; return auth2.getAuthInstance()?.signOut(); } @override Future<void> disconnect() async { await initialized; final auth2.GoogleUser? currentUser = auth2.getAuthInstance()?.currentUser?.get(); if (currentUser == null) return; return currentUser.disconnect(); } @override Future<bool> isSignedIn() async { await initialized; final auth2.GoogleUser? currentUser = auth2.getAuthInstance()?.currentUser?.get(); if (currentUser == null) return false; return currentUser.isSignedIn(); } @override Future<void> clearAuthCache({required String token}) async { await initialized; return auth2.getAuthInstance()?.disconnect(); } @override Future<bool> requestScopes(List<String> scopes) async { await initialized; final currentUser = auth2.getAuthInstance()?.currentUser?.get(); if (currentUser == null) return false; final grantedScopes = currentUser.getGrantedScopes() ?? ''; final missingScopes = scopes.where((scope) => !grantedScopes.contains(scope)); if (missingScopes.isEmpty) return true; final response = await currentUser .grant(auth2.SigninOptions(scope: missingScopes.join(' '))); return response != null; } }
plugins/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart/0
{'file_path': 'plugins/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart', 'repo_id': 'plugins', 'token_count': 2317}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; void main() { group('InAppPurchase', () { final ProductDetails productDetails = ProductDetails( id: 'id', title: 'title', description: 'description', price: 'price', rawPrice: 0.0, currencyCode: 'currencyCode', ); final PurchaseDetails purchaseDetails = PurchaseDetails( productID: 'productID', verificationData: PurchaseVerificationData( localVerificationData: 'localVerificationData', serverVerificationData: 'serverVerificationData', source: 'source', ), transactionDate: 'transactionDate', status: PurchaseStatus.purchased, ); late InAppPurchase inAppPurchase; late MockInAppPurchasePlatform fakePlatform; setUp(() { debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; fakePlatform = MockInAppPurchasePlatform(); InAppPurchasePlatform.instance = fakePlatform; inAppPurchase = InAppPurchase.instance; }); tearDown(() { // Restore the default target platform debugDefaultTargetPlatformOverride = null; }); test('isAvailable', () async { final bool isAvailable = await inAppPurchase.isAvailable(); expect(isAvailable, true); expect(fakePlatform.log, <Matcher>[ isMethodCall('isAvailable', arguments: null), ]); }); test('purchaseStream', () async { final bool isEmptyStream = await inAppPurchase.purchaseStream.isEmpty; expect(isEmptyStream, true); expect(fakePlatform.log, <Matcher>[ isMethodCall('purchaseStream', arguments: null), ]); }); test('queryProductDetails', () async { final ProductDetailsResponse response = await inAppPurchase.queryProductDetails(Set<String>()); expect(response.notFoundIDs.isEmpty, true); expect(response.productDetails.isEmpty, true); expect(fakePlatform.log, <Matcher>[ isMethodCall('queryProductDetails', arguments: null), ]); }); test('buyNonConsumable', () async { final bool result = await inAppPurchase.buyNonConsumable( purchaseParam: PurchaseParam( productDetails: productDetails, ), ); expect(result, true); expect(fakePlatform.log, <Matcher>[ isMethodCall('buyNonConsumable', arguments: null), ]); }); test('buyConsumable', () async { final purchaseParam = PurchaseParam(productDetails: productDetails); final bool result = await inAppPurchase.buyConsumable( purchaseParam: purchaseParam, ); expect(result, true); expect(fakePlatform.log, <Matcher>[ isMethodCall('buyConsumable', arguments: { "purchaseParam": purchaseParam, "autoConsume": true, }), ]); }); test('buyConsumable with autoConsume=false', () async { final purchaseParam = PurchaseParam(productDetails: productDetails); final bool result = await inAppPurchase.buyConsumable( purchaseParam: purchaseParam, autoConsume: false, ); expect(result, true); expect(fakePlatform.log, <Matcher>[ isMethodCall('buyConsumable', arguments: { "purchaseParam": purchaseParam, "autoConsume": false, }), ]); }); test('completePurchase', () async { await inAppPurchase.completePurchase(purchaseDetails); expect(fakePlatform.log, <Matcher>[ isMethodCall('completePurchase', arguments: null), ]); }); test('restorePurchases', () async { await inAppPurchase.restorePurchases(); expect(fakePlatform.log, <Matcher>[ isMethodCall('restorePurchases', arguments: null), ]); }); }); } class MockInAppPurchasePlatform extends Fake with MockPlatformInterfaceMixin implements InAppPurchasePlatform { final List<MethodCall> log = []; @override Future<bool> isAvailable() { log.add(MethodCall('isAvailable')); return Future.value(true); } @override Stream<List<PurchaseDetails>> get purchaseStream { log.add(MethodCall('purchaseStream')); return Stream.empty(); } @override Future<ProductDetailsResponse> queryProductDetails(Set<String> identifiers) { log.add(MethodCall('queryProductDetails')); return Future.value( ProductDetailsResponse(productDetails: [], notFoundIDs: [])); } @override Future<bool> buyNonConsumable({required PurchaseParam purchaseParam}) { log.add(MethodCall('buyNonConsumable')); return Future.value(true); } @override Future<bool> buyConsumable({ required PurchaseParam purchaseParam, bool autoConsume = true, }) { log.add(MethodCall('buyConsumable', { "purchaseParam": purchaseParam, "autoConsume": autoConsume, })); return Future.value(true); } @override Future<void> completePurchase(PurchaseDetails purchase) { log.add(MethodCall('completePurchase')); return Future.value(null); } @override Future<void> restorePurchases({String? applicationUserName}) { log.add(MethodCall('restorePurchases')); return Future.value(null); } }
plugins/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart/0
{'file_path': 'plugins/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart', 'repo_id': 'plugins', 'token_count': 2039}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'fakes/fake_storekit_platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform(); setUpAll(() { SystemChannels.platform .setMockMethodCallHandler(fakeStoreKitPlatform.onMethodCall); }); group('present code redemption sheet', () { test('null', () async { expect( await InAppPurchaseStoreKitPlatformAddition() .presentCodeRedemptionSheet(), null); }); }); group('refresh receipt data', () { test('should refresh receipt data', () async { PurchaseVerificationData? receiptData = await InAppPurchaseStoreKitPlatformAddition() .refreshPurchaseVerificationData(); expect(receiptData, isNotNull); expect(receiptData!.source, kIAPSource); expect(receiptData.localVerificationData, 'refreshed receipt data'); expect(receiptData.serverVerificationData, 'refreshed receipt data'); }); }); }
plugins/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart/0
{'file_path': 'plugins/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart', 'repo_id': 'plugins', 'token_count': 501}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Abstract class for storing platform specific strings. abstract class AuthMessages { /// Constructs an instance of [AuthMessages]. const AuthMessages(); /// Returns all platform-specific messages as a map. Map<String, String> get args; }
plugins/packages/local_auth/local_auth_platform_interface/lib/types/auth_messages.dart/0
{'file_path': 'plugins/packages/local_auth/local_auth_platform_interface/lib/types/auth_messages.dart', 'repo_id': 'plugins', 'token_count': 106}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path_provider_android/path_provider_android.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); const String kTemporaryPath = 'temporaryPath'; const String kApplicationSupportPath = 'applicationSupportPath'; const String kLibraryPath = 'libraryPath'; const String kApplicationDocumentsPath = 'applicationDocumentsPath'; const String kExternalCachePaths = 'externalCachePaths'; const String kExternalStoragePaths = 'externalStoragePaths'; const String kDownloadsPath = 'downloadsPath'; group('PathProviderAndroid', () { late PathProviderAndroid pathProvider; final List<MethodCall> log = <MethodCall>[]; setUp(() async { pathProvider = PathProviderAndroid(); TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger .setMockMethodCallHandler(pathProvider.methodChannel, (MethodCall methodCall) async { log.add(methodCall); switch (methodCall.method) { case 'getTemporaryDirectory': return kTemporaryPath; case 'getApplicationSupportDirectory': return kApplicationSupportPath; case 'getLibraryDirectory': return kLibraryPath; case 'getApplicationDocumentsDirectory': return kApplicationDocumentsPath; case 'getExternalStorageDirectories': return <String>[kExternalStoragePaths]; case 'getExternalCacheDirectories': return <String>[kExternalCachePaths]; case 'getDownloadsDirectory': return kDownloadsPath; default: return null; } }); }); tearDown(() { log.clear(); }); // TODO(stuartmorgan): Change this to a test that it uses a different name, // to avoid potential confusion, once the SDK is changed to 2.8+. See // https://github.com/flutter/plugins/pull/4617#discussion_r774673962 test('channel name is compatible with shared method channel', () async { expect( pathProvider.methodChannel.name, 'plugins.flutter.io/path_provider'); }); test('getTemporaryPath', () async { final String? path = await pathProvider.getTemporaryPath(); expect( log, <Matcher>[isMethodCall('getTemporaryDirectory', arguments: null)], ); expect(path, kTemporaryPath); }); test('getApplicationSupportPath', () async { final String? path = await pathProvider.getApplicationSupportPath(); expect( log, <Matcher>[ isMethodCall('getApplicationSupportDirectory', arguments: null) ], ); expect(path, kApplicationSupportPath); }); test('getLibraryPath fails', () async { try { await pathProvider.getLibraryPath(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); test('getApplicationDocumentsPath', () async { final String? path = await pathProvider.getApplicationDocumentsPath(); expect( log, <Matcher>[ isMethodCall('getApplicationDocumentsDirectory', arguments: null) ], ); expect(path, kApplicationDocumentsPath); }); test('getExternalCachePaths succeeds', () async { final List<String>? result = await pathProvider.getExternalCachePaths(); expect( log, <Matcher>[isMethodCall('getExternalCacheDirectories', arguments: null)], ); expect(result!.length, 1); expect(result.first, kExternalCachePaths); }); for (final StorageDirectory? type in <StorageDirectory?>[ null, ...StorageDirectory.values ]) { test('getExternalStoragePaths (type: $type) android succeeds', () async { final List<String>? result = await pathProvider.getExternalStoragePaths(type: type); expect( log, <Matcher>[ isMethodCall( 'getExternalStorageDirectories', arguments: <String, dynamic>{'type': type?.index}, ) ], ); expect(result!.length, 1); expect(result.first, kExternalStoragePaths); }); } // end of for-loop test('getDownloadsPath fails', () async { try { await pathProvider.getDownloadsPath(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); }); }
plugins/packages/path_provider/path_provider_android/test/path_provider_android_test.dart/0
{'file_path': 'plugins/packages/path_provider/path_provider_android/test/path_provider_android_test.dart', 'repo_id': 'plugins', 'token_count': 1840}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; /// The macOS implementation of [PathProviderPlatform]. class PathProviderMacOS extends PathProviderPlatform { /// The method channel used to interact with the native platform. @visibleForTesting MethodChannel methodChannel = const MethodChannel('plugins.flutter.io/path_provider_macos'); /// Registers this class as the default instance of [PathProviderPlatform] static void registerWith() { PathProviderPlatform.instance = PathProviderMacOS(); } @override Future<String?> getTemporaryPath() { return methodChannel.invokeMethod<String>('getTemporaryDirectory'); } @override Future<String?> getApplicationSupportPath() async { final String? path = await methodChannel .invokeMethod<String>('getApplicationSupportDirectory'); if (path != null) { // Ensure the directory exists before returning it, for consistency with // other platforms. await Directory(path).create(recursive: true); } return path; } @override Future<String?> getLibraryPath() { return methodChannel.invokeMethod<String>('getLibraryDirectory'); } @override Future<String?> getApplicationDocumentsPath() { return methodChannel .invokeMethod<String>('getApplicationDocumentsDirectory'); } @override Future<String?> getExternalStoragePath() async { throw UnsupportedError('getExternalStoragePath is not supported on macOS'); } @override Future<List<String>?> getExternalCachePaths() async { throw UnsupportedError('getExternalCachePaths is not supported on macOS'); } @override Future<List<String>?> getExternalStoragePaths({ StorageDirectory? type, }) async { throw UnsupportedError('getExternalStoragePaths is not supported on macOS'); } @override Future<String?> getDownloadsPath() { return methodChannel.invokeMethod<String>('getDownloadsDirectory'); } }
plugins/packages/path_provider/path_provider_macos/lib/path_provider_macos.dart/0
{'file_path': 'plugins/packages/path_provider/path_provider_macos/lib/path_provider_macos.dart', 'repo_id': 'plugins', 'token_count': 662}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:quick_actions_android/quick_actions_android.dart'; import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$QuickActionsAndroid', () { late List<MethodCall> log; setUp(() { log = <MethodCall>[]; }); QuickActionsAndroid buildQuickActionsPlugin() { final QuickActionsAndroid quickActions = QuickActionsAndroid(); quickActions.channel .setMockMethodCallHandler((MethodCall methodCall) async { log.add(methodCall); return ''; }); return quickActions; } test('registerWith() registers correct instance', () { QuickActionsAndroid.registerWith(); expect(QuickActionsPlatform.instance, isA<QuickActionsAndroid>()); }); group('#initialize', () { test('passes getLaunchAction on launch method', () { final QuickActionsAndroid quickActions = buildQuickActionsPlugin(); quickActions.initialize((String type) {}); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), ], ); }); test('initialize', () async { final QuickActionsAndroid quickActions = buildQuickActionsPlugin(); final Completer<bool> quickActionsHandler = Completer<bool>(); await quickActions .initialize((_) => quickActionsHandler.complete(true)); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), ], ); log.clear(); expect(quickActionsHandler.future, completion(isTrue)); }); }); group('#setShortCutItems', () { test('passes shortcutItem through channel', () { final QuickActionsAndroid quickActions = buildQuickActionsPlugin(); quickActions.initialize((String type) {}); quickActions.setShortcutItems(<ShortcutItem>[ const ShortcutItem( type: 'test', localizedTitle: 'title', icon: 'icon.svg') ]); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), isMethodCall('setShortcutItems', arguments: <Map<String, String>>[ <String, String>{ 'type': 'test', 'localizedTitle': 'title', 'icon': 'icon.svg', } ]), ], ); }); test('setShortcutItems with demo data', () async { const String type = 'type'; const String localizedTitle = 'localizedTitle'; const String icon = 'icon'; final QuickActionsAndroid quickActions = buildQuickActionsPlugin(); await quickActions.setShortcutItems( const <ShortcutItem>[ ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon) ], ); expect( log, <Matcher>[ isMethodCall( 'setShortcutItems', arguments: <Map<String, String>>[ <String, String>{ 'type': type, 'localizedTitle': localizedTitle, 'icon': icon, } ], ), ], ); log.clear(); }); }); group('#clearShortCutItems', () { test('send clearShortcutItems through channel', () { final QuickActionsAndroid quickActions = buildQuickActionsPlugin(); quickActions.initialize((String type) {}); quickActions.clearShortcutItems(); expect( log, <Matcher>[ isMethodCall('getLaunchAction', arguments: null), isMethodCall('clearShortcutItems', arguments: null), ], ); }); test('clearShortcutItems', () { final QuickActionsAndroid quickActions = buildQuickActionsPlugin(); quickActions.clearShortcutItems(); expect( log, <Matcher>[ isMethodCall('clearShortcutItems', arguments: null), ], ); log.clear(); }); }); }); group('$ShortcutItem', () { test('Shortcut item can be constructed', () { const String type = 'type'; const String localizedTitle = 'title'; const String icon = 'foo'; const ShortcutItem item = ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon); expect(item.type, type); expect(item.localizedTitle, localizedTitle); expect(item.icon, icon); }); }); }
plugins/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart/0
{'file_path': 'plugins/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart', 'repo_id': 'plugins', 'token_count': 2141}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart'; export 'package:quick_actions_platform_interface/types/types.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/quick_actions_ios'); /// An implementation of [QuickActionsPlatform] for iOS. class QuickActionsIos extends QuickActionsPlatform { /// Registers this class as the default instance of [QuickActionsPlatform]. static void registerWith() { QuickActionsPlatform.instance = QuickActionsIos(); } /// The MethodChannel that is being used by this implementation of the plugin. @visibleForTesting MethodChannel get channel => _channel; @override Future<void> initialize(QuickActionHandler handler) async { channel.setMethodCallHandler((MethodCall call) async { assert(call.method == 'launch'); handler(call.arguments as String); }); final String? action = await channel.invokeMethod<String?>('getLaunchAction'); if (action != null) { handler(action); } } @override Future<void> setShortcutItems(List<ShortcutItem> items) async { final List<Map<String, String?>> itemsList = items.map(_serializeItem).toList(); await channel.invokeMethod<void>('setShortcutItems', itemsList); } @override Future<void> clearShortcutItems() => channel.invokeMethod<void>('clearShortcutItems'); Map<String, String?> _serializeItem(ShortcutItem item) { return <String, String?>{ 'type': item.type, 'localizedTitle': item.localizedTitle, 'icon': item.icon, }; } }
plugins/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart/0
{'file_path': 'plugins/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart', 'repo_id': 'plugins', 'token_count': 587}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import '../platform_interface/javascript_channel_registry.dart'; import '../platform_interface/platform_interface.dart'; import '../types/types.dart'; /// A [WebViewPlatformController] that uses a method channel to control the webview. class MethodChannelWebViewPlatform implements WebViewPlatformController { /// Constructs an instance that will listen for webviews broadcasting to the /// given [id], using the given [WebViewPlatformCallbacksHandler]. MethodChannelWebViewPlatform( int id, this._platformCallbacksHandler, this._javascriptChannelRegistry, ) : assert(_platformCallbacksHandler != null), _channel = MethodChannel('plugins.flutter.io/webview_$id') { _channel.setMethodCallHandler(_onMethodCall); } final JavascriptChannelRegistry _javascriptChannelRegistry; final WebViewPlatformCallbacksHandler _platformCallbacksHandler; final MethodChannel _channel; static const MethodChannel _cookieManagerChannel = MethodChannel('plugins.flutter.io/cookie_manager'); Future<bool?> _onMethodCall(MethodCall call) async { switch (call.method) { case 'javascriptChannelMessage': final String channel = call.arguments['channel']! as String; final String message = call.arguments['message']! as String; _javascriptChannelRegistry.onJavascriptChannelMessage(channel, message); return true; case 'navigationRequest': return await _platformCallbacksHandler.onNavigationRequest( url: call.arguments['url']! as String, isForMainFrame: call.arguments['isForMainFrame']! as bool, ); case 'onPageFinished': _platformCallbacksHandler .onPageFinished(call.arguments['url']! as String); return null; case 'onProgress': _platformCallbacksHandler.onProgress(call.arguments['progress'] as int); return null; case 'onPageStarted': _platformCallbacksHandler .onPageStarted(call.arguments['url']! as String); return null; case 'onWebResourceError': _platformCallbacksHandler.onWebResourceError( WebResourceError( errorCode: call.arguments['errorCode']! as int, description: call.arguments['description']! as String, // iOS doesn't support `failingUrl`. failingUrl: call.arguments['failingUrl'] as String?, domain: call.arguments['domain'] as String?, errorType: call.arguments['errorType'] == null ? null : WebResourceErrorType.values.firstWhere( (WebResourceErrorType type) { return type.toString() == '$WebResourceErrorType.${call.arguments['errorType']}'; }, ), ), ); return null; } throw MissingPluginException( '${call.method} was invoked but has no handler', ); } @override Future<void> loadFile(String absoluteFilePath) async { assert(absoluteFilePath != null); try { return await _channel.invokeMethod<void>('loadFile', absoluteFilePath); } on PlatformException catch (ex) { if (ex.code == 'loadFile_failed') { throw ArgumentError(ex.message); } rethrow; } } @override Future<void> loadFlutterAsset(String key) async { assert(key.isNotEmpty); try { return await _channel.invokeMethod<void>('loadFlutterAsset', key); } on PlatformException catch (ex) { if (ex.code == 'loadFlutterAsset_invalidKey') { throw ArgumentError(ex.message); } rethrow; } } @override Future<void> loadHtmlString( String html, { String? baseUrl, }) async { assert(html != null); return _channel.invokeMethod<void>('loadHtmlString', <String, dynamic>{ 'html': html, 'baseUrl': baseUrl, }); } @override Future<void> loadUrl( String url, Map<String, String>? headers, ) async { assert(url != null); return _channel.invokeMethod<void>('loadUrl', <String, dynamic>{ 'url': url, 'headers': headers, }); } @override Future<void> loadRequest(WebViewRequest request) async { assert(request != null); return _channel.invokeMethod<void>('loadRequest', <String, dynamic>{ 'request': request.toJson(), }); } @override Future<String?> currentUrl() => _channel.invokeMethod<String>('currentUrl'); @override Future<bool> canGoBack() => _channel.invokeMethod<bool>('canGoBack').then((bool? result) => result!); @override Future<bool> canGoForward() => _channel .invokeMethod<bool>('canGoForward') .then((bool? result) => result!); @override Future<void> goBack() => _channel.invokeMethod<void>('goBack'); @override Future<void> goForward() => _channel.invokeMethod<void>('goForward'); @override Future<void> reload() => _channel.invokeMethod<void>('reload'); @override Future<void> clearCache() => _channel.invokeMethod<void>('clearCache'); @override Future<void> updateSettings(WebSettings settings) async { final Map<String, dynamic> updatesMap = _webSettingsToMap(settings); if (updatesMap.isNotEmpty) { await _channel.invokeMethod<void>('updateSettings', updatesMap); } } @override Future<String> evaluateJavascript(String javascript) { return _channel .invokeMethod<String>('evaluateJavascript', javascript) .then((String? result) => result!); } @override Future<void> runJavascript(String javascript) async { await _channel.invokeMethod<String>('runJavascript', javascript); } @override Future<String> runJavascriptReturningResult(String javascript) { return _channel .invokeMethod<String>('runJavascriptReturningResult', javascript) .then((String? result) => result!); } @override Future<void> addJavascriptChannels(Set<String> javascriptChannelNames) { return _channel.invokeMethod<void>( 'addJavascriptChannels', javascriptChannelNames.toList()); } @override Future<void> removeJavascriptChannels(Set<String> javascriptChannelNames) { return _channel.invokeMethod<void>( 'removeJavascriptChannels', javascriptChannelNames.toList()); } @override Future<String?> getTitle() => _channel.invokeMethod<String>('getTitle'); @override Future<void> scrollTo(int x, int y) { return _channel.invokeMethod<void>('scrollTo', <String, int>{ 'x': x, 'y': y, }); } @override Future<void> scrollBy(int x, int y) { return _channel.invokeMethod<void>('scrollBy', <String, int>{ 'x': x, 'y': y, }); } @override Future<int> getScrollX() => _channel.invokeMethod<int>('getScrollX').then((int? result) => result!); @override Future<int> getScrollY() => _channel.invokeMethod<int>('getScrollY').then((int? result) => result!); /// Method channel implementation for [WebViewPlatform.clearCookies]. static Future<bool> clearCookies() { return _cookieManagerChannel .invokeMethod<bool>('clearCookies') .then<bool>((dynamic result) => result! as bool); } /// Method channel implementation for [WebViewPlatform.setCookie]. static Future<void> setCookie(WebViewCookie cookie) { return _cookieManagerChannel.invokeMethod<void>( 'setCookie', cookie.toJson()); } static Map<String, dynamic> _webSettingsToMap(WebSettings? settings) { final Map<String, dynamic> map = <String, dynamic>{}; void _addIfNonNull(String key, dynamic value) { if (value == null) { return; } map[key] = value; } void _addSettingIfPresent<T>(String key, WebSetting<T> setting) { if (!setting.isPresent) { return; } map[key] = setting.value; } _addIfNonNull('jsMode', settings!.javascriptMode?.index); _addIfNonNull('hasNavigationDelegate', settings.hasNavigationDelegate); _addIfNonNull('hasProgressTracking', settings.hasProgressTracking); _addIfNonNull('debuggingEnabled', settings.debuggingEnabled); _addIfNonNull( 'gestureNavigationEnabled', settings.gestureNavigationEnabled); _addIfNonNull( 'allowsInlineMediaPlayback', settings.allowsInlineMediaPlayback); _addSettingIfPresent('userAgent', settings.userAgent); _addIfNonNull('zoomEnabled', settings.zoomEnabled); return map; } /// Converts a [CreationParams] object to a map as expected by `platform_views` channel. /// /// This is used for the `creationParams` argument of the platform views created by /// [AndroidWebViewBuilder] and [CupertinoWebViewBuilder]. static Map<String, dynamic> creationParamsToMap( CreationParams creationParams, { bool usesHybridComposition = false, }) { return <String, dynamic>{ 'initialUrl': creationParams.initialUrl, 'settings': _webSettingsToMap(creationParams.webSettings), 'javascriptChannelNames': creationParams.javascriptChannelNames.toList(), 'userAgent': creationParams.userAgent, 'autoMediaPlaybackPolicy': creationParams.autoMediaPlaybackPolicy.index, 'usesHybridComposition': usesHybridComposition, 'backgroundColor': creationParams.backgroundColor?.value, 'cookies': creationParams.cookies .map((WebViewCookie cookie) => cookie.toJson()) .toList() }; } }
plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/method_channel/webview_method_channel.dart/0
{'file_path': 'plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/method_channel/webview_method_channel.dart', 'repo_id': 'plugins', 'token_count': 3522}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:html' as html; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:webview_flutter_web_example/web_view.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // URLs to navigate to in tests. These need to be URLs that we are confident will // always be accessible, and won't do redirection. (E.g., just // 'https://www.google.com/' will sometimes redirect traffic that looks // like it's coming from a bot, which is true of these tests). const String primaryUrl = 'https://flutter.dev/'; const String secondaryUrl = 'https://www.google.com/robots.txt'; testWidgets('initialUrl', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, ), ), ); await controllerCompleter.future; // Assert an iframe has been rendered to the DOM with the correct src attribute. final html.IFrameElement? element = html.document.querySelector('iframe') as html.IFrameElement?; expect(element, isNotNull); expect(element!.src, primaryUrl); }); testWidgets('loadUrl', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, ), ), ); final WebViewController controller = await controllerCompleter.future; await controller.loadUrl(secondaryUrl); // Assert an iframe has been rendered to the DOM with the correct src attribute. final html.IFrameElement? element = html.document.querySelector('iframe') as html.IFrameElement?; expect(element, isNotNull); expect(element!.src, secondaryUrl); }); }
plugins/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart/0
{'file_path': 'plugins/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart', 'repo_id': 'plugins', 'token_count': 933}
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:flutter_plugin_tools/src/common/pub_version_finder.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:mockito/mockito.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:test/test.dart'; void main() { test('Package does not exist.', () async { final MockClient mockClient = MockClient((http.Request request) async { return http.Response('', 404); }); final PubVersionFinder finder = PubVersionFinder(httpClient: mockClient); final PubVersionFinderResponse response = await finder.getPackageVersion(packageName: 'some_package'); expect(response.versions, isEmpty); expect(response.result, PubVersionFinderResult.noPackageFound); expect(response.httpResponse.statusCode, 404); expect(response.httpResponse.body, ''); }); test('HTTP error when getting versions from pub', () async { final MockClient mockClient = MockClient((http.Request request) async { return http.Response('', 400); }); final PubVersionFinder finder = PubVersionFinder(httpClient: mockClient); final PubVersionFinderResponse response = await finder.getPackageVersion(packageName: 'some_package'); expect(response.versions, isEmpty); expect(response.result, PubVersionFinderResult.fail); expect(response.httpResponse.statusCode, 400); expect(response.httpResponse.body, ''); }); test('Get a correct list of versions when http response is OK.', () async { const Map<String, dynamic> httpResponse = <String, dynamic>{ 'name': 'some_package', 'versions': <String>[ '0.0.1', '0.0.2', '0.0.2+2', '0.1.1', '0.0.1+1', '0.1.0', '0.2.0', '0.1.0+1', '0.0.2+1', '2.0.0', '1.2.0', '1.0.0', ], }; final MockClient mockClient = MockClient((http.Request request) async { return http.Response(json.encode(httpResponse), 200); }); final PubVersionFinder finder = PubVersionFinder(httpClient: mockClient); final PubVersionFinderResponse response = await finder.getPackageVersion(packageName: 'some_package'); expect(response.versions, <Version>[ Version.parse('2.0.0'), Version.parse('1.2.0'), Version.parse('1.0.0'), Version.parse('0.2.0'), Version.parse('0.1.1'), Version.parse('0.1.0+1'), Version.parse('0.1.0'), Version.parse('0.0.2+2'), Version.parse('0.0.2+1'), Version.parse('0.0.2'), Version.parse('0.0.1+1'), Version.parse('0.0.1'), ]); expect(response.result, PubVersionFinderResult.success); expect(response.httpResponse.statusCode, 200); expect(response.httpResponse.body, json.encode(httpResponse)); }); } class MockProcessResult extends Mock implements ProcessResult {}
plugins/script/tool/test/common/pub_version_finder_test.dart/0
{'file_path': 'plugins/script/tool/test/common/pub_version_finder_test.dart', 'repo_id': 'plugins', 'token_count': 1182}
import 'dart:async' show Future; import 'dart:io' show File; import 'package:flutter/services.dart' show MethodChannel; import 'package:image_picker/image_picker.dart' show ImagePicker, ImageSource; import 'package:meta/meta.dart' show required; class FilePicker { static const MethodChannel _channel = const MethodChannel('file_picker'); static Future<File> get _getPDF async { var path = await _channel.invokeMethod('pickPDF'); return path == null ? null : new File(path); } static Future<File> _getImage(ImageSource type) async { return await ImagePicker.pickImage(source: type); } static Future<File> getFilePath({@required FileType type}) async { switch (type) { case FileType.PDF: return _getPDF; case FileType.IMAGE: return _getImage(ImageSource.gallery); case FileType.CAPTURE: return _getImage(ImageSource.camera); } return null; } } enum FileType { PDF, IMAGE, CAPTURE, }
plugins_flutter_file_picker/lib/file_picker.dart/0
{'file_path': 'plugins_flutter_file_picker/lib/file_picker.dart', 'repo_id': 'plugins_flutter_file_picker', 'token_count': 349}
export './firebase/firebase.dart';
pnyws/lib/data/network/network.dart/0
{'file_path': 'pnyws/lib/data/network/network.dart', 'repo_id': 'pnyws', 'token_count': 13}
import 'package:pnyws/environments/environment.dart'; import 'package:pnyws/main.dart' as def; void main() => def.main(delay: 2, environment: Environment.DEVELOPMENT);
pnyws/lib/main_dev.dart/0
{'file_path': 'pnyws/lib/main_dev.dart', 'repo_id': 'pnyws', 'token_count': 57}
import 'package:flutter/foundation.dart'; import 'package:pnyws/environments/environment.dart'; class Session { Session({@required Environment environment}) : assert(environment != null), isMock = environment.isMock; final bool isMock; }
pnyws/lib/services/session.dart/0
{'file_path': 'pnyws/lib/services/session.dart', 'repo_id': 'pnyws', 'token_count': 85}
import 'package:flutter/material.dart'; import 'package:pnyws/constants/mk_colors.dart'; import 'package:pnyws/constants/mk_style.dart'; import 'package:pnyws/widgets/theme_provider.dart'; class SecondaryButton extends StatelessWidget { const SecondaryButton({ Key key, @required this.child, @required this.onPressed, }) : super(key: key); final Widget child; final VoidCallback onPressed; @override Widget build(BuildContext context) { return RawMaterialButton( constraints: BoxConstraints(minHeight: 0), padding: EdgeInsets.symmetric(vertical: 16, horizontal: 48), shape: StadiumBorder( side: MkBorderSide(width: 4, color: Colors.white), ), fillColor: MkColors.secondaryAccent, child: DefaultTextStyle(child: child, style: context.theme.button), onPressed: onPressed, ); } }
pnyws/lib/widgets/secondary_button.dart/0
{'file_path': 'pnyws/lib/widgets/secondary_button.dart', 'repo_id': 'pnyws', 'token_count': 318}
import 'package:flame/flame.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'game.dart'; import 'input.dart'; main() async { Flame.audio.disableLog(); await Flame.util.initialDimensions(); MyGame game = MyGame(); runApp(MaterialApp( routes: { '/': (BuildContext ctx) => Scaffold(body: WillPopScope( onWillPop: () async { game.pause(); return false; }, child: game.widget, )), }, )); Input(game).attach(); }
pocket-dungeons/game/lib/main.dart/0
{'file_path': 'pocket-dungeons/game/lib/main.dart', 'repo_id': 'pocket-dungeons', 'token_count': 222}
import 'package:flutter/widgets.dart'; import 'package:provider_example/core/enums/viewstate.dart'; class BaseModel extends ChangeNotifier { ViewState _state = ViewState.Idle; ViewState get state => _state; void setState(ViewState viewState) { _state = viewState; notifyListeners(); } }
provider-example/lib/core/viewmodels/base_model.dart/0
{'file_path': 'provider-example/lib/core/viewmodels/base_model.dart', 'repo_id': 'provider-example', 'token_count': 103}
import 'package:flutter/material.dart'; import 'package:provider_example/ui/shared/text_styles.dart'; import 'package:provider_example/ui/shared/ui_helpers.dart'; class LoginHeader extends StatelessWidget { final TextEditingController controller; final String validationMessage; LoginHeader({@required this.controller, this.validationMessage}); @override Widget build(BuildContext context) { return Column(children: <Widget>[ Text('Login', style: headerStyle), UIHelper.verticalSpaceMedium(), Text('Enter a number between 1 - 10', style: subHeaderStyle), LoginTextField(controller), this.validationMessage != null ? Text(validationMessage, style: TextStyle(color: Colors.red)) : Container() ]); } } class LoginTextField extends StatelessWidget { final TextEditingController controller; LoginTextField(this.controller); @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.symmetric(horizontal: 15.0), margin: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0), height: 50.0, alignment: Alignment.centerLeft, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10.0)), child: TextField( decoration: InputDecoration.collapsed(hintText: 'User Id'), controller: controller), ); } }
provider-example/lib/ui/widgets/login_header.dart/0
{'file_path': 'provider-example/lib/ui/widgets/login_header.dart', 'repo_id': 'provider-example', 'token_count': 491}
import 'dart:developer'; import 'package:pub_updater/pub_updater.dart'; Future<void> main() async { const packageName = 'my_package'; const currentVersion = '0.1.0'; // Initialize an instance of PubUpdater. final pubUpdater = PubUpdater(); // Check whether a package is up to date. final isUpToDate = await pubUpdater.isUpToDate( packageName: packageName, currentVersion: currentVersion, ); if (!isUpToDate) { // Upgrade to the latest version if not up to date. await pubUpdater.update(packageName: packageName); } // You can also query the latest version available for a specific package. final latestVersion = await pubUpdater.getLatestVersion(packageName); log(latestVersion); }
pub_updater/example/main.dart/0
{'file_path': 'pub_updater/example/main.dart', 'repo_id': 'pub_updater', 'token_count': 235}
name: pubviz version: 2.5.5 author: Kevin Moore <kevmoo@google.com> description: >- A tool to visualize package dependencies and version constraints in your Dart project. homepage: https://github.com/kevmoo/pubviz environment: sdk: '>=2.2.0 <3.0.0' dependencies: args: ^1.4.1 build_cli_annotations: ^1.0.0 collection: ^1.0.0 gviz: ^0.3.0 http: '>=0.11.1+3 <0.13.0' io: ^0.3.2+1 path: ^1.0.0 pubspec_parse: ^0.1.0 pub_semver: ^1.0.0 stack_trace: ^1.6.0 yaml: ^2.0.0 dev_dependencies: build_cli: ^1.2.1 build_runner: ^1.0.0 build_verify: ^1.0.0 build_web_compilers: '>=1.0.0 <3.0.0' js: ^0.6.1 pedantic: ^1.1.0 test: ^1.0.0 test_descriptor: ^1.0.3 test_process: ^1.0.1 executables: pubviz: null
pubviz/pubspec.yaml/0
{'file_path': 'pubviz/pubspec.yaml', 'repo_id': 'pubviz', 'token_count': 374}
export 'cubit/capture_cubit.dart'; export 'cubit/capture_cubit_state.dart'; export 'view/capture_end_page.dart'; export 'view/capture_page.dart';
put-flutter-to-work/flutter_nps/lib/capture/capture.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/lib/capture/capture.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 64}
import 'package:flutter/material.dart'; abstract class NpsColors { static const colorPrimary1 = Color(0xFF041E3C); static const colorBlueDash = Color(0xFF00529E); static const colorSecondary = Color(0xFF6200EE); static const colorGrey1 = Color(0xFF4A4A4A); static const colorGrey2 = Color(0xFF9FA2AF); static const colorGrey5 = Color(0xFFF8F9FA); static const colorWhite = Color(0xFFFFFFFF); static const transparent = Colors.transparent; }
put-flutter-to-work/flutter_nps/packages/app_ui/lib/src/colors/colors.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/packages/app_ui/lib/src/colors/colors.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 159}
import 'dart:async'; import 'package:app_ui/app_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; void main() { group('AnswerChips', () { final chips = ['a', 'b', 'c']; final selectedChipIndices = [0, 1]; testWidgets( 'renders 3 chips', (tester) async { await tester.pumpApp( AnswerChips( chips: chips, selectedChipIndices: selectedChipIndices, chipToggleCallback: (_) {}, ), ); expect(find.byType(ActionChip), findsNWidgets(3)); }, ); testWidgets( 'tap callback with first', (tester) async { final completer = Completer<int>(); await tester.pumpApp( AnswerChips( chips: chips, selectedChipIndices: selectedChipIndices, chipToggleCallback: completer.complete, ), ); await tester.tap(find.byType(ActionChip).first); expect(completer.isCompleted, isTrue); expect(await completer.future, equals(0)); }, ); testWidgets( 'tap callback with last index', (tester) async { final completer = Completer<int>(); await tester.pumpApp( AnswerChips( chips: chips, selectedChipIndices: selectedChipIndices, chipToggleCallback: completer.complete, ), ); await tester.tap(find.byType(ActionChip).last); expect(completer.isCompleted, isTrue); expect(await completer.future, equals(2)); }, ); }); }
put-flutter-to-work/flutter_nps/packages/app_ui/test/src/widgets/answer_chips_test.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/packages/app_ui/test/src/widgets/answer_chips_test.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 783}
import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:nps_repository/nps_repository.dart'; void main() { test('ScoreSubmitModel toJson translates corectly', () { const scoreSubmitModel = CustomerSatisfaction(chipIndexes: [0, 1], score: 1); final result = scoreSubmitModel.toJson(); expect(result, jsonDecode(jsonEncode(scoreSubmitModel))); }); }
put-flutter-to-work/flutter_nps/packages/nps_repository/test/src/score_submit_model_test.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/packages/nps_repository/test/src/score_submit_model_test.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 149}
import 'package:flutter_nps/capture/capture.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('CaptureCubitState', () { final initialCaptureCubitState = CaptureCubitState.initial(); test('initial values are set to score: -1 and chipIndexes: []', () { expect(initialCaptureCubitState.chipIndexes, isEmpty); expect(initialCaptureCubitState.score, equals(-1)); }); test('initial state props returns array of props', () { expect( initialCaptureCubitState.props, contains(initialCaptureCubitState.score), ); expect( initialCaptureCubitState.props, contains(initialCaptureCubitState.chipIndexes), ); }); group('copyWith', () { final capture = CaptureCubitState.initial(); test('copies CaptureCubitState with changed values', () { expect(capture.score, equals(-1)); expect(capture.chipIndexes, equals(<int>[])); final firstCapture = capture.copyWith(score: 1); expect(firstCapture.score, equals(1)); expect(firstCapture.chipIndexes, equals(<int>[])); final secondCapture = firstCapture.copyWith(chipIndexes: [1]); expect(secondCapture.score, equals(1)); expect(secondCapture.chipIndexes, equals([1])); }); }); }); }
put-flutter-to-work/flutter_nps/test/capture/cubit/capture_state_test.dart/0
{'file_path': 'put-flutter-to-work/flutter_nps/test/capture/cubit/capture_state_test.dart', 'repo_id': 'put-flutter-to-work', 'token_count': 503}
// import 'package:example_app/_constants.dart'; import 'package:quidpay/quidpay.dart'; import '_bootstrap.dart'; void fetch() async { await Banks().fetch(); } void main() async { init(); fetch(); }
quidpay.dart/example/banks.dart/0
{'file_path': 'quidpay.dart/example/banks.dart', 'repo_id': 'quidpay.dart', 'token_count': 77}