Skip to content

Commit f92ba2d

Browse files
authored
Replace MockUsage with Usage.test in build tests (flutter#67670)
1 parent 41325b5 commit f92ba2d

File tree

7 files changed

+64
-61
lines changed

7 files changed

+64
-61
lines changed

packages/flutter_tools/lib/src/reporting/usage.dart

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ class _DefaultUsage implements Usage {
198198
final bool usingLogFile = logFilePath != null && logFilePath.isNotEmpty;
199199

200200
analyticsIOFactory ??= _defaultAnalyticsIOFactory;
201+
_clock = globals.systemClock;
201202

202203
if (// To support testing, only allow other signals to supress analytics
203204
// when analytics are not being shunted to a file.
@@ -272,13 +273,15 @@ class _DefaultUsage implements Usage {
272273
}
273274

274275
_DefaultUsage.test() :
275-
_suppressAnalytics = true,
276-
_analytics = AnalyticsMock();
276+
_suppressAnalytics = false,
277+
_analytics = AnalyticsMock(true),
278+
_clock = SystemClock.fixed(DateTime(2020, 10, 8));
277279

278280
Analytics _analytics;
279281

280282
bool _printedWelcome = false;
281283
bool _suppressAnalytics = false;
284+
SystemClock _clock;
282285

283286
@override
284287
bool get isFirstRun => _analytics.firstRun;
@@ -310,7 +313,7 @@ class _DefaultUsage implements Usage {
310313

311314
final Map<String, String> paramsWithLocalTime = <String, String>{
312315
...?parameters,
313-
cdKey(CustomDimensions.localTime): formatDateTime(globals.systemClock.now()),
316+
cdKey(CustomDimensions.localTime): formatDateTime(_clock.now()),
314317
};
315318
_analytics.sendScreenView(command, parameters: paramsWithLocalTime);
316319
}
@@ -329,7 +332,7 @@ class _DefaultUsage implements Usage {
329332

330333
final Map<String, String> paramsWithLocalTime = <String, String>{
331334
...?parameters,
332-
cdKey(CustomDimensions.localTime): formatDateTime(globals.systemClock.now()),
335+
cdKey(CustomDimensions.localTime): formatDateTime(_clock.now()),
333336
};
334337

335338
_analytics.sendEvent(

packages/flutter_tools/test/commands.shard/hermetic/build_linux_test.dart

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import 'package:flutter_tools/src/commands/build_linux.dart';
1515
import 'package:flutter_tools/src/features.dart';
1616
import 'package:flutter_tools/src/project.dart';
1717
import 'package:flutter_tools/src/reporting/reporting.dart';
18-
import 'package:mockito/mockito.dart';
1918
import 'package:process/process.dart';
2019

2120
import '../../src/common.dart';
@@ -45,12 +44,12 @@ void main() {
4544

4645
FileSystem fileSystem;
4746
ProcessManager processManager;
48-
MockUsage usage;
47+
Usage usage;
4948

5049
setUp(() {
5150
fileSystem = MemoryFileSystem.test();
5251
Cache.flutterRoot = _kTestFlutterRoot;
53-
usage = MockUsage();
52+
usage = Usage.test();
5453
});
5554

5655
// Creates the mock files necessary to look like a Flutter project.
@@ -399,11 +398,15 @@ set(BINARY_NAME "fizz_bar")
399398
..createSync(recursive: true)
400399
..writeAsBytesSync(List<int>.filled(10000, 0));
401400

402-
await createTestCommandRunner(command).run(
403-
const <String>['build', 'linux', '--no-pub', '--analyze-size']
401+
// Capture Usage.test() events.
402+
final StringBuffer buffer = await capturedConsolePrint(() =>
403+
createTestCommandRunner(command).run(
404+
const <String>['build', 'linux', '--no-pub', '--analyze-size']
405+
)
404406
);
407+
405408
expect(testLogger.statusText, contains('A summary of your Linux bundle analysis can be found at'));
406-
verify(usage.sendEvent('code-size-analysis', 'linux')).called(1);
409+
expect(buffer.toString(), contains('event {category: code-size-analysis, action: linux, label: null, value: null, cd33:'));
407410
}, overrides: <Type, Generator>{
408411
FileSystem: () => fileSystem,
409412
ProcessManager: () => processManager,
@@ -412,5 +415,3 @@ set(BINARY_NAME "fizz_bar")
412415
Usage: () => usage,
413416
});
414417
}
415-
416-
class MockUsage extends Mock implements Usage {}

packages/flutter_tools/test/commands.shard/hermetic/build_macos_test.dart

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5+
import 'dart:async';
6+
57
import 'package:args/command_runner.dart';
68
import 'package:file/memory.dart';
79
import 'package:flutter_tools/src/base/file_system.dart';
@@ -15,7 +17,6 @@ import 'package:flutter_tools/src/features.dart';
1517
import 'package:flutter_tools/src/ios/xcodeproj.dart';
1618
import 'package:flutter_tools/src/project.dart';
1719
import 'package:flutter_tools/src/reporting/reporting.dart';
18-
import 'package:mockito/mockito.dart';
1920
import 'package:process/process.dart';
2021

2122
import '../../src/common.dart';
@@ -49,15 +50,15 @@ final Platform notMacosPlatform = FakePlatform(
4950

5051
void main() {
5152
FileSystem fileSystem;
52-
MockUsage usage;
53+
Usage usage;
5354

5455
setUpAll(() {
5556
Cache.disableLocking();
5657
});
5758

5859
setUp(() {
5960
fileSystem = MemoryFileSystem.test();
60-
usage = MockUsage();
61+
usage = Usage.test();
6162
});
6263

6364
// Sets up the minimal mock project files necessary to look like a Flutter project.
@@ -329,12 +330,15 @@ void main() {
329330
..createSync(recursive: true)
330331
..writeAsBytesSync(List<int>.generate(10000, (int index) => 0));
331332

332-
await createTestCommandRunner(command).run(
333-
const <String>['build', 'macos', '--no-pub', '--analyze-size']
333+
// Capture Usage.test() events.
334+
final StringBuffer buffer = await capturedConsolePrint(() =>
335+
createTestCommandRunner(command).run(
336+
const <String>['build', 'macos', '--no-pub', '--analyze-size']
337+
)
334338
);
335339

336340
expect(testLogger.statusText, contains('A summary of your macOS bundle analysis can be found at'));
337-
verify(usage.sendEvent('code-size-analysis', 'macos')).called(1);
341+
expect(buffer.toString(), contains('event {category: code-size-analysis, action: macos, label: null, value: null, cd33:'));
338342
}, overrides: <Type, Generator>{
339343
FileSystem: () => fileSystem,
340344
ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
@@ -360,5 +364,3 @@ void main() {
360364
Usage: () => usage,
361365
});
362366
}
363-
364-
class MockUsage extends Mock implements Usage {}

packages/flutter_tools/test/commands.shard/hermetic/build_windows_test.dart

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ void main() {
4343

4444
ProcessManager processManager;
4545
MockVisualStudio mockVisualStudio;
46-
MockUsage usage;
46+
Usage usage;
4747

4848
setUpAll(() {
4949
Cache.disableLocking();
@@ -53,7 +53,7 @@ void main() {
5353
fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows);
5454
Cache.flutterRoot = flutterRoot;
5555
mockVisualStudio = MockVisualStudio();
56-
usage = MockUsage();
56+
usage = Usage.test();
5757
});
5858

5959
// Creates the mock files necessary to look like a Flutter project.
@@ -403,12 +403,15 @@ C:\foo\windows\runner\main.cpp(17,1): error C2065: 'Baz': undeclared identifier
403403
}),
404404
]);
405405

406-
await createTestCommandRunner(command).run(
407-
const <String>['windows', '--no-pub', '--analyze-size']
406+
// Capture Usage.test() events.
407+
final StringBuffer buffer = await capturedConsolePrint(() =>
408+
createTestCommandRunner(command).run(
409+
const <String>['windows', '--no-pub', '--analyze-size']
410+
)
408411
);
409412

410413
expect(testLogger.statusText, contains('A summary of your Windows bundle analysis can be found at'));
411-
verify(usage.sendEvent('code-size-analysis', 'windows')).called(1);
414+
expect(buffer.toString(), contains('event {category: code-size-analysis, action: windows, label: null, value: null, cd33:'));
412415
}, overrides: <Type, Generator>{
413416
FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true),
414417
FileSystem: () => fileSystem,
@@ -420,4 +423,3 @@ C:\foo\windows\runner\main.cpp(17,1): error C2065: 'Baz': undeclared identifier
420423
}
421424

422425
class MockVisualStudio extends Mock implements VisualStudio {}
423-
class MockUsage extends Mock implements Usage {}

packages/flutter_tools/test/commands.shard/hermetic/daemon_test.dart

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,7 @@ void main() {
8181
});
8282

8383
testUsingContext('printStatus should log to stdout when logToStdout is enabled', () async {
84-
final StringBuffer buffer = StringBuffer();
85-
86-
await runZoned<Future<void>>(() async {
84+
final StringBuffer buffer = await capturedConsolePrint(() {
8785
final StreamController<Map<String, dynamic>> commands = StreamController<Map<String, dynamic>>();
8886
final StreamController<Map<String, dynamic>> responses = StreamController<Map<String, dynamic>>();
8987
daemon = Daemon(
@@ -93,11 +91,8 @@ void main() {
9391
logToStdout: true,
9492
);
9593
globals.printStatus('daemon.logMessage test');
96-
// Service the event loop.
97-
await Future<void>.value();
98-
}, zoneSpecification: ZoneSpecification(print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
99-
buffer.writeln(line);
100-
}));
94+
return Future<void>.value();
95+
});
10196

10297
expect(buffer.toString().trim(), 'daemon.logMessage test');
10398
}, overrides: <Type, Generator>{

packages/flutter_tools/test/commands.shard/hermetic/run_test.dart

Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5+
import 'dart:async';
6+
57
import 'package:file/file.dart';
68
import 'package:file/memory.dart';
79
import 'package:flutter_tools/src/application_package.dart';
@@ -143,13 +145,13 @@ void main() {
143145
Artifacts artifacts;
144146
MockCache mockCache;
145147
MockProcessManager mockProcessManager;
146-
MockUsage mockUsage;
148+
Usage usage;
147149
Directory tempDir;
148150

149151
setUp(() {
150152
artifacts = Artifacts.test();
151153
mockCache = MockCache();
152-
mockUsage = MockUsage();
154+
usage = Usage.test();
153155
fs = MemoryFileSystem.test();
154156
mockProcessManager = MockProcessManager();
155157

@@ -374,41 +376,27 @@ void main() {
374376
..writeAsStringSync('# Hello, World');
375377
globals.fs.currentDirectory = tempDir;
376378

377-
try {
378-
await createTestCommandRunner(command).run(<String>[
379+
// Capture Usage.test() events.
380+
final StringBuffer buffer = await capturedConsolePrint(() =>
381+
expectToolExitLater(createTestCommandRunner(command).run(<String>[
379382
'run',
380383
'--no-pub',
381384
'--no-hot',
382-
]);
383-
fail('Exception expected');
384-
} on ToolExit catch (e) {
385-
// We expect a ToolExit because app does not start
386-
expect(e.message, null);
387-
} on Exception catch (e) {
388-
fail('ToolExit expected, got $e');
389-
}
390-
final List<dynamic> captures = verify(mockUsage.sendCommand(
391-
captureAny,
392-
parameters: captureAnyNamed('parameters'),
393-
)).captured;
394-
expect(captures[0], 'run');
395-
final Map<String, String> parameters = captures[1] as Map<String, String>;
396-
397-
expect(parameters[cdKey(CustomDimensions.commandRunIsEmulator)], 'false');
398-
expect(parameters[cdKey(CustomDimensions.commandRunTargetName)], 'ios');
399-
expect(parameters[cdKey(CustomDimensions.commandRunProjectHostLanguage)], 'swift');
400-
expect(parameters[cdKey(CustomDimensions.commandRunTargetOsVersion)], 'iOS 13');
401-
expect(parameters[cdKey(CustomDimensions.commandRunModeName)], 'debug');
402-
expect(parameters[cdKey(CustomDimensions.commandRunProjectModule)], 'false');
403-
expect(parameters.containsKey(cdKey(CustomDimensions.commandRunAndroidEmbeddingVersion)), false);
385+
]), isNull)
386+
);
387+
// Allow any CustomDimensions.localTime (cd33) timestamp.
388+
final RegExp usageRegexp = RegExp(
389+
'screenView {cd3: false, cd4: ios, cd22: iOS 13, cd23: debug, cd18: false, cd15: swift, cd31: false, cd47: false, cd33: .*, viewName: run'
390+
);
391+
expect(buffer.toString(), matches(usageRegexp));
404392
}, overrides: <Type, Generator>{
405393
ApplicationPackageFactory: () => mockApplicationPackageFactory,
406394
Artifacts: () => artifacts,
407395
Cache: () => mockCache,
408396
DeviceManager: () => mockDeviceManager,
409397
FileSystem: () => fs,
410398
ProcessManager: () => mockProcessManager,
411-
Usage: () => mockUsage,
399+
Usage: () => usage,
412400
});
413401
});
414402

packages/flutter_tools/test/src/common.dart

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,18 @@ CommandRunner<void> createTestCommandRunner([ FlutterCommand command ]) {
9292
return runner;
9393
}
9494

95+
/// Capture console print events into a string buffer.
96+
Future<StringBuffer> capturedConsolePrint(Future<void> Function() body) async {
97+
final StringBuffer buffer = StringBuffer();
98+
await runZoned<Future<void>>(() async {
99+
// Service the event loop.
100+
await body();
101+
}, zoneSpecification: ZoneSpecification(print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
102+
buffer.writeln(line);
103+
}));
104+
return buffer;
105+
}
106+
95107
/// Matcher for functions that throw [AssertionError].
96108
final Matcher throwsAssertionError = throwsA(isA<AssertionError>());
97109

0 commit comments

Comments
 (0)