How to use CustomTypeSafeMatcher class of org.hamcrest package

Best junit code snippet using org.hamcrest.CustomTypeSafeMatcher

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *	   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18package org.w3.ldp.testsuite.matcher;
19
20import java.util.regex.Pattern;
21
22import org.apache.commons.lang3.StringUtils;
23import org.hamcrest.BaseMatcher;
24import org.hamcrest.CustomTypeSafeMatcher;
25import org.hamcrest.Description;
26import org.hamcrest.Matcher;
27import org.jboss.resteasy.plugins.delegates.LinkDelegate;
28import org.w3.ldp.testsuite.http.MediaTypes;
29
30import javax.ws.rs.core.Link;
31
32/**
33 * Matcher collection to work with HttpHeaders.
34 */
35public class HeaderMatchers {
36
37	private static final Pattern TURTLE_REGEX = Pattern.compile("^" + MediaTypes.TEXT_TURTLE + "\\s*(;|$)");
38	/**
39	 * Regular expression matching valid ETag values.
40	 *
41	 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19">HTTP 1.1: Section 14.19 - ETag</a>
42	 */
43	public final static String ETAG_REGEX = "^(W/)?\"([^\"]|\\\\\")*\"$";
44
45	public static Matcher<String> headerPresent() {
46		return new BaseMatcher<String>() {
47			@Override
48			public boolean matches(Object item) {
49				return item != null && StringUtils.isNotBlank(item.toString());
50			}
51
52			@Override
53			public void describeTo(Description description) {
54				description.appendText("set");
55			}
56		};
57	}
58
59	public static Matcher<String> headerNotPresent() {
60		return new BaseMatcher<String>() {
61			@Override
62			public boolean matches(Object item) {
63				return item == null || StringUtils.isBlank(item.toString());
64			}
65
66			@Override
67			public void describeTo(Description description) {
68				description.appendText("absent or empty");
69			}
70		};
71	}
72
73	public static Matcher<String> isLink(String uri, String rel) {
74		final Link expected = Link.fromUri(uri).rel(rel).build();
75		return new CustomTypeSafeMatcher<String>(String.format("a Link-Header to <%s> with rel='%s'", uri, rel)) {
76			@Override
77			protected boolean matchesSafely(String item) {
78				return expected.equals(new LinkDelegate().fromString(item));
79			}
80		};
81	}
82
83
84	public static Matcher<String> isValidEntityTag() {
85		return new CustomTypeSafeMatcher<String>("a valid EntityTag value as defined in RFC2616 section 14.19 (did you quote the value?)") {
86			/**
87			 * Checks that the ETag value is present and valid as defined in RFC2616
88			 *
89			 * @param item
90			 *			  the header value
91			 * @return true only if the ETag is valid
92			 *
93			 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19">HTTP 1.1: Section 14.19 - ETag</a>
94			 */
95			@Override
96			protected boolean matchesSafely(String item) {
97				return item.trim().matches(ETAG_REGEX);
98			}
99		};
100	}
101
102	/**
103	 * Matcher testing a Content-Type response header's compatibility with
104	 * JSON-LD (expects application/ld+json or application/json).
105	 *
106	 * @return the matcher
107	 */
108	public static Matcher<String> isJsonLdCompatibleContentType() {
109		return new CustomTypeSafeMatcher<String>("application/ld+json or application/json") {
110			@Override
111			protected boolean matchesSafely(String item) {
112				return item.equals(MediaTypes.APPLICATION_LD_JSON) || item.equals(MediaTypes.APPLICATION_JSON);
113			}
114		};
115	}
116
117	/**
118	 * Matcher testing a Content-Type response header's compatibility with
119	 * Turtle (expects text/turtle).
120	 *
121	 * @return the matcher
122	 */
123	public static Matcher<String> isTurtleCompatibleContentType() {
124		return new CustomTypeSafeMatcher<String>("text/turtle") {
125			@Override
126			protected boolean matchesSafely(String item) {
127				return MediaTypes.TEXT_TURTLE.equals(item)
128						|| TURTLE_REGEX.matcher(item).find();
129			}
130		};
131	}
132}
133
Full Screen
copy
1package com.github.dockerjava.junit;
2
3import com.github.dockerjava.api.command.InspectContainerResponse;
4import com.github.dockerjava.api.model.Volume;
5import com.github.dockerjava.core.DockerRule;
6import com.github.dockerjava.core.RemoteApiVersion;
7import org.hamcrest.CustomTypeSafeMatcher;
8import org.hamcrest.Description;
9import org.hamcrest.FeatureMatcher;
10import org.hamcrest.Matcher;
11
12import java.util.ArrayList;
13import java.util.List;
14
15import static com.github.dockerjava.utils.TestUtils.getVersion;
16
17/**
18 * @author Kanstantsin Shautsou
19 */
20public class DockerMatchers {
21    private DockerMatchers() {
22    }
23
24    public static MountedVolumes mountedVolumes(Matcher<? super List<Volume>> subMatcher) {
25        return new MountedVolumes(subMatcher, "Mounted volumes", "mountedVolumes");
26    }
27
28    public static class MountedVolumes extends FeatureMatcher<InspectContainerResponse, List<Volume>> {
29        public MountedVolumes(Matcher<? super List<Volume>> subMatcher, String featureDescription, String featureName) {
30            super(subMatcher, featureDescription, featureName);
31        }
32
33        @Override
34        public List<Volume> featureValueOf(InspectContainerResponse item) {
35            List<Volume> volumes = new ArrayList<>();
36            for (InspectContainerResponse.Mount mount : item.getMounts()) {
37                volumes.add(mount.getDestination());
38            }
39            return volumes;
40        }
41    }
42
43
44    public static Matcher<DockerRule> apiVersionGreater(final RemoteApiVersion version) {
45        return new CustomTypeSafeMatcher<DockerRule>("is greater") {
46            public boolean matchesSafely(DockerRule dockerRule) {
47                return getVersion(dockerRule.getClient()).isGreater(version);
48            }
49        };
50    }
51
52    public static Matcher<DockerRule> isGreaterOrEqual(final RemoteApiVersion version) {
53        return new CustomTypeSafeMatcher<DockerRule>("is greater or equal") {
54            public boolean matchesSafely(DockerRule dockerRule) {
55                return getVersion(dockerRule.getClient()).isGreaterOrEqual(version);
56            }
57
58            @Override
59            protected void describeMismatchSafely(DockerRule rule, Description mismatchDescription) {
60                mismatchDescription
61                        .appendText(" was ")
62                        .appendText(getVersion(rule.getClient()).toString());
63            }
64        };
65    }
66}
67
Full Screen
copy
1package com.bluecatcode.hamcrest.matchers;
2
3import org.hamcrest.CustomTypeSafeMatcher;
4import org.hamcrest.Description;
5import org.hamcrest.Factory;
6import org.hamcrest.Matcher;
7
8import static org.hamcrest.Matchers.allOf;
9import static org.hamcrest.Matchers.is;
10import static org.hamcrest.core.IsInstanceOf.instanceOf;
11
12public class IsThrowable<T extends Throwable> extends CustomTypeSafeMatcher<T> {
13
14    private final Matcher<T> matcher;
15
16    public IsThrowable(Matcher<T> matcher) {
17        super(CustomMatchers.fixedDescription(matcher));
18        this.matcher = matcher;
19    }
20
21    @Override
22    protected boolean matchesSafely(T item) {
23        return matcher.matches(item);
24    }
25
26    public void describeMismatchSafely(T item, Description mismatchDescription) {
27        matcher.describeMismatch(item, mismatchDescription);
28    }
29
30    /**
31     * Matches if value is a Throwable of type <tt>type</tt>
32     *
33     * @param type throwable type
34     * @param <T> the throwable type
35     * @return the matcher
36     */
37    @Factory
38    public static <T extends Throwable> Matcher<T> isThrowable(Class<?> type) {
39        final Matcher<T> typeMatcher = instanceOf(type);
40        return new IsThrowable<>(typeMatcher);
41    }
42
43    /**
44     * Matches if value is a Throwable of type <tt>type</tt> that matches the <tt>matcher</tt>
45     *
46     * @param type    throwable type
47     * @param matcher throwable matcher
48     * @param <T> the throwable type
49     * @return the matcher
50     */
51    @Factory
52    public static <T extends Throwable> Matcher<T> isThrowable(Class<?> type, Matcher<? super T> matcher) {
53        final Matcher<T> typeMatcher = instanceOf(type);
54        return new IsThrowable<>(allOf(typeMatcher, matcher));
55    }
56
57    /**
58     * Matches if value is a throwable with the <tt>message</tt>
59     *
60     * @param message message to match
61     * @param <T> the throwable type
62     * @return the matcher
63     */
64    @Factory
65    public static <T extends Throwable> Matcher<T> withMessage(String message) {
66        return withMessage(is(message));
67    }
68
69    /**
70     * Matches if value is a throwable with a message that matches the <tt>matcher</tt>
71     *
72     * @param matcher message matcher
73     * @param <T> the throwable type
74     * @return the matcher
75     */
76    @Factory
77    public static <T extends Throwable> Matcher<T> withMessage(final Matcher<String> matcher) {
78        return new CustomTypeSafeMatcher<T>(CustomMatchers.fixedDescription("message ", matcher)) {
79            @Override
80            protected boolean matchesSafely(T item) {
81                return matcher.matches(item.getMessage());
82            }
83
84            public void describeMismatchSafely(T item, Description mismatchDescription) {
85                matcher.describeMismatch(item.getMessage(), mismatchDescription);
86            }
87        };
88    }
89
90    /**
91     * Matches if value is a throwable with a cause that matches the <tt>matcher</tt>
92     *
93     * @param matcher cause matcher
94     * @param <T> the throwable type
95     * @param <C> the cause throwable type
96     * @return the matcher
97     */
98    @Factory
99    public static <T extends Throwable, C extends Throwable> Matcher<T> withCause(final Matcher<C> matcher) {
100        return new CustomTypeSafeMatcher<T>(CustomMatchers.fixedDescription("cause ", matcher)) {
101            @Override
102            protected boolean matchesSafely(T item) {
103                return matcher.matches(item.getCause());
104            }
105
106            public void describeMismatchSafely(T item, Description mismatchDescription) {
107                matcher.describeMismatch(item.getCause(), mismatchDescription);
108            }
109        };
110    }
111}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on CustomTypeSafeMatcher

Most used methods in CustomTypeSafeMatcher

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)