Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch topackage:dart_flutter_team_lints #763

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
include: package:lints/recommended.yaml
include: package:dart_flutter_team_lints/analysis_options.yaml

analyzer:
exclude:
- test/**.mocks.dart
errors:
lines_longer_than_80_chars: ignore
language:
strict-casts: true

Expand Down
4 changes: 3 additions & 1 deletion example/build_extensions/example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

// ignore_for_file: unreachable_from_main

import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:test_api/scaffolding.dart';
Expand All @@ -30,7 +32,7 @@ class Dog {
@GenerateNiceMocks([MockSpec<Dog>()])
void main() {
test('Verify some dog behaviour', () async {
MockDog mockDog = MockDog();
var mockDog = MockDog();
when(mockDog.eatFood(any));

mockDog.eatFood('biscuits');
Expand Down
4 changes: 3 additions & 1 deletion example/example.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// ignore_for_file: unreachable_from_main

import 'dart:async';

import 'package:mockito/annotations.dart';
Expand Down Expand Up @@ -229,7 +231,7 @@ void main() {
final cat = FakeCat();

cat.eatFood('Milk'); // Prints 'Fake eat Milk'.
expect(() => cat.sleep(), throwsUnimplementedError);
expect(cat.sleep, throwsUnimplementedError);
});

test('Relaxed mock class', () {
Expand Down
7 changes: 4 additions & 3 deletions example/iss/iss.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ class IssLocator {
// at this moment.
final uri = Uri.parse('http://api.open-notify.org/iss-now.json');
final rs = await client.get(uri);
final data = jsonDecode(rs.body);
final latitude = double.parse(data['iss_position']['latitude'] as String);
final longitude = double.parse(data['iss_position']['longitude'] as String);
final data = jsonDecode(rs.body) as Map;
final position = data['iss_position'] as Map;
final latitude = double.parse(position['latitude'] as String);
final longitude = double.parse(position['longitude'] as String);
_position = Point<double>(latitude, longitude);
}
}
Expand Down
16 changes: 8 additions & 8 deletions example/iss/iss_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@ void main() {
// verify the calculated distance between them.
group('Spherical distance', () {
test('London - Paris', () {
final london = Point(51.5073, -0.1277);
final paris = Point(48.8566, 2.3522);
final london = const Point(51.5073, -0.1277);
final paris = const Point(48.8566, 2.3522);
final d = sphericalDistanceKm(london, paris);
// London should be approximately 343.5km
// (+/- 0.1km) from Paris.
expect(d, closeTo(343.5, 0.1));
});

test('San Francisco - Mountain View', () {
final sf = Point(37.783333, -122.416667);
final mtv = Point(37.389444, -122.081944);
final sf = const Point(37.783333, -122.416667);
final mtv = const Point(37.389444, -122.081944);
final d = sphericalDistanceKm(sf, mtv);
// San Francisco should be approximately 52.8km
// (+/- 0.1km) from Mountain View.
Expand All @@ -52,8 +52,8 @@ void main() {
// second predefined location. This test runs asynchronously.
group('ISS spotter', () {
test('ISS visible', () async {
final sf = Point(37.783333, -122.416667);
final mtv = Point(37.389444, -122.081944);
final sf = const Point(37.783333, -122.416667);
final mtv = const Point(37.389444, -122.081944);
final IssLocator locator = MockIssLocator();
// Mountain View should be visible from San Francisco.
when(locator.currentPosition).thenReturn(sf);
Expand All @@ -63,8 +63,8 @@ void main() {
});

test('ISS not visible', () async {
final london = Point(51.5073, -0.1277);
final mtv = Point(37.389444, -122.081944);
final london = const Point(51.5073, -0.1277);
final mtv = const Point(37.389444, -122.081944);
final IssLocator locator = MockIssLocator();
// London should not be visible from Mountain View.
when(locator.currentPosition).thenReturn(london);
Expand Down
53 changes: 27 additions & 26 deletions lib/src/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ import 'package:build/build.dart';
import 'package:code_builder/code_builder.dart' hide refer;
import 'package:collection/collection.dart';
import 'package:dart_style/dart_style.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/src/version.dart';
import 'package:path/path.dart' as p;
import 'package:source_gen/source_gen.dart';

import '../annotations.dart';
import 'version.dart';

/// For a source Dart library, generate the mocks referenced therein.
///
/// Given an input library, 'foo.dart', this builder will search the top-level
Expand Down Expand Up @@ -106,31 +107,33 @@ class MockBuilder implements Builder {
// These comments are added after import directives; leading newlines
// are necessary. Individual rules are still ignored to preserve backwards
// compatibility with older versions of Dart.
b.body.add(Code('\n\n// ignore_for_file: type=lint\n'));
b.body.add(Code('// ignore_for_file: avoid_redundant_argument_values\n'));
b.body.add(const Code('\n\n// ignore_for_file: type=lint\n'));
b.body.add(
const Code('// ignore_for_file: avoid_redundant_argument_values\n'));
// We might generate a setter without a corresponding getter.
b.body.add(Code('// ignore_for_file: avoid_setters_without_getters\n'));
b.body.add(
const Code('// ignore_for_file: avoid_setters_without_getters\n'));
// We don't properly prefix imported class names in doc comments.
b.body.add(Code('// ignore_for_file: comment_references\n'));
b.body.add(const Code('// ignore_for_file: comment_references\n'));
// We might import a deprecated library, or implement a deprecated class.
b.body.add(Code('// ignore_for_file: deprecated_member_use\n'));
b.body.add(Code(
b.body.add(const Code('// ignore_for_file: deprecated_member_use\n'));
b.body.add(const Code(
'// ignore_for_file: deprecated_member_use_from_same_package\n'));
// We might import a package's 'src' directory.
b.body.add(Code('// ignore_for_file: implementation_imports\n'));
b.body.add(const Code('// ignore_for_file: implementation_imports\n'));
// `Mock.noSuchMethod` is `@visibleForTesting`, but the generated code is
// not always in a test directory; the Mockito `example/iss` tests, for
// example.
b.body.add(Code(
b.body.add(const Code(
'// ignore_for_file: invalid_use_of_visible_for_testing_member\n'));
b.body.add(Code('// ignore_for_file: must_be_immutable\n'));
b.body.add(Code('// ignore_for_file: prefer_const_constructors\n'));
b.body.add(const Code('// ignore_for_file: must_be_immutable\n'));
b.body.add(const Code('// ignore_for_file: prefer_const_constructors\n'));
// The code_builder `asA` API unconditionally adds defensive parentheses.
b.body.add(Code('// ignore_for_file: unnecessary_parenthesis\n'));
b.body.add(const Code('// ignore_for_file: unnecessary_parenthesis\n'));
// The generator appends a suffix to fake classes
b.body.add(Code('// ignore_for_file: camel_case_types\n'));
b.body.add(const Code('// ignore_for_file: camel_case_types\n'));
// The generator has to occasionally implement sealed classes
b.body.add(Code('// ignore_for_file: subtype_of_sealed_class\n\n'));
b.body.add(const Code('// ignore_for_file: subtype_of_sealed_class\n\n'));
b.body.addAll(mockLibraryInfo.fakeClasses);
b.body.addAll(mockLibraryInfo.mockClasses);
});
Expand Down Expand Up @@ -329,8 +332,8 @@ class _TypeVisitor extends RecursiveElementVisitor<void> {
if (!alreadyVisitedElement) {
type.element.typeParameters.forEach(visitTypeParameterElement);

final toStringMethod =
type.element.lookUpMethod('toString', type.element.library);
final toStringMethod = type.element.augmented
.lookUpMethod(name: 'toString', library: type.element.library);
if (toStringMethod != null && toStringMethod.parameters.isNotEmpty) {
// In a Fake class which implements a class which overrides `toString`
// with additional (optional) parameters, we must also override
Expand Down Expand Up @@ -594,9 +597,7 @@ class _MockTargetGatherer {
var type = _determineDartType(typeToMock, entryLib.typeProvider);
final mockTypeArguments = mockType?.typeArguments;
if (mockTypeArguments != null) {
final typeName =
type.alias?.element.getDisplayString(withNullability: false) ??
'type $type';
final typeName = type.alias?.element.getDisplayString() ?? 'type $type';
final typeArguments = type.alias?.typeArguments ?? type.typeArguments;
// Check explicit type arguments for unknown types that were
// turned into `dynamic` by the analyzer.
Expand Down Expand Up @@ -1593,7 +1594,7 @@ class _MockClassInfo {
}
}
if (type.returnType is analyzer.VoidType) {
b.body = Code('');
b.body = const Code('');
} else {
b.body = _dummyValue(type.returnType, invocation).code;
}
Expand Down Expand Up @@ -1688,8 +1689,8 @@ class _MockClassInfo {
..initializers.add(refer('super')
.call([refer('parent'), refer('parentInvocation')]).code)));

final toStringMethod =
elementToFake.lookUpMethod('toString', elementToFake.library);
final toStringMethod = elementToFake.augmented
.lookUpMethod(name: 'toString', library: elementToFake.library);
if (toStringMethod != null && toStringMethod.parameters.isNotEmpty) {
// If [elementToFake] includes an overriding `toString` implementation,
// we need to include an implementation which matches the signature.
Expand Down Expand Up @@ -1849,7 +1850,7 @@ class _MockClassInfo {
// TODO(srawlins): It seems like this might be revivable, but Angular
// does not revive Types; we should investigate this if users request it.
final type = object.toTypeValue()!;
final typeStr = type.getDisplayString(withNullability: false);
final typeStr = type.getDisplayString();
throw _ReviveException('default value is a Type: $typeStr.');
} else {
// If [constant] is not null, a literal, or a type, then it must be an
Expand Down Expand Up @@ -2177,7 +2178,7 @@ class _MockClassInfo {
..isNullable = forceNullable || typeSystem.isNullable(type));
} else {
return referImported(
type.getDisplayString(withNullability: false),
type.getDisplayString(),
_typeImport(type.element),
);
}
Expand Down Expand Up @@ -2286,7 +2287,7 @@ class _AvoidConflictsAllocator implements Allocator {
/// A [MockBuilder] instance for use by `build.yaml`.
Builder buildMocks(BuilderOptions options) {
final buildExtensions = options.config['build_extensions'];
if (buildExtensions == null) return MockBuilder();
if (buildExtensions == null) return const MockBuilder();
if (buildExtensions is! Map) {
throw ArgumentError(
'build_extensions should be a map from inputs to outputs');
Expand Down
3 changes: 2 additions & 1 deletion lib/src/dummies.dart
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ List<Object?> _defaultDummies = [
<Never>[],
<Never>{},
<Never, Never>{},
Stream<Never>.empty(),
const Stream<Never>.empty(),
SplayTreeSet<Never>(),
SplayTreeMap<Never, Never>(),
];
Expand All @@ -155,6 +155,7 @@ T? dummyValueOrNull<T>(Object parent, Invocation invocation) {
T dummyValue<T>(Object parent, Invocation invocation) {
final value = dummyValueOrNull<T>(parent, invocation);
if (value is T) return value;
// ignore: only_throw_errors
throw MissingDummyValueError(T);
}

Expand Down
8 changes: 4 additions & 4 deletions lib/src/invocation_matcher.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import 'package:collection/collection.dart';
import 'package:matcher/matcher.dart';
import 'package:mockito/src/mock.dart';
import 'mock.dart';

/// Returns a matcher that expects an invocation that matches arguments given.
///
Expand Down Expand Up @@ -130,7 +130,7 @@ class _InvocationMatcher implements Matcher {
// Specifically, if a Matcher is passed as an argument, we'd like to get an
// error like "Expected fly(miles: > 10), Actual: fly(miles: 5)".
@override
Description describeMismatch(item, Description d, _, __) {
Description describeMismatch(dynamic item, Description d, _, __) {
if (item is Invocation) {
d = d.add('Does not match ');
return _describeInvocation(d, item);
Expand All @@ -139,7 +139,7 @@ class _InvocationMatcher implements Matcher {
}

@override
bool matches(item, _) =>
bool matches(dynamic item, _) =>
item is Invocation &&
_invocation.memberName == item.memberName &&
_invocation.isSetter == item.isSetter &&
Expand All @@ -156,7 +156,7 @@ class _MatcherEquality extends DeepCollectionEquality /* <Matcher | E> */ {
const _MatcherEquality();

@override
bool equals(e1, e2) {
bool equals(Object? e1, Object? e2) {
// All argument matches are wrapped in `ArgMatcher`, so we have to unwrap
// them into the raw `Matcher` type in order to finish our equality checks.
if (e1 is ArgMatcher) {
Expand Down
27 changes: 14 additions & 13 deletions lib/src/mock.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ import 'dart:collection';

import 'package:matcher/expect.dart';
import 'package:meta/meta.dart';
import 'package:mockito/src/call_pair.dart';
import 'package:mockito/src/dummies.dart' show resetDummyBuilders;
import 'package:mockito/src/invocation_matcher.dart';
// ignore: deprecated_member_use
import 'package:test_api/fake.dart';

import 'call_pair.dart';
import 'dummies.dart' show resetDummyBuilders;
import 'invocation_matcher.dart';

/// Whether a [when] call is "in progress."
///
/// Since [when] is a getter, this is `true` immediately after [when] returns,
Expand Down Expand Up @@ -195,7 +196,7 @@ mixin class Mock {
int get hashCode => _givenHashCode ?? 0;

@override
bool operator ==(other) => (_givenHashCode != null && other is Mock)
bool operator ==(Object other) => (_givenHashCode != null && other is Mock)
? _givenHashCode == other._givenHashCode
: identical(this, other);

Expand Down Expand Up @@ -392,8 +393,7 @@ class _InvocationForMatchedArguments extends Invocation {
// by a stored value in [_storedNamedArgs].
static Map<Symbol, dynamic> _reconstituteNamedArgs(Invocation invocation) {
final namedArguments = <Symbol, dynamic>{};
final storedNamedArgSymbols =
_storedNamedArgs.keys.map((name) => Symbol(name));
final storedNamedArgSymbols = _storedNamedArgs.keys.map(Symbol.new);

// Iterate through [invocation]'s named args, validate them, and add them
// to the return map.
Expand Down Expand Up @@ -509,13 +509,13 @@ T named<T extends Mock>(T mock, {String? name, int? hashCode}) => mock
.._givenHashCode = hashCode;

/// Clear stubs of, and collected interactions with [mock].
void reset(var mock) {
void reset(Mock mock) {
mock._realCalls.clear();
mock._responses.clear();
}

/// Clear the collected interactions with [mock].
void clearInteractions(var mock) {
void clearInteractions(Mock mock) {
mock._realCalls.clear();
}

Expand Down Expand Up @@ -557,6 +557,7 @@ class PostExpectation<T> {
/// Store an exception to throw when this method stub is called.
void thenThrow(Object throwable) {
return _completeWhen((Invocation _) {
// ignore: only_throw_errors
throw throwable;
});
}
Expand Down Expand Up @@ -668,7 +669,7 @@ class InvocationMatcher {
return true;
}

bool isMatchingArg(roleArg, actArg) {
bool isMatchingArg(dynamic roleArg, dynamic actArg) {
if (roleArg is ArgMatcher) {
return roleArg.matcher.matches(actArg, {});
} else {
Expand Down Expand Up @@ -967,7 +968,6 @@ class VerificationResult {
@Deprecated(
'captured should be considered final - assigning this field may be '
'removed as early as Mockito 5.0.0')
// ignore: unnecessary_getters_setters
set captured(List<dynamic> captured) => _captured = captured;

/// The number of calls matched in this verification.
Expand Down Expand Up @@ -1133,6 +1133,7 @@ List<VerificationResult> Function<T>(List<T> recordedInvocations)
matchedCalls.add(matched.realCall);
verificationResults.add(VerificationResult._(1, matched.capturedArgs));
time = matched.realCall.timeStamp;
// ignore: avoid_catching_errors
} on StateError {
final mocks = tmpVerifyCalls.map((vc) => vc.mock).toSet();
final allInvocations =
Expand All @@ -1154,14 +1155,14 @@ List<VerificationResult> Function<T>(List<T> recordedInvocations)
};
}

void _throwMockArgumentError(String method, var nonMockInstance) {
void _throwMockArgumentError(String method, dynamic nonMockInstance) {
if (nonMockInstance == null) {
throw ArgumentError('$method was called with a null argument');
}
throw ArgumentError('$method must only be given a Mock object');
}

void verifyNoMoreInteractions(var mock) {
void verifyNoMoreInteractions(dynamic mock) {
if (mock is Mock) {
final unverified = mock._realCalls.where((inv) => !inv.verified).toList();
if (unverified.isNotEmpty) {
Expand All @@ -1172,7 +1173,7 @@ void verifyNoMoreInteractions(var mock) {
}
}

void verifyZeroInteractions(var mock) {
void verifyZeroInteractions(dynamic mock) {
if (mock is Mock) {
if (mock._realCalls.isNotEmpty) {
fail('No interaction expected, but following found: '
Expand Down
Loading
Loading