-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathbuilder.dart
2438 lines (2247 loc) · 93.9 KB
/
builder.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 Dart Mockito authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart' as ast;
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart' as analyzer;
import 'package:analyzer/dart/element/type_provider.dart';
import 'package:analyzer/dart/element/type_system.dart';
import 'package:analyzer/dart/element/visitor.dart';
// ignore: implementation_imports
import 'package:analyzer/src/dart/element/element.dart'
show ElementAnnotationImpl;
// ignore: implementation_imports
import 'package:analyzer/src/dart/element/inheritance_manager3.dart'
show InheritanceManager3, Name;
// ignore: implementation_imports
import 'package:analyzer/src/dart/element/member.dart' show ExecutableMember;
// ignore: implementation_imports
import 'package:analyzer/src/dart/element/type_algebra.dart' show Substitution;
import 'package:build/build.dart';
// Do not expose [refer] in the default namespace.
//
// [refer] allows a reference to include or not include a URL. Omitting the URL
// of an element, like a class, has resulted in many bugs. [_MockLibraryInfo]
// provides a [refer] function and a [referBasic] function. The former requires
// a URL to be passed.
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';
/// For a source Dart library, generate the mocks referenced therein.
///
/// Given an input library, 'foo.dart', this builder will search the top-level
/// elements for an annotation, `@GenerateMocks`, from the mockito package. For
/// example:
///
/// ```dart
/// @GenerateMocks([Foo])
/// void main() {}
/// ```
///
/// If this builder finds any classes to mock (for example, `Foo`, above), it
/// will produce a "'.mocks.dart' file with such mocks. In this example,
/// 'foo.mocks.dart' will be created.
class MockBuilder implements Builder {
@override
final Map<String, List<String>> buildExtensions;
const MockBuilder(
{this.buildExtensions = const {
'.dart': ['.mocks.dart']
}});
@override
Future<void> build(BuildStep buildStep) async {
if (!await buildStep.resolver.isLibrary(buildStep.inputId)) return;
final entryLib = await buildStep.inputLibrary;
final sourceLibIsNonNullable = entryLib.isNonNullableByDefault;
final mockLibraryAsset = buildStep.allowedOutputs.singleOrNull;
if (mockLibraryAsset == null) {
throw ArgumentError(
'Build_extensions has missing or conflicting outputs for '
'`${buildStep.inputId.path}`, this is usually caused by a misconfigured '
'build extension override in `build.yaml`');
}
final inheritanceManager = InheritanceManager3();
final mockTargetGatherer =
_MockTargetGatherer(entryLib, inheritanceManager);
final assetUris = await _resolveAssetUris(buildStep.resolver,
mockTargetGatherer._mockTargets, mockLibraryAsset.path, entryLib);
final mockLibraryInfo = _MockLibraryInfo(mockTargetGatherer._mockTargets,
assetUris: assetUris,
entryLib: entryLib,
inheritanceManager: inheritanceManager);
if (mockLibraryInfo.fakeClasses.isEmpty &&
mockLibraryInfo.mockClasses.isEmpty) {
// Nothing to mock here!
return;
}
final mockLibrary = Library((b) {
// 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'));
// We might generate a setter without a corresponding getter.
b.body.add(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'));
// 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(
'// 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'));
// `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(
'// ignore_for_file: invalid_use_of_visible_for_testing_member\n'));
b.body.add(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'));
// The generator appends a suffix to fake classes
b.body.add(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.addAll(mockLibraryInfo.fakeClasses);
b.body.addAll(mockLibraryInfo.mockClasses);
});
final emitter = DartEmitter(
allocator: _AvoidConflictsAllocator(
coreConflicts: mockLibraryInfo.coreConflicts),
orderDirectives: true,
useNullSafetySyntax: sourceLibIsNonNullable);
final rawOutput = mockLibrary.accept(emitter).toString();
// The source lib may be pre-null-safety because of an explicit opt-out
// (`// @dart=2.9`), as opposed to living in a pre-null-safety package. To
// allow for this situation, we must also add an opt-out comment here.
final dartVersionComment = sourceLibIsNonNullable ? '' : '// @dart=2.9';
final mockLibraryContent = DartFormatter().format('''
// Mocks generated by Mockito $packageVersion from annotations
// in ${entryLib.definingCompilationUnit.source.uri.path}.
// Do not manually edit this file.
$dartVersionComment
$rawOutput
''');
await buildStep.writeAsString(mockLibraryAsset, mockLibraryContent);
}
Future<Map<Element, String>> _resolveAssetUris(
Resolver resolver,
List<_MockTarget> mockTargets,
String entryAssetPath,
LibraryElement entryLib) async {
// We pass in the `Future<dynamic>` type so that an asset URI is known for
// `Future`, which is needed when overriding some methods which return
// `FutureOr`.
final typeVisitor = _TypeVisitor(entryLib.typeProvider.futureDynamicType);
final seenTypes = <analyzer.InterfaceType>{};
final librariesWithTypes = <LibraryElement>{};
void addTypesFrom(analyzer.InterfaceType type) {
// Prevent infinite recursion.
if (seenTypes.contains(type)) {
return;
}
seenTypes.add(type);
librariesWithTypes.add(type.element.library);
type.element.accept(typeVisitor);
if (type.alias != null) type.alias!.element.accept(typeVisitor);
// For a type like `Foo<Bar>`, add the `Bar`.
type.typeArguments
.whereType<analyzer.InterfaceType>()
.forEach(addTypesFrom);
// For a type like `Foo extends Bar<Baz>`, add the `Baz`.
for (final supertype in type.allSupertypes) {
addTypesFrom(supertype);
}
}
for (final mockTarget in mockTargets) {
addTypesFrom(mockTarget.classType);
for (final mixinTarget in mockTarget.mixins) {
addTypesFrom(mixinTarget);
}
}
final typeUris = <Element, String>{};
final elements = [
// Types which may be referenced.
...typeVisitor._elements,
// Fallback generator functions which may be referenced.
for (final mockTarget in mockTargets)
...mockTarget.fallbackGenerators.values,
];
for (final element in elements) {
final elementLibrary = element.library!;
if (elementLibrary.isInSdk && !elementLibrary.name.startsWith('dart._')) {
// For public SDK libraries, just use the source URI.
typeUris[element] = elementLibrary.source.uri.toString();
continue;
}
final exportingLibrary = _findExportOf(librariesWithTypes, element);
try {
final typeAssetId = await resolver.assetIdForElement(exportingLibrary);
if (typeAssetId.path.startsWith('lib/')) {
typeUris[element] = typeAssetId.uri.toString();
} else {
typeUris[element] = p.posix.relative(typeAssetId.path,
from: p.posix.dirname(entryAssetPath));
}
} on UnresolvableAssetException {
// Asset may be in a summary.
typeUris[element] = exportingLibrary.source.uri.toString();
}
}
return typeUris;
}
/// Returns a library which exports [element], selecting from the imports of
/// [inputLibraries] (and all exported libraries).
///
/// If [element] is not exported by any libraries in this set, then
/// [element]'s declaring library is returned.
static LibraryElement _findExportOf(
Iterable<LibraryElement> inputLibraries, Element element) {
final elementName = element.name;
if (elementName == null) {
return element.library!;
}
final libraries = Queue.of([
for (final library in inputLibraries) ...library.importedLibraries,
]);
for (final library in libraries) {
if (library.exportNamespace.get(elementName) == element) {
return library;
}
}
return element.library!;
}
}
/// An [Element] visitor which collects the elements of all of the
/// [analyzer.InterfaceType]s which it encounters.
class _TypeVisitor extends RecursiveElementVisitor<void> {
final _elements = <Element>{};
final analyzer.DartType _futureType;
_TypeVisitor(this._futureType);
@override
void visitClassElement(ClassElement element) {
_elements.add(element);
super.visitClassElement(element);
}
@override
void visitEnumElement(EnumElement element) {
_elements.add(element);
super.visitEnumElement(element);
}
@override
void visitFieldElement(FieldElement element) {
_addType(element.type);
super.visitFieldElement(element);
}
@override
void visitMethodElement(MethodElement element) {
_addType(element.returnType);
super.visitMethodElement(element);
}
@override
void visitMixinElement(MixinElement element) {
_elements.add(element);
super.visitMixinElement(element);
}
@override
void visitParameterElement(ParameterElement element) {
_addType(element.type);
if (element.hasDefaultValue) {
_addTypesFromConstant(element.computeConstantValue()!);
}
super.visitParameterElement(element);
}
@override
void visitTypeParameterElement(TypeParameterElement element) {
_addType(element.bound);
super.visitTypeParameterElement(element);
}
@override
void visitTypeAliasElement(TypeAliasElement element) {
_elements.add(element);
super.visitTypeAliasElement(element);
}
/// Adds [type] to the collected [_elements].
void _addType(analyzer.DartType? type) {
if (type == null) return;
type.alias?.typeArguments.forEach(_addType);
if (type is analyzer.InterfaceType) {
final alreadyVisitedElement = _elements.contains(type.element);
_elements.add(type.element);
type.typeArguments.forEach(_addType);
if (!alreadyVisitedElement) {
type.element.typeParameters.forEach(visitTypeParameterElement);
final toStringMethod =
type.element.lookUpMethod('toString', 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
// `toString` and reference the same types referenced in those
// parameters.
for (final parameter in toStringMethod.parameters) {
final parameterType = parameter.type;
if (parameterType is analyzer.InterfaceType) {
parameterType.element.accept(this);
}
}
}
}
if (type.isDartAsyncFutureOr) {
// For some methods which return `FutureOr`, we need a dummy `Future`
// subclass and value.
_addType(_futureType);
}
} else if (type is analyzer.FunctionType) {
_addType(type.returnType);
// [RecursiveElementVisitor] does not "step out of" the element model,
// into types, while traversing, so we must explicitly traverse [type]
// here, in order to visit contained elements.
for (final typeParameter in type.typeFormals) {
typeParameter.accept(this);
}
for (final parameter in type.parameters) {
parameter.accept(this);
}
final aliasElement = type.alias?.element;
if (aliasElement != null) {
_elements.add(aliasElement);
}
} else if (type is analyzer.RecordType) {
for (final f in type.positionalFields) {
_addType(f.type);
}
for (final f in type.namedFields) {
_addType(f.type);
}
}
}
void _addTypesFromConstant(DartObject object) {
final constant = ConstantReader(object);
if (constant.isNull ||
constant.isBool ||
constant.isInt ||
constant.isDouble ||
constant.isString ||
constant.isType) {
// No types to add from a literal.
return;
} else if (constant.isList) {
for (final element in constant.listValue) {
_addTypesFromConstant(element);
}
} else if (constant.isSet) {
for (final element in constant.setValue) {
_addTypesFromConstant(element);
}
} else if (constant.isMap) {
for (final pair in constant.mapValue.entries) {
_addTypesFromConstant(pair.key!);
_addTypesFromConstant(pair.value!);
}
} else if (object.toFunctionValue() != null) {
_elements.add(object.toFunctionValue()!);
} else {
// If [constant] is not null, a literal, or a type, then it must be an
// object constructed with `const`. Revive it.
final revivable = constant.revive();
for (final argument in revivable.positionalArguments) {
_addTypesFromConstant(argument);
}
for (final pair in revivable.namedArguments.entries) {
_addTypesFromConstant(pair.value);
}
_addType(object.type);
}
}
}
class _MockTarget {
/// The class to be mocked.
final analyzer.InterfaceType classType;
/// The desired name of the mock class.
final String mockName;
final List<analyzer.InterfaceType> mixins;
final OnMissingStub onMissingStub;
final Set<String> unsupportedMembers;
final Map<String, ExecutableElement> fallbackGenerators;
/// Instantiated mock was requested, i.e. `MockSpec<Foo<Bar>>`,
/// instead of `MockSpec<Foo>`.
final bool hasExplicitTypeArguments;
_MockTarget(
this.classType, {
required this.mixins,
required this.onMissingStub,
required this.unsupportedMembers,
required this.fallbackGenerators,
this.hasExplicitTypeArguments = false,
String? mockName,
}) : mockName = mockName ??
'Mock${classType.alias?.element.name ?? classType.element.name}';
InterfaceElement get interfaceElement => classType.element;
}
/// This class gathers and verifies mock targets referenced in `GenerateMocks`
/// annotations.
class _MockTargetGatherer {
final LibraryElement _entryLib;
final List<_MockTarget> _mockTargets;
final InheritanceManager3 _inheritanceManager;
_MockTargetGatherer._(
this._entryLib, this._mockTargets, this._inheritanceManager) {
_checkClassesToMockAreValid();
}
/// Searches the top-level elements of [entryLib] for `GenerateMocks`
/// annotations and creates a [_MockTargetGatherer] with all of the classes
/// identified as mocking targets.
factory _MockTargetGatherer(
LibraryElement entryLib,
InheritanceManager3 inheritanceManager,
) {
final mockTargets = <_MockTarget>{};
final possiblyAnnotatedElements = [
...entryLib.libraryExports,
...entryLib.libraryImports,
...entryLib.topLevelElements,
];
for (final element in possiblyAnnotatedElements) {
// TODO(srawlins): Re-think the idea of multiple @GenerateMocks
// annotations, on one element or even on different elements in a library.
for (final annotation in element.metadata) {
if (annotation.element is! ConstructorElement) continue;
final annotationClass = annotation.element!.enclosingElement!.name;
switch (annotationClass) {
case 'GenerateMocks':
mockTargets
.addAll(_mockTargetsFromGenerateMocks(annotation, entryLib));
case 'GenerateNiceMocks':
mockTargets.addAll(
_mockTargetsFromGenerateNiceMocks(annotation, entryLib));
}
}
}
return _MockTargetGatherer._(
entryLib, mockTargets.toList(), inheritanceManager);
}
static ast.NamedType? _mockType(ast.CollectionElement mockSpec) {
if (mockSpec is! ast.InstanceCreationExpression) {
throw InvalidMockitoAnnotationException(
'MockSpecs must be constructor calls inside the annotation, '
'please inline them if you are using a variable');
}
return mockSpec.constructorName.type.typeArguments?.arguments.firstOrNull
as ast.NamedType?;
}
static ast.ListLiteral? _customMocksAst(ast.Annotation annotation) =>
(annotation.arguments!.arguments
.firstWhereOrNull((arg) => arg is ast.NamedExpression)
as ast.NamedExpression?)
?.expression as ast.ListLiteral?;
static ast.ListLiteral _niceMocksAst(ast.Annotation annotation) =>
annotation.arguments!.arguments.first as ast.ListLiteral;
static Iterable<_MockTarget> _mockTargetsFromGenerateMocks(
ElementAnnotation annotation, LibraryElement entryLib) {
final generateMocksValue = annotation.computeConstantValue();
final classesField = generateMocksValue?.getField('classes');
if (classesField == null || classesField.isNull) {
throw InvalidMockitoAnnotationException(
'The GenerateMocks "classes" argument is missing, includes an '
'unknown type, or includes an extension');
}
final mockTargets = <_MockTarget>[];
for (final objectToMock in classesField.toListValue()!) {
final typeToMock = objectToMock.toTypeValue();
if (typeToMock == null) {
throw InvalidMockitoAnnotationException(
'The "classes" argument includes a non-type: $objectToMock');
}
if (typeToMock is analyzer.DynamicType ||
typeToMock is analyzer.InvalidType) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock `dynamic`');
}
var type = _determineDartType(typeToMock, entryLib.typeProvider);
if (type.alias == null) {
// For a generic class without an alias like `Foo<T>` or
// `Foo<T extends num>`, a type literal (`Foo`) cannot express type
// arguments. The type argument(s) on `type` have been instantiated to
// bounds here. Switch to the declaration, which will be an
// uninstantiated type.
type = (type.element.declaration as InterfaceElement).thisType;
}
mockTargets.add(_MockTarget(
type,
mixins: [],
onMissingStub: OnMissingStub.throwException,
unsupportedMembers: {},
fallbackGenerators: {},
));
}
final customMocksField = generateMocksValue?.getField('customMocks');
if (customMocksField != null && !customMocksField.isNull) {
final customMocksAsts =
_customMocksAst(annotation.annotationAst)?.elements ??
<ast.CollectionElement>[];
mockTargets.addAll(customMocksField.toListValue()!.mapIndexed(
(index, mockSpec) => _mockTargetFromMockSpec(
mockSpec, entryLib, index, customMocksAsts.toList())));
}
return mockTargets;
}
static _MockTarget _mockTargetFromMockSpec(
DartObject mockSpec,
LibraryElement entryLib,
int index,
List<ast.CollectionElement> mockSpecAsts,
{bool nice = false}) {
// need to get the parent until type name is not MockSpec to allow inheritance
while (mockSpec.type?.element?.name != "MockSpec") {
mockSpec = mockSpec.getField("(super)")!;
}
final mockSpecType = mockSpec.type as analyzer.InterfaceType;
assert(mockSpecType.typeArguments.length == 1);
final mockType = _mockType(mockSpecAsts[index]);
final typeToMock = mockSpecType.typeArguments.single;
if (typeToMock is analyzer.DynamicType ||
typeToMock is analyzer.InvalidType) {
final mockTypeName = mockType?.qualifiedName;
if (mockTypeName == null) {
throw InvalidMockitoAnnotationException(
'MockSpec requires a type argument to determine the class to mock. '
'Be sure to declare a type argument on the ${(index + 1).ordinal} '
'MockSpec() in @GenerateMocks.');
} else {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock unknown type `$mockTypeName`. Did you '
'misspell it or forget to add a dependency on it?');
}
}
var type = _determineDartType(typeToMock, entryLib.typeProvider);
final mockTypeArguments = mockType?.typeArguments;
if (mockTypeArguments != null) {
final typeName =
type.alias?.element.getDisplayString(withNullability: false) ??
'type $type';
final typeArguments = type.alias?.typeArguments ?? type.typeArguments;
// Check explicit type arguments for unknown types that were
// turned into `dynamic` by the analyzer.
typeArguments.forEachIndexed((typeArgIdx, typeArgument) {
if (!(typeArgument is analyzer.DynamicType ||
typeArgument is analyzer.InvalidType)) return;
if (typeArgIdx >= mockTypeArguments.arguments.length) return;
final typeArgAst = mockTypeArguments.arguments[typeArgIdx];
if (typeArgAst is! ast.NamedType) {
// Is this even possible?
throw InvalidMockitoAnnotationException(
'Undefined type $typeArgAst passed as the '
'${(typeArgIdx + 1).ordinal} type argument for mocked '
'$typeName.');
}
if (typeArgAst.qualifiedName == 'dynamic') return;
throw InvalidMockitoAnnotationException(
'Undefined type $typeArgAst passed as the '
'${(typeArgIdx + 1).ordinal} type argument for mocked $typeName. Are '
'you trying to pass to-be-generated mock class as a type argument? '
'Mockito does not support that (yet).',
);
});
} else if (type.alias == null) {
// The mock type was given without explicit type arguments. In this case
// the type argument(s) on `type` have been instantiated to bounds if this
// isn't a type alias. Switch to the declaration, which will be an
// uninstantiated type.
type = (type.element.declaration as InterfaceElement).thisType;
}
final mockName = mockSpec.getField('mockName')!.toSymbolValue();
final mixins = <analyzer.InterfaceType>[];
for (final m in mockSpec.getField('mixins')!.toListValue()!) {
final typeToMixin = m.toTypeValue();
if (typeToMixin == null) {
throw InvalidMockitoAnnotationException(
'The "mixingIn" argument includes a non-type: $m');
}
if (typeToMixin is analyzer.DynamicType ||
typeToMixin is analyzer.InvalidType) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mix `dynamic` into a mock class');
}
final mixinInterfaceType =
_determineDartType(typeToMixin, entryLib.typeProvider);
mixins.add(mixinInterfaceType);
}
final onMissingStubValue = mockSpec.getField('onMissingStub')!;
final OnMissingStub onMissingStub;
if (onMissingStubValue.isNull) {
onMissingStub =
nice ? OnMissingStub.returnDefault : OnMissingStub.throwException;
} else {
final onMissingStubIndex =
onMissingStubValue.getField('index')!.toIntValue()!;
onMissingStub = OnMissingStub.values[onMissingStubIndex];
}
final unsupportedMembers = {
for (final m in mockSpec.getField('unsupportedMembers')!.toSetValue()!)
m.toSymbolValue()!,
};
final fallbackGeneratorObjects =
mockSpec.getField('fallbackGenerators')!.toMapValue()!;
return _MockTarget(
type,
mockName: mockName,
mixins: mixins,
onMissingStub: onMissingStub,
unsupportedMembers: unsupportedMembers,
fallbackGenerators: _extractFallbackGenerators(fallbackGeneratorObjects),
hasExplicitTypeArguments: mockTypeArguments != null,
);
}
static Iterable<_MockTarget> _mockTargetsFromGenerateNiceMocks(
ElementAnnotation annotation, LibraryElement entryLib) {
final generateNiceMocksValue = annotation.computeConstantValue()!;
final mockSpecsField = generateNiceMocksValue.getField('mocks')!;
if (mockSpecsField.isNull) {
throw InvalidMockitoAnnotationException(
'The GenerateNiceMocks "mockSpecs" argument is missing');
}
final mockSpecAsts =
_niceMocksAst(annotation.annotationAst).elements.toList();
return mockSpecsField.toListValue()!.mapIndexed((index, mockSpec) =>
_mockTargetFromMockSpec(mockSpec, entryLib, index, mockSpecAsts,
nice: true));
}
static Map<String, ExecutableElement> _extractFallbackGenerators(
Map<DartObject?, DartObject?> objects) {
final fallbackGenerators = <String, ExecutableElement>{};
objects.forEach((methodName, generator) {
if (methodName == null) {
throw InvalidMockitoAnnotationException(
'Unexpected null key in fallbackGenerators: $objects');
}
if (generator == null) {
throw InvalidMockitoAnnotationException(
'Unexpected null value in fallbackGenerators for key '
'"$methodName"');
}
fallbackGenerators[methodName.toSymbolValue()!] =
generator.toFunctionValue()!;
});
return fallbackGenerators;
}
/// Map the values passed to the GenerateMocks annotation to the classes which
/// they represent.
///
/// This function is responsible for ensuring that each value is an
/// appropriate target for mocking. It will throw an
/// [InvalidMockitoAnnotationException] under various conditions.
static analyzer.InterfaceType _determineDartType(
analyzer.DartType typeToMock, TypeProvider typeProvider) {
if (typeToMock is analyzer.InterfaceType) {
final elementToMock = typeToMock.element;
final displayName = "'${elementToMock.displayName}'";
if (elementToMock is EnumElement) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock an enum: $displayName');
}
if (typeProvider.isNonSubtypableClass(elementToMock)) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock a non-subtypable type: '
'$displayName. It is illegal to subtype this '
'type.');
}
if (elementToMock is ClassElement) {
if (elementToMock.isSealed) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock a sealed class $displayName, '
'try mocking one of the variants instead.');
}
if (elementToMock.isBase) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock a base class $displayName.');
}
if (elementToMock.isFinal) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock a final class $displayName.');
}
}
if (elementToMock.isPrivate) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock a private type: $displayName.');
}
final typeParameterErrors =
_checkTypeParameters(elementToMock.typeParameters, elementToMock);
if (typeParameterErrors.isNotEmpty) {
final joinedMessages =
typeParameterErrors.map((m) => ' $m').join('\n');
throw InvalidMockitoAnnotationException(
'Mockito cannot generate a valid mock class which implements '
'$displayName for the following reasons:\n'
'$joinedMessages');
}
if (typeToMock.alias != null &&
typeToMock.nullabilitySuffix == NullabilitySuffix.question) {
throw InvalidMockitoAnnotationException(
'Mockito cannot mock a type-aliased nullable type: '
'${typeToMock.alias!.element.name}');
}
return typeToMock;
}
throw InvalidMockitoAnnotationException('Mockito cannot mock a non-class: '
'${typeToMock.alias?.element.name ?? typeToMock.toString()}');
}
void _checkClassesToMockAreValid() {
final classesInEntryLib =
_entryLib.topLevelElements.whereType<InterfaceElement>();
final classNamesToMock = <String, _MockTarget>{};
final uniqueNameSuggestion =
"use the 'customMocks' argument in @GenerateMocks to specify a unique "
'name';
for (final mockTarget in _mockTargets) {
final name = mockTarget.mockName;
if (classNamesToMock.containsKey(name)) {
final firstClass = classNamesToMock[name]!.interfaceElement;
final firstSource = firstClass.source.fullName;
final secondSource = mockTarget.interfaceElement.source.fullName;
throw InvalidMockitoAnnotationException(
'Mockito cannot generate two mocks with the same name: $name (for '
'${firstClass.name} declared in $firstSource, and for '
'${mockTarget.interfaceElement.name} declared in $secondSource); '
'$uniqueNameSuggestion.');
}
classNamesToMock[name] = mockTarget;
}
classNamesToMock.forEach((name, mockTarget) {
final conflictingClass =
classesInEntryLib.firstWhereOrNull((c) => c.name == name);
if (conflictingClass != null) {
throw InvalidMockitoAnnotationException(
'Mockito cannot generate a mock with a name which conflicts with '
'another class declared in this library: ${conflictingClass.name}; '
'$uniqueNameSuggestion.');
}
final preexistingMock = classesInEntryLib.firstWhereOrNull((c) =>
c.interfaces
.map((type) => type.element)
.contains(mockTarget.interfaceElement) &&
_isMockClass(c.supertype!));
if (preexistingMock != null) {
throw InvalidMockitoAnnotationException(
'The GenerateMocks annotation contains a class which appears to '
'already be mocked inline: ${preexistingMock.name}; '
'$uniqueNameSuggestion.');
}
_checkMethodsToStubAreValid(mockTarget);
});
}
/// Throws if any public instance methods of [mockTarget]'s class are not
/// valid stubbing candidates.
///
/// A method is not valid for stubbing if:
/// - It has a private type anywhere in its signature; Mockito cannot override
/// such a method.
void _checkMethodsToStubAreValid(_MockTarget mockTarget) {
final interfaceElement = mockTarget.interfaceElement;
final className = interfaceElement.name;
final substitution = Substitution.fromInterfaceType(mockTarget.classType);
final relevantMembers = _inheritanceManager
.getInterface(interfaceElement)
.map
.values
.where((m) => !m.isPrivate && !m.isStatic)
.map((member) => ExecutableMember.from2(member, substitution));
final unstubbableErrorMessages = relevantMembers.expand((member) {
if (_entryLib.typeSystem._returnTypeIsNonNullable(member) ||
_entryLib.typeSystem._hasNonNullableParameter(member) ||
_needsOverrideForVoidStub(member)) {
return _checkFunction(
member.type,
member,
allowUnsupportedMember:
mockTarget.unsupportedMembers.contains(member.name),
hasDummyGenerator:
mockTarget.fallbackGenerators.containsKey(member.name),
);
} else {
// Mockito is not going to override this method, so the types do not
// need to be checked.
return [];
}
}).toList();
if (unstubbableErrorMessages.isNotEmpty) {
final joinedMessages =
unstubbableErrorMessages.map((m) => ' $m').join('\n');
throw InvalidMockitoAnnotationException(
'Mockito cannot generate a valid mock class which implements '
"'$className' for the following reasons:\n$joinedMessages");
}
}
String get _tryUnsupportedMembersMessage => 'Try generating this mock with '
"a MockSpec with 'unsupportedMembers' or a dummy generator (see "
'https://pub.dev/documentation/mockito/latest/annotations/MockSpec-class.html).';
/// Checks [function] for properties that would make it un-stubbable.
///
/// Types are checked in the following positions:
/// - return type
/// - parameter types
/// - bounds of type parameters
/// - recursively, written types on types in the above three positions
/// (namely, type arguments, return types of function types, and parameter
/// types of function types)
///
/// If any type in the above positions is private, [function] is un-stubbable.
/// If the return type is potentially non-nullable, [function] is
/// un-stubbable, unless [isParameter] is true (indicating that [function] is
/// found in a parameter of a method-to-be-stubbed) or
/// [allowUnsupportedMember] is true, or [hasDummyGenerator] is true
/// (indicating that a dummy generator, which can return dummy values, has
/// been provided).
List<String> _checkFunction(
analyzer.FunctionType function,
Element enclosingElement, {
bool isParameter = false,
bool allowUnsupportedMember = false,
bool hasDummyGenerator = false,
}) {
final errorMessages = <String>[];
final returnType = function.returnType;
if (returnType is analyzer.InterfaceType) {
if (returnType.containsPrivateName) {
if (!allowUnsupportedMember && !hasDummyGenerator) {
errorMessages.add(
'${enclosingElement.fullName} features a private return type, '
'and cannot be stubbed. $_tryUnsupportedMembersMessage');
}
}
errorMessages.addAll(_checkTypeArguments(
returnType.typeArguments,
enclosingElement,
isParameter: isParameter,
allowUnsupportedMember: allowUnsupportedMember,
));
} else if (returnType is analyzer.FunctionType) {
errorMessages.addAll(_checkFunction(returnType, enclosingElement,
allowUnsupportedMember: allowUnsupportedMember,
hasDummyGenerator: hasDummyGenerator));
}
for (final parameter in function.parameters) {
final parameterType = parameter.type;
if (parameterType is analyzer.InterfaceType) {
final parameterTypeElement = parameterType.element;
if (parameterTypeElement.isPrivate) {
// Technically, we can expand the type in the mock to something like
// `Object?`. However, until there is a decent use case, we will not
// generate such a mock.
if (!allowUnsupportedMember) {
errorMessages.add(
'${enclosingElement.fullName} features a private parameter '
"type, '${parameterTypeElement.name}', and cannot be stubbed. "
'$_tryUnsupportedMembersMessage');
}
}
errorMessages.addAll(_checkTypeArguments(
parameterType.typeArguments,
enclosingElement,
isParameter: true,
allowUnsupportedMember: allowUnsupportedMember,
));
} else if (parameterType is analyzer.FunctionType) {
errorMessages.addAll(
_checkFunction(parameterType, enclosingElement, isParameter: true));
}
}
errorMessages
.addAll(_checkTypeParameters(function.typeFormals, enclosingElement));
final aliasArguments = function.alias?.typeArguments;
if (aliasArguments != null) {
errorMessages.addAll(_checkTypeArguments(aliasArguments, enclosingElement,
isParameter: isParameter));
}
return errorMessages;
}
/// Checks the bounds of [typeParameters] for properties that would make the
/// enclosing method un-stubbable.
static List<String> _checkTypeParameters(
List<TypeParameterElement> typeParameters, Element enclosingElement) {
final errorMessages = <String>[];
for (final element in typeParameters) {
final typeParameter = element.bound;
if (typeParameter == null) continue;
if (typeParameter is analyzer.InterfaceType) {
// TODO(srawlins): Check for private names in bound; could be
// `List<_Bar>`.
if (typeParameter.element.isPrivate) {
errorMessages.add(
'${enclosingElement.fullName} features a private type parameter '
'bound, and cannot be stubbed.');
}
}
}
return errorMessages;
}
/// Checks [typeArguments] for properties that would make the enclosing
/// method un-stubbable.
///
/// See [_checkMethodsToStubAreValid] for what properties make a function
/// un-stubbable.
List<String> _checkTypeArguments(
List<analyzer.DartType> typeArguments,
Element enclosingElement, {
bool isParameter = false,
bool allowUnsupportedMember = false,
}) {
final errorMessages = <String>[];
for (final typeArgument in typeArguments) {
if (typeArgument is analyzer.InterfaceType) {
if (typeArgument.element.isPrivate && !allowUnsupportedMember) {
errorMessages.add(
'${enclosingElement.fullName} features a private type argument, '
'and cannot be stubbed. $_tryUnsupportedMembersMessage');
}
} else if (typeArgument is analyzer.FunctionType) {
errorMessages.addAll(_checkFunction(