Skip to content

Commit

Permalink
Use FeatureMatcher for containsKey and containsValue
Browse files Browse the repository at this point in the history
  • Loading branch information
natebosch committed Oct 25, 2024
1 parent ab8f659 commit c5fbf31
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions pkgs/matcher/lib/src/map_matchers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,20 @@
// 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 'feature_matcher.dart';
import 'interfaces.dart';
import 'util.dart';

/// Returns a matcher which matches maps containing the given [value].
Matcher containsValue(Object? value) => _ContainsValue(value);

class _ContainsValue extends Matcher {
class _ContainsValue extends FeatureMatcher<Map> {
final Object? _value;

const _ContainsValue(this._value);

@override
bool matches(Object? item, Map matchState) =>
// ignore: avoid_dynamic_calls
(item as dynamic).containsValue(_value);
bool typedMatches(Map item, Map matchState) => item.containsValue(_value);
@override
Description describe(Description description) =>
description.add('contains value ').addDescriptionOf(_value);
Expand All @@ -27,17 +26,15 @@ class _ContainsValue extends Matcher {
Matcher containsPair(Object? key, Object? valueOrMatcher) =>
_ContainsMapping(key, wrapMatcher(valueOrMatcher));

class _ContainsMapping extends Matcher {
class _ContainsMapping extends FeatureMatcher<Map> {
final Object? _key;
final Matcher _valueMatcher;

const _ContainsMapping(this._key, this._valueMatcher);

@override
bool matches(Object? item, Map matchState) =>
// ignore: avoid_dynamic_calls
(item as dynamic).containsKey(_key) &&
_valueMatcher.matches((item as dynamic)[_key], matchState);
bool typedMatches(Map item, Map matchState) =>
item.containsKey(_key) && _valueMatcher.matches(item[_key], matchState);

@override
Description describe(Description description) {
Expand All @@ -49,10 +46,9 @@ class _ContainsMapping extends Matcher {
}

@override
Description describeMismatch(Object? item, Description mismatchDescription,
Map matchState, bool verbose) {
// ignore: avoid_dynamic_calls
if (!((item as dynamic).containsKey(_key) as bool)) {
Description describeTypedMismatch(
Map item, Description mismatchDescription, Map matchState, bool verbose) {
if (!item.containsKey(_key)) {
return mismatchDescription
.add(" doesn't contain key ")
.addDescriptionOf(_key);
Expand All @@ -62,7 +58,7 @@ class _ContainsMapping extends Matcher {
.addDescriptionOf(_key)
.add(' but with value ');
_valueMatcher.describeMismatch(
(item as dynamic)[_key], mismatchDescription, matchState, verbose);
item[_key], mismatchDescription, matchState, verbose);
return mismatchDescription;
}
}
Expand Down

0 comments on commit c5fbf31

Please sign in to comment.