Unverified Commit 8436c6ab authored by Jonah Williams's avatar Jonah Williams Committed by GitHub

remove testUsingContext (#70482)

parent f98c4683
...@@ -229,7 +229,10 @@ Future<T> runInContext<T>( ...@@ -229,7 +229,10 @@ Future<T> runInContext<T>(
featureFlags: featureFlags, featureFlags: featureFlags,
platform: globals.platform, platform: globals.platform,
), ),
MDnsObservatoryDiscovery: () => MDnsObservatoryDiscovery(), MDnsObservatoryDiscovery: () => MDnsObservatoryDiscovery(
logger: globals.logger,
flutterUsage: globals.flutterUsage,
),
OperatingSystemUtils: () => OperatingSystemUtils( OperatingSystemUtils: () => OperatingSystemUtils(
fileSystem: globals.fs, fileSystem: globals.fs,
logger: globals.logger, logger: globals.logger,
......
...@@ -8,24 +8,30 @@ import 'package:multicast_dns/multicast_dns.dart'; ...@@ -8,24 +8,30 @@ import 'package:multicast_dns/multicast_dns.dart';
import 'base/common.dart'; import 'base/common.dart';
import 'base/context.dart'; import 'base/context.dart';
import 'base/io.dart'; import 'base/io.dart';
import 'base/logger.dart';
import 'build_info.dart'; import 'build_info.dart';
import 'device.dart'; import 'device.dart';
import 'globals.dart' as globals;
import 'reporting/reporting.dart'; import 'reporting/reporting.dart';
/// A wrapper around [MDnsClient] to find a Dart observatory instance. /// A wrapper around [MDnsClient] to find a Dart observatory instance.
class MDnsObservatoryDiscovery { class MDnsObservatoryDiscovery {
/// Creates a new [MDnsObservatoryDiscovery] object. /// Creates a new [MDnsObservatoryDiscovery] object.
/// ///
/// The [client] parameter will be defaulted to a new [MDnsClient] if null. /// The [_client] parameter will be defaulted to a new [MDnsClient] if null.
/// The [applicationId] parameter may be null, and can be used to /// The [applicationId] parameter may be null, and can be used to
/// automatically select which application to use if multiple are advertising /// automatically select which application to use if multiple are advertising
/// Dart observatory ports. /// Dart observatory ports.
MDnsObservatoryDiscovery({MDnsClient mdnsClient}) MDnsObservatoryDiscovery({
: client = mdnsClient ?? MDnsClient(); MDnsClient mdnsClient,
@required Logger logger,
@required Usage flutterUsage,
}): _client = mdnsClient ?? MDnsClient(),
_logger = logger,
_flutterUsage = flutterUsage;
/// The [MDnsClient] used to do a lookup. final MDnsClient _client;
final MDnsClient client; final Logger _logger;
final Usage _flutterUsage;
@visibleForTesting @visibleForTesting
static const String dartObservatoryName = '_dartobservatory._tcp.local'; static const String dartObservatoryName = '_dartobservatory._tcp.local';
...@@ -53,16 +59,16 @@ class MDnsObservatoryDiscovery { ...@@ -53,16 +59,16 @@ class MDnsObservatoryDiscovery {
// TODO(jonahwilliams): use `deviceVmservicePort` to filter mdns results. // TODO(jonahwilliams): use `deviceVmservicePort` to filter mdns results.
@visibleForTesting @visibleForTesting
Future<MDnsObservatoryDiscoveryResult> query({String applicationId, int deviceVmservicePort}) async { Future<MDnsObservatoryDiscoveryResult> query({String applicationId, int deviceVmservicePort}) async {
globals.printTrace('Checking for advertised Dart observatories...'); _logger.printTrace('Checking for advertised Dart observatories...');
try { try {
await client.start(); await _client.start();
final List<PtrResourceRecord> pointerRecords = await client final List<PtrResourceRecord> pointerRecords = await _client
.lookup<PtrResourceRecord>( .lookup<PtrResourceRecord>(
ResourceRecordQuery.serverPointer(dartObservatoryName), ResourceRecordQuery.serverPointer(dartObservatoryName),
) )
.toList(); .toList();
if (pointerRecords.isEmpty) { if (pointerRecords.isEmpty) {
globals.printTrace('No pointer records found.'); _logger.printTrace('No pointer records found.');
return null; return null;
} }
// We have no guarantee that we won't get multiple hits from the same // We have no guarantee that we won't get multiple hits from the same
...@@ -94,9 +100,9 @@ class MDnsObservatoryDiscovery { ...@@ -94,9 +100,9 @@ class MDnsObservatoryDiscovery {
} else { } else {
domainName = pointerRecords[0].domainName; domainName = pointerRecords[0].domainName;
} }
globals.printTrace('Checking for available port on $domainName'); _logger.printTrace('Checking for available port on $domainName');
// Here, if we get more than one, it should just be a duplicate. // Here, if we get more than one, it should just be a duplicate.
final List<SrvResourceRecord> srv = await client final List<SrvResourceRecord> srv = await _client
.lookup<SrvResourceRecord>( .lookup<SrvResourceRecord>(
ResourceRecordQuery.service(domainName), ResourceRecordQuery.service(domainName),
) )
...@@ -105,11 +111,11 @@ class MDnsObservatoryDiscovery { ...@@ -105,11 +111,11 @@ class MDnsObservatoryDiscovery {
return null; return null;
} }
if (srv.length > 1) { if (srv.length > 1) {
globals.printError('Unexpectedly found more than one observatory report for $domainName ' _logger.printError('Unexpectedly found more than one observatory report for $domainName '
'- using first one (${srv.first.port}).'); '- using first one (${srv.first.port}).');
} }
globals.printTrace('Checking for authentication code for $domainName'); _logger.printTrace('Checking for authentication code for $domainName');
final List<TxtResourceRecord> txt = await client final List<TxtResourceRecord> txt = await _client
.lookup<TxtResourceRecord>( .lookup<TxtResourceRecord>(
ResourceRecordQuery.text(domainName), ResourceRecordQuery.text(domainName),
) )
...@@ -133,7 +139,7 @@ class MDnsObservatoryDiscovery { ...@@ -133,7 +139,7 @@ class MDnsObservatoryDiscovery {
} }
return MDnsObservatoryDiscoveryResult(srv.first.port, authCode); return MDnsObservatoryDiscoveryResult(srv.first.port, authCode);
} finally { } finally {
client.stop(); _client.stop();
} }
} }
...@@ -166,14 +172,14 @@ class MDnsObservatoryDiscovery { ...@@ -166,14 +172,14 @@ class MDnsObservatoryDiscovery {
// If there's not an ipv4 link local address in `NetworkInterfaces.list`, // If there's not an ipv4 link local address in `NetworkInterfaces.list`,
// then request user interventions with a `printError()` if possible. // then request user interventions with a `printError()` if possible.
Future<void> _checkForIPv4LinkLocal(Device device) async { Future<void> _checkForIPv4LinkLocal(Device device) async {
globals.printTrace( _logger.printTrace(
'mDNS query failed. Checking for an interface with a ipv4 link local address.' 'mDNS query failed. Checking for an interface with a ipv4 link local address.'
); );
final List<NetworkInterface> interfaces = await listNetworkInterfaces( final List<NetworkInterface> interfaces = await listNetworkInterfaces(
includeLinkLocal: true, includeLinkLocal: true,
type: InternetAddressType.IPv4, type: InternetAddressType.IPv4,
); );
if (globals.logger.isVerbose) { if (_logger.isVerbose) {
_logInterfaces(interfaces); _logInterfaces(interfaces);
} }
final bool hasIPv4LinkLocal = interfaces.any( final bool hasIPv4LinkLocal = interfaces.any(
...@@ -182,14 +188,14 @@ class MDnsObservatoryDiscovery { ...@@ -182,14 +188,14 @@ class MDnsObservatoryDiscovery {
), ),
); );
if (hasIPv4LinkLocal) { if (hasIPv4LinkLocal) {
globals.printTrace('An interface with an ipv4 link local address was found.'); _logger.printTrace('An interface with an ipv4 link local address was found.');
return; return;
} }
final TargetPlatform targetPlatform = await device.targetPlatform; final TargetPlatform targetPlatform = await device.targetPlatform;
switch (targetPlatform) { switch (targetPlatform) {
case TargetPlatform.ios: case TargetPlatform.ios:
UsageEvent('ios-mdns', 'no-ipv4-link-local', flutterUsage: globals.flutterUsage).send(); UsageEvent('ios-mdns', 'no-ipv4-link-local', flutterUsage: _flutterUsage).send();
globals.printError( _logger.printError(
'The mDNS query for an attached iOS device failed. It may ' 'The mDNS query for an attached iOS device failed. It may '
'be necessary to disable the "Personal Hotspot" on the device, and ' 'be necessary to disable the "Personal Hotspot" on the device, and '
'to ensure that the "Disable unless needed" setting is unchecked ' 'to ensure that the "Disable unless needed" setting is unchecked '
...@@ -198,18 +204,18 @@ class MDnsObservatoryDiscovery { ...@@ -198,18 +204,18 @@ class MDnsObservatoryDiscovery {
); );
break; break;
default: default:
globals.printTrace('No interface with an ipv4 link local address was found.'); _logger.printTrace('No interface with an ipv4 link local address was found.');
break; break;
} }
} }
void _logInterfaces(List<NetworkInterface> interfaces) { void _logInterfaces(List<NetworkInterface> interfaces) {
for (final NetworkInterface interface in interfaces) { for (final NetworkInterface interface in interfaces) {
if (globals.logger.isVerbose) { if (_logger.isVerbose) {
globals.printTrace('Found interface "${interface.name}":'); _logger.printTrace('Found interface "${interface.name}":');
for (final InternetAddress address in interface.addresses) { for (final InternetAddress address in interface.addresses) {
final String linkLocal = address.isLinkLocal ? 'link local' : ''; final String linkLocal = address.isLinkLocal ? 'link local' : '';
globals.printTrace('\tBound address: "${address.address}" $linkLocal'); _logger.printTrace('\tBound address: "${address.address}" $linkLocal');
} }
} }
} }
......
...@@ -3,13 +3,14 @@ ...@@ -3,13 +3,14 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/mdns_discovery.dart'; import 'package:flutter_tools/src/mdns_discovery.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:mockito/mockito.dart'; import 'package:mockito/mockito.dart';
import 'package:multicast_dns/multicast_dns.dart'; import 'package:multicast_dns/multicast_dns.dart';
import '../src/common.dart'; import '../src/common.dart';
import '../src/context.dart';
import '../src/mocks.dart'; import '../src/mocks.dart';
void main() { void main() {
...@@ -55,27 +56,35 @@ void main() { ...@@ -55,27 +56,35 @@ void main() {
return client; return client;
} }
testUsingContext('No ports available', () async { testWithoutContext('No ports available', () async {
final MDnsClient client = getMockClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}); final MDnsClient client = getMockClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{});
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
);
final int port = (await portDiscovery.query())?.port; final int port = (await portDiscovery.query())?.port;
expect(port, isNull); expect(port, isNull);
}); });
testUsingContext('Prints helpful message when there is no ipv4 link local address.', () async { testWithoutContext('Prints helpful message when there is no ipv4 link local address.', () async {
final MDnsClient client = getMockClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}); final MDnsClient client = getMockClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{});
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final BufferLogger logger = BufferLogger.test();
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: logger,
flutterUsage: Usage.test(),
);
final Uri uri = await portDiscovery.getObservatoryUri( final Uri uri = await portDiscovery.getObservatoryUri(
'', '',
MockIOSDevice(), MockIOSDevice(),
); );
expect(uri, isNull); expect(uri, isNull);
expect(testLogger.errorText, contains('Personal Hotspot')); expect(logger.errorText, contains('Personal Hotspot'));
}); });
testUsingContext('One port available, no appId', () async { testWithoutContext('One port available, no appId', () async {
final MDnsClient client = getMockClient( final MDnsClient client = getMockClient(
<PtrResourceRecord>[ <PtrResourceRecord>[
PtrResourceRecord('foo', year3000, domainName: 'bar'), PtrResourceRecord('foo', year3000, domainName: 'bar'),
...@@ -87,12 +96,16 @@ void main() { ...@@ -87,12 +96,16 @@ void main() {
}, },
); );
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
);
final int port = (await portDiscovery.query())?.port; final int port = (await portDiscovery.query())?.port;
expect(port, 123); expect(port, 123);
}); });
testUsingContext('One port available, no appId, with authCode', () async { testWithoutContext('One port available, no appId, with authCode', () async {
final MDnsClient client = getMockClient( final MDnsClient client = getMockClient(
<PtrResourceRecord>[ <PtrResourceRecord>[
PtrResourceRecord('foo', year3000, domainName: 'bar'), PtrResourceRecord('foo', year3000, domainName: 'bar'),
...@@ -111,13 +124,15 @@ void main() { ...@@ -111,13 +124,15 @@ void main() {
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery( final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client, mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
); );
final MDnsObservatoryDiscoveryResult result = await portDiscovery.query(); final MDnsObservatoryDiscoveryResult result = await portDiscovery.query();
expect(result?.port, 123); expect(result?.port, 123);
expect(result?.authCode, 'xyz/'); expect(result?.authCode, 'xyz/');
}); });
testUsingContext('Multiple ports available, without appId', () async { testWithoutContext('Multiple ports available, without appId', () async {
final MDnsClient client = getMockClient( final MDnsClient client = getMockClient(
<PtrResourceRecord>[ <PtrResourceRecord>[
PtrResourceRecord('foo', year3000, domainName: 'bar'), PtrResourceRecord('foo', year3000, domainName: 'bar'),
...@@ -133,11 +148,15 @@ void main() { ...@@ -133,11 +148,15 @@ void main() {
}, },
); );
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
);
expect(portDiscovery.query, throwsToolExit()); expect(portDiscovery.query, throwsToolExit());
}); });
testUsingContext('Multiple ports available, with appId', () async { testWithoutContext('Multiple ports available, with appId', () async {
final MDnsClient client = getMockClient( final MDnsClient client = getMockClient(
<PtrResourceRecord>[ <PtrResourceRecord>[
PtrResourceRecord('foo', year3000, domainName: 'bar'), PtrResourceRecord('foo', year3000, domainName: 'bar'),
...@@ -153,12 +172,16 @@ void main() { ...@@ -153,12 +172,16 @@ void main() {
}, },
); );
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
);
final int port = (await portDiscovery.query(applicationId: 'fiz'))?.port; final int port = (await portDiscovery.query(applicationId: 'fiz'))?.port;
expect(port, 321); expect(port, 321);
}); });
testUsingContext('Multiple ports available per process, with appId', () async { testWithoutContext('Multiple ports available per process, with appId', () async {
final MDnsClient client = getMockClient( final MDnsClient client = getMockClient(
<PtrResourceRecord>[ <PtrResourceRecord>[
PtrResourceRecord('foo', year3000, domainName: 'bar'), PtrResourceRecord('foo', year3000, domainName: 'bar'),
...@@ -176,23 +199,31 @@ void main() { ...@@ -176,23 +199,31 @@ void main() {
}, },
); );
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
);
final int port = (await portDiscovery.query(applicationId: 'bar'))?.port; final int port = (await portDiscovery.query(applicationId: 'bar'))?.port;
expect(port, 1234); expect(port, 1234);
}); });
testUsingContext('Query returns null', () async { testWithoutContext('Query returns null', () async {
final MDnsClient client = getMockClient( final MDnsClient client = getMockClient(
<PtrResourceRecord>[], <PtrResourceRecord>[],
<String, List<SrvResourceRecord>>{}, <String, List<SrvResourceRecord>>{},
); );
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
);
final int port = (await portDiscovery.query(applicationId: 'bar'))?.port; final int port = (await portDiscovery.query(applicationId: 'bar'))?.port;
expect(port, isNull); expect(port, isNull);
}); });
testUsingContext('Throws Exception when client throws OSError on start', () async { testWithoutContext('Throws Exception when client throws OSError on start', () async {
final MDnsClient client = MockMDnsClient(); final MDnsClient client = MockMDnsClient();
when(client.start()).thenAnswer((_) { when(client.start()).thenAnswer((_) {
throw const OSError('Operation not suppoted on socket', 102); throw const OSError('Operation not suppoted on socket', 102);
...@@ -200,6 +231,8 @@ void main() { ...@@ -200,6 +231,8 @@ void main() {
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery( final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client, mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
); );
expect( expect(
() async => await portDiscovery.query(), () async => await portDiscovery.query(),
...@@ -207,7 +240,7 @@ void main() { ...@@ -207,7 +240,7 @@ void main() {
); );
}); });
testUsingContext('Correctly builds Observatory URI with hostVmservicePort == 0', () async { testWithoutContext('Correctly builds Observatory URI with hostVmservicePort == 0', () async {
final MDnsClient client = getMockClient( final MDnsClient client = getMockClient(
<PtrResourceRecord>[ <PtrResourceRecord>[
PtrResourceRecord('foo', year3000, domainName: 'bar'), PtrResourceRecord('foo', year3000, domainName: 'bar'),
...@@ -221,7 +254,11 @@ void main() { ...@@ -221,7 +254,11 @@ void main() {
final MockIOSDevice mockDevice = MockIOSDevice(); final MockIOSDevice mockDevice = MockIOSDevice();
when(mockDevice.portForwarder).thenReturn(const NoOpDevicePortForwarder()); when(mockDevice.portForwarder).thenReturn(const NoOpDevicePortForwarder());
final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(mdnsClient: client); final MDnsObservatoryDiscovery portDiscovery = MDnsObservatoryDiscovery(
mdnsClient: client,
logger: BufferLogger.test(),
flutterUsage: Usage.test(),
);
final Uri uri = await portDiscovery.getObservatoryUri('bar', mockDevice, hostVmservicePort: 0); final Uri uri = await portDiscovery.getObservatoryUri('bar', mockDevice, hostVmservicePort: 0);
expect(uri.toString(), 'http://127.0.0.1:123/'); expect(uri.toString(), 'http://127.0.0.1:123/');
}); });
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment