JavaHamcrest-2.2/000077500000000000000000000000001355170103300137235ustar00rootroot00000000000000JavaHamcrest-2.2/.gitignore000066400000000000000000000002501355170103300157100ustar00rootroot00000000000000build/ classes/ bin/ out/ .DS_Store *~ *.swp .idea/ *.iws *.ipr *.iml .classpath .gradle .project .settings/ gradle.properties release-key.asc grade-wrapper.properties JavaHamcrest-2.2/.travis.yml000066400000000000000000000013711355170103300160360ustar00rootroot00000000000000language: java # Need to select an older Ubuntu distribution that supports JDK7 dist: trusty # Workaround to using openjdk7 with Gradle due to security issue: # https://github.com/gradle/gradle/issues/2421 before_install: - BCPROV_FILENAME=bcprov-ext-jdk15on-158.jar - wget "https://bouncycastle.org/download/${BCPROV_FILENAME}" - sudo mv $BCPROV_FILENAME /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext - sudo perl -pi.bak -e 's/^(security\.provider\.)([0-9]+)/$1.($2+1)/ge' /etc/java-7-openjdk/security/java.security - echo "security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider" | sudo tee -a /etc/java-7-openjdk/security/java.security jdk: - openjdk7 - oraclejdk8 - openjdk8 - oraclejdk9 script: - ./gradlew clean build javadoc JavaHamcrest-2.2/BUILDING.txt000066400000000000000000000010431355170103300156570ustar00rootroot00000000000000 ********************** ********************* Building Hamcrest ********************* ********************** --[ Build requirements ]------------------------------------- * JDK 1.7 --[ Building from the command line ]------------------------- Execute Gradle target: ./gradlew clean build javadoc This will download the correct version of Gradle, do a full clean build, run all tests and (if successful) package up a distribution. The resulting builds reside in the 'build' directory. JavaHamcrest-2.2/CHANGES.md000066400000000000000000000176471355170103300153340ustar00rootroot00000000000000# Hamcrest Changes ## Version 2.2 (Unreleased) ### Improvements * AllOf/AnyOf: Pass the matchers to constructor using varargs ([Issue #245](https://github.com/hamcrest/JavaHamcrest/pull/245)) * Matchers.anyOf: Fix generic bounds compatibility for JDK 11 ([Issue #256](https://github.com/hamcrest/JavaHamcrest/issues/256), [Issue #257](https://github.com/hamcrest/JavaHamcrest/issues/257)) * AssertionError message is unhelpful when match fails for byte type ([Issue #254](https://github.com/hamcrest/JavaHamcrest/issues/254), [Issue #255](https://github.com/hamcrest/JavaHamcrest/issues/255)) * Use platform specific line breaks ([PR #267](https://github.com/hamcrest/JavaHamcrest/pull/267)) * Build now checks for consistent use of spaces ([PR #217](https://github.com/hamcrest/JavaHamcrest/pull/217)) ### Bugfixes * Fix compatibility issue for development with Android D8 ([Issue #246](https://github.com/hamcrest/JavaHamcrest/issues/246)) * Fix typo in license name ([Issue #247](https://github.com/hamcrest/JavaHamcrest/pull/247)) * 1.3 compatible constructors for string matchers ([Issue #259](https://github.com/hamcrest/JavaHamcrest/issues/259), [Issue #260](https://github.com/hamcrest/JavaHamcrest/issues/260)) * Fix for split packages with Java 9 modules ([Issue #269](https://github.com/hamcrest/JavaHamcrest/issues/269), [PR #270](https://github.com/hamcrest/JavaHamcrest/pull/270)) ## Version 2.1 (21st December 2018) ### Overview for 2.1 After a long hiatus without releases, this version simplifies the packaging of Hamcrest into a single jar: `hamcrest-.jar`. Other big changes include Java 9 module compatibility, migrating the code repository from Google Code to GitHub, along with numerous other new features, improvements and bug fixes. ### Breaking Changes for 2.1 * The way that the project is packaged has changed. This may cause problems with correctly upgrading transitive dependencies. Refer to the [Hamcrest Distributables](http://hamcrest.org/JavaHamcrest/distributables.html) documentation for more information, and in particular, [Upgrading from Hamcrest 1.x](http://hamcrest.org/JavaHamcrest/distributables.html#upgrading-from-hamcrest-1.x) * `org.hamcrest.Factory` has been removed. This was only used in old implementations of the hamcrest build toolchain, and can safely be deleted from client code without any effect. ### Changes for 2.1 * Documentation updates * Several JavaDoc improvements and corrections * Fix JavaDoc examples * Upgraded to Java 7 * Build with Gradle * Publish a single jar `hamcrest-2.1.jar` * Publish pom-only artifacts for `hamcrest-core` and `hamcrest-library`. * Add implementation for CharSequence length matcher * Fix for TypeSafeDiagnosingMatcher can't detect generic types for subclass * Make Hamcrest an OSGI bundle * Add StringRegularExpression matcher * Fix StringContainsInOrder to detect if a repeated pattern is missing * Add ArrayAsIterableMatcher * Fix description for IsEqualIgnoringCase * Removed deprecated methods from previous release * Improve mismatch description of hasItem/hasItems * General improvements to mismatch descriptions * Deprecated several matcher factory methods of the for "isXyz" * Fix [GH issue #75](https://github.com/hamcrest/JavaHamcrest/issues/75) - address doclint errors reported in JDK 1.8 * Fix [GH issue #69](https://github.com/hamcrest/JavaHamcrest/issues/69) - Iterable contains in order is null-safe * Fix [GH issue #59](https://github.com/hamcrest/JavaHamcrest/issues/59) - added equalToObject() (i.e. unchecked) method * Fix [GH issue #25](https://github.com/hamcrest/JavaHamcrest/issues/25) - arrayContaining(null, null) cause NullPointerException * Fix [GH issue #36](https://github.com/hamcrest/JavaHamcrest/issues/36) - string matching on regular expressions * Fix [GH issue #8](https://github.com/hamcrest/JavaHamcrest/issues/8) - isCloseTo() shows wrong delta in mismatch description * Fix [GH issue #59](https://github.com/hamcrest/JavaHamcrest/issues/59) - add untyped version of equalTo, named equalToObject * Fix [GC issue #131](https://code.google.com/archive/p/hamcrest/issues/131) - Implement IsEmptyMap, IsMapWithSize * Fix [GC issue #187](https://code.google.com/archive/p/hamcrest/issues/187) - IsArray.describeMismatchSafely() should use Matcher.describeMismatch * Fix [GC issue #155](https://code.google.com/archive/p/hamcrest/issues/155) - Add Matcher implementation for files * Fix [GC issue #69](https://code.google.com/archive/p/hamcrest/issues/69) - fix NPE in IsIterableContainingInOrder ## Version 1.3 (9th July 2012) * Introduce Condition class to ease the implementation of multi-step matches * Upgrade qdox (included in the generator) to the latest stable version * Correct inadvertent deprecation of the Is.isA factory method * Fix [issue #179](https://code.google.com/archive/p/hamcrest/issues/179) - AllOf does not output mismatch description * Fix [issue #177](https://code.google.com/archive/p/hamcrest/issues/177) - Introduced closeTo matcher for BigDecimals * Fix [issue #152](https://code.google.com/archive/p/hamcrest/issues/152) - Factory classes missing from matchers.xml * Fix [issue #144](https://code.google.com/archive/p/hamcrest/issues/144) - OrderingComparison doesn't describe mismatch of comparables that return values other than (-1,0,1) * Fix [issue #134](https://code.google.com/archive/p/hamcrest/issues/134) - DescribedAs does not delegate describeMismatch * Fix [issue #106](https://code.google.com/archive/p/hamcrest/issues/106) - deprecation warning when writing custom matchers * Fix [issue #101](https://code.google.com/archive/p/hamcrest/issues/101) - Added theInstance alias for sameInstance factory method ## Version 1.3 RC2 (22nd October 2010) * Added FeatureMatcher * distinguish between instanceOf() and any() ## Version 1.2 (16th May 2009) * Added mismatch reporting * Added WithSamePropertyValuesAs matcher * Moved any() from IsAnything to IsInstanceOf. It now checks the type of the matched object * Moved MatcherAssert from integration to core * Tightened up generics. * Added IsMapContainingKey and IsMapContainingValue matchers to resolve a generics bug in hasKey and hasValue static factories previously declared in IsMapContaining (ngd) * Added IsCollectionOnlyContaining and IsArrayOnlyContaining which matches collections (and arrays) where all match a given matcher. E.g onlyContains(3,4,5) or onlyContains(lessThan(9)) * text module moved to separate project, hamcrest-text-patterns * added more colection matchers: xContainingInAnyOrder, xContainingInOrder, xWithSize * new text Matcher: IsEmptyString * hamcrest generator uses method return type ## Version 1.1 (30th June 2007) * Hamcrest Generator now includes JavaDoc and parameter names in generated code by using QDox to parse the source code. * Created hamcrest-core.jar (and removed hamcrest-api.jar). Moved core set of matchers (and, eq, not, etc) to this package to make it more practical for external libraries to embed Hamcrest. * Created CoreMatchers (static import sugar) in hamcrest-core.jar. * StringBuilder can use any Appendable (not just StringBuffer). * Added sensible toString() method to BaseMatcher. * Created StringDescription.asString() alias (because toString() caused issues with static imports). * Relaxed isInstanceOf() matcher generic type so it can be used on any kind of object. e.g. assertThat(someUnknownObject, isInstanceOf(String.class)); * Added any(Class), null(Class) and notNull(Class) matchers, which returns Matcher. Helpful when the compiler struggles with type inference. * Modified anyOf() and allOf() to accept mixed-types. * TypeSafeMatcher.matchesSafely() is now public. * Generator recognizes @Factory methods that return subclass of Matcher. (Fix by David Saff) ## Version 1.0 (15th Dececmber 2006) Initial release. * Support for namespaces in HasXPath * Bug fix for matching empty elements with HasXPath JavaHamcrest-2.2/LICENSE.txt000066400000000000000000000027441355170103300155550ustar00rootroot00000000000000BSD License Copyright (c) 2000-2015 www.hamcrest.org All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Hamcrest nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. JavaHamcrest-2.2/README.md000066400000000000000000000033201355170103300152000ustar00rootroot00000000000000![JavaHamcrest](http://hamcrest.org/images/logo.jpg) [![Build Status](https://travis-ci.org/hamcrest/JavaHamcrest.png?branch=master)](https://travis-ci.org/hamcrest/JavaHamcrest) Java Hamcrest ============= Licensed under [BSD License][]. What is Hamcrest? ----------------- Hamcrest is a library of matchers, which can be combined in to create flexible expressions of intent in tests. They've also been used for other purposes. Downloads --------- You can obtain Hamcrest binaries from [maven central][]. Extensions ---------- For Hamcrest extension projects see the [hamcrest extensions page][]. Documentation ------------- Documentation can be found on the [Hamcrest site](http://hamcrest.org). Reporting Bugs/Issues --------------------- If you find an issue with Java Hamcrest, please report it via the [GitHub issue tracker](https://github.com/hamcrest/JavaHamcrest/issues), after first checking that it hasn't been raised already. Source ------ To build, please read BUILDING.txt Acknowledgements ---------------- Developers: * Joe Walnes * Nat Pryce * Steve Freeman Contributors: * Robert Chatley * Tom White * Neil Dunn * Dan North * Magne Rasmussen * David Saff * Tom Denley Also, thanks to everyone who has worked on DynaMock, nMock, jMock, EasyMock and MiniMock! These libraries inspired Hamcrest. [logo]: http://hamcrest.org/images/logo.jpg [website]: https://github.com/hamcrest/JavaHamcrest [BSD License]: http://opensource.org/licenses/BSD-3-Clause [Maven central]: http://search.maven.org/#search%7Cga%7C1%7Cg%3Aorg.hamcrest [hamcrest extensions page]: https://github.com/hamcrest/JavaHamcrest/wiki/Related-Projects [GitHub issue tracker]: https://github.com/hamcrest/JavaHamcrest/issues JavaHamcrest-2.2/build.gradle000066400000000000000000000106541355170103300162100ustar00rootroot00000000000000apply plugin: 'signing' apply plugin: 'osgi' apply plugin: 'maven-publish' group = "org.hamcrest" version = "2.2" subprojects { apply plugin: 'checkstyle' apply plugin: 'java-library' sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 group = rootProject.group version = rootProject.version repositories { mavenCentral() } checkstyle { project.ext.checkstyleVersion = '6.18' //works with a JDK 7 version which is supposed to be supported although //deprecated, see https://github.com/hamcrest/JavaHamcrest/pull/211 for //the discussion about the support sourceSets = [ project.sourceSets.main, project.sourceSets.test ] ignoreFailures = false configFile = file("${project.rootDir}/checkstyle.xml") configurations { checkstyle } dependencies{ assert project.hasProperty("checkstyleVersion") checkstyle "com.puppycrawl.tools:checkstyle:${checkstyleVersion}" } } test { testLogging { exceptionFormat = 'full' } } task sourcesJar(type: Jar) { classifier = 'sources' from sourceSets.main.allSource } task javadocJar(type: Jar) { classifier = 'javadoc' from javadoc } } def pomConfigurationFor(String pomName, String pomDescription) { return { name = pomName description = pomDescription url = 'http://hamcrest.org/JavaHamcrest/' scm { connection = 'git@github.com:hamcrest/JavaHamcrest.git' url = 'https://github.com/hamcrest/JavaHamcrest' } licenses { license { name = 'BSD License 3' url = 'http://opensource.org/licenses/BSD-3-Clause' } } developers { developer { id = 'joewalnes' name = 'Joe Walnes' } developer { id = 'npryce' name = 'Nat Pryce' } developer { id = 'sf105' name = 'Steve Freeman' } } } } def publishToOssrh = project.hasProperty('ossrhUsername') && project.hasProperty('ossrhPassword') publishing { publications { def hamcrestProject = project(':hamcrest') hamcrest(MavenPublication) { from hamcrestProject.components.java artifactId hamcrestProject.name artifact hamcrestProject.sourcesJar artifact hamcrestProject.javadocJar pom pomConfigurationFor( 'Hamcrest', 'Core API and libraries of hamcrest matcher framework.') } def hamcrestCoreProject = project(':hamcrest-core') hamcrestCore(MavenPublication) { from hamcrestCoreProject.components.java artifactId hamcrestCoreProject.name artifact hamcrestCoreProject.sourcesJar artifact hamcrestCoreProject.javadocJar pom pomConfigurationFor( 'Hamcrest Core', 'Core Hamcrest API - deprecated, please use "hamcrest" instead') } def hamcrestLibraryProject = project(':hamcrest-library') hamcrestLibrary(MavenPublication) { from hamcrestLibraryProject.components.java artifactId hamcrestLibraryProject.name artifact hamcrestLibraryProject.sourcesJar artifact hamcrestLibraryProject.javadocJar pom pomConfigurationFor( 'Hamcrest Library', 'A library of Hamcrest matchers - deprecated, please use "hamcrest" instead') } } repositories { if (publishToOssrh) { maven { def snapshotRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots/" def stagingRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" url = version.contains('SNAPSHOT') ? snapshotRepoUrl : stagingRepoUrl credentials { username = ossrhUsername password = ossrhPassword } } } } } signing { required { publishToOssrh } sign publishing.publications.hamcrest sign publishing.publications.hamcrestCore sign publishing.publications.hamcrestLibrary } JavaHamcrest-2.2/build.xml.original000066400000000000000000000367051355170103300173620ustar00rootroot00000000000000 JavaHamcrest-2.2/checkstyle.xml000066400000000000000000000006471355170103300166120ustar00rootroot00000000000000 JavaHamcrest-2.2/docs/000077500000000000000000000000001355170103300146535ustar00rootroot00000000000000JavaHamcrest-2.2/docs/_config.yml000066400000000000000000000000231355170103300167750ustar00rootroot00000000000000markdown: kramdown JavaHamcrest-2.2/docs/_includes/000077500000000000000000000000001355170103300166205ustar00rootroot00000000000000JavaHamcrest-2.2/docs/_includes/head.html000066400000000000000000000007611355170103300204130ustar00rootroot00000000000000 {{ page.title }} JavaHamcrest-2.2/docs/_layouts/000077500000000000000000000000001355170103300165125ustar00rootroot00000000000000JavaHamcrest-2.2/docs/_layouts/default.html000066400000000000000000000011671355170103300210310ustar00rootroot00000000000000 {% include head.html %}
{{ content }}
Fork me on GitHub JavaHamcrest-2.2/docs/css/000077500000000000000000000000001355170103300154435ustar00rootroot00000000000000JavaHamcrest-2.2/docs/css/hamcrest.css000066400000000000000000000013531355170103300177650ustar00rootroot00000000000000@import url(https://fonts.googleapis.com/css?family=Cabin+Sketch); @import url(https://fonts.googleapis.com/css?family=Alegreya); body { font-family: "Alegreya"; margin: 40px auto; width: 700px; } .content { position: relative; } footer { padding: 2em 0 1em 0; font-size: 12px; } h1 { font-size: 80px; margin-top: .3em; margin-bottom: 0; } h1 + h2 { margin-top: 0; } h2 { font-weight: 400; font-size: 20px; } h1, h2 { font-family: "Cabin Sketch"; text-rendering: optimizeLegibility; } .content > p { line-height: 1.5em; text-rendering: optimizeLegibility; } .logo { height: 60px; padding-left: 0px; padding-right: 40px; } pre.highlight { border: 1px solid #ccc; background-color: #eee; padding: 0.5em; }JavaHamcrest-2.2/docs/css/pygments-default.css000066400000000000000000000074351355170103300214560ustar00rootroot00000000000000.highlight .hll { background-color: #ffffcc } .highlight .c { color: #408080; font-style: italic } /* Comment */ .highlight .err { border: 1px solid #FF0000 } /* Error */ .highlight .k { color: #008000; font-weight: bold } /* Keyword */ .highlight .o { color: #666666 } /* Operator */ .highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */ .highlight .cp { color: #BC7A00 } /* Comment.Preproc */ .highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */ .highlight .cs { color: #408080; font-style: italic } /* Comment.Special */ .highlight .gd { color: #A00000 } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #FF0000 } /* Generic.Error */ .highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ .highlight .gi { color: #00A000 } /* Generic.Inserted */ .highlight .go { color: #808080 } /* Generic.Output */ .highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ .highlight .gt { color: #0040D0 } /* Generic.Traceback */ .highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008000 } /* Keyword.Pseudo */ .highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #B00040 } /* Keyword.Type */ .highlight .m { color: #666666 } /* Literal.Number */ .highlight .s { color: #BA2121 } /* Literal.String */ .highlight .na { color: #7D9029 } /* Name.Attribute */ .highlight .nb { color: #008000 } /* Name.Builtin */ .highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */ .highlight .no { color: #880000 } /* Name.Constant */ .highlight .nd { color: #AA22FF } /* Name.Decorator */ .highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */ .highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0000FF } /* Name.Function */ .highlight .nl { color: #A0A000 } /* Name.Label */ .highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ .highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #19177C } /* Name.Variable */ .highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mf { color: #666666 } /* Literal.Number.Float */ .highlight .mh { color: #666666 } /* Literal.Number.Hex */ .highlight .mi { color: #666666 } /* Literal.Number.Integer */ .highlight .mo { color: #666666 } /* Literal.Number.Oct */ .highlight .sb { color: #BA2121 } /* Literal.String.Backtick */ .highlight .sc { color: #BA2121 } /* Literal.String.Char */ .highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ .highlight .s2 { color: #BA2121 } /* Literal.String.Double */ .highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ .highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */ .highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ .highlight .sx { color: #008000 } /* Literal.String.Other */ .highlight .sr { color: #BB6688 } /* Literal.String.Regex */ .highlight .s1 { color: #BA2121 } /* Literal.String.Single */ .highlight .ss { color: #19177C } /* Literal.String.Symbol */ .highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */ .highlight .vc { color: #19177C } /* Name.Variable.Class */ .highlight .vg { color: #19177C } /* Name.Variable.Global */ .highlight .vi { color: #19177C } /* Name.Variable.Instance */ .highlight .il { color: #666666 } /* Literal.Number.Integer.Long */ JavaHamcrest-2.2/docs/distributables.md000066400000000000000000000121251355170103300202160ustar00rootroot00000000000000--- title: Hamcrest Distributables layout: default --- [Java Hamcrest Home](index) # Hamcrest Distributables {:.no_toc} ## Introduction {:.no_toc} This document describes the current and previous versions of the various Hamcrest distributables, and the functionality contained in each of them. The latest version of Hamcrest consists of a single jar file which contains base classes and a library of useful matcher implementations. This is different from older versions. Older versions of Hamcrest consisted of a number of different jars matching the different needs of applications. The change in the jar packaging requires care when upgrading. ## Table of Contents {:.no_toc} * TOC {:toc} ## The Hamcrest Jar All the base classes and standard matcher implementations are contained in a single jar file called `hamcrest-2.1.jar`. ### Using Hamcrest in a Gradle Project Add `"org.hamcrest:hamcrest:2.1"` to the dependencies section of your `build.gradle`, for example: ```gradle apply plugin: 'java' dependencies { testImplementation 'org.hamcrest:hamcrest:2.1' } ``` Note: older versions of Gradle use the `testCompile` configuration instead of the `testImplementation` configuration. ### Using Hamcrest in a Maven Project Add the following to the `` section in your `pom.xml`: ```xml org.hamcrest hamcrest 2.1 test ``` ### Download the Hamcrest Jar You can download the jars directly from Maven Central. You can find the jars by searching Maven Central for groupId `org.hamcrest` using the following link: > [https://search.maven.org/search?q=g:org.hamcrest](https://search.maven.org/search?q=g:org.hamcrest) ## Previous Versions of Hamcrest Prior to version 2.x, Hamcrest was distributed through multiple jars, described below. * **`hamcrest-core.jar`**: This was the core API to be used by third-party framework providers. This includes a foundation set of matcher implementations for common operations. This library was used as a dependency for many third-party libraries, including JUnit 4.x. From Hamcrest version 2.x, all the classes in `hamcrest-core.jar` were moved into `hamcrest.jar`. * **`hamcrest-library.jar`**: The library of Matcher implementations which are based on the core functionality in hamcrest-core.jar. From Hamcrest version 2.x, all the classes in `hamcrest-core.jar` were moved into `hamcrest.jar`. * **`hamcrest-integration.jar`**: Provides integration between Hamcrest and other testing tools, such as jMock and EasyMock. It depends upon `hamcrest-core.jar` and `hamcrest-library.jar`. There are no new releases of this library since version 1.3. * **`hamcrest-generator.jar`**: A tool to allow many Matcher implementations to be combined into a single class with static methods returning the different matchers so users don't have to remember many classes/packages to import. Generates code. This library is only used internally at compile time. It is not necessary for the use of any of the other hamcrest libraries at runtime. There are no new releases of this library since version 1.3. * **`hamcrest-all.jar`**: One jar containing all classes of all the other jars. There are no new releases of this library since version 1.3. Please use the single `hamcrest.jar` instead. ### Upgrading from Hamcrest 1.x Care must be taken when upgrading from Hamcrest 1.3 or earlier. Due to the change in packaging, the version conflict resolution that happens in dependency management tools won't happen automatically. A common example is projects that depend upon JUnit 4. JUnit 4 declares a transitive dependency upon `hamcrest-core-1.3.jar`. Because `hamcrest-core` is not the same artifact as `hamcrest`, it will not be upgraded. To address this issue, Hamcrest 2.1 and later also publish artifacts for `hamcrest-core` and `hamcrest-library`. Although these jars contain no classes, they trigger the version conflict upgrade in the dependency manager, and correctly declare transitive dependencies upon the new `hamcrest` packaging. Users can directly declare a dependency upon these shim jars to force the upgrade. #### Gradle Upgrade Example ```gradle apply plugin: 'java' dependencies { testImplementation 'org.hamcrest:hamcrest:2.1' testImplementation 'org.hamcrest:hamcrest-library:2.1' testImplementation 'junit:junit:4.12' } ``` #### Maven Upgrade Example **Warning**: Maven users should declare a dependency upon `hamcrest-library` **before** other dependencies, otherwise the older version will take precedence. ```xml org.hamcrest hamcrest 2.1 test org.hamcrest hamcrest-library 2.1 test junit junit 4.12 test ``` JavaHamcrest-2.2/docs/images/000077500000000000000000000000001355170103300161205ustar00rootroot00000000000000JavaHamcrest-2.2/docs/images/logo.jpg000066400000000000000000000204061355170103300175640ustar00rootroot00000000000000JFIF,,ExifMM*C  !"$"$C" ?!1AQ"aq2#Bb3$4RSr.!1AQ"2#qBa ?w*chj}2Fǖ[?寑x,%Z5]=aqņbM\R `<řs^yإ1֤?Eo3QUlܦP=l`ErPy?hֺ% KE@v@=>»t ~Y$1SF[)_EX SԒ5꺠O&@ c}Vڧ O0?K-hСboT< ơ9 Ǯwy.;ָDI @m<^*H`F YuwƐ6ULE,P_7uWz=7FkIEK5JS$ikP!g.p2?mO+,L$2)c܎{jUpjClc?UUm:/PSCv[?B;~ƀٍLjbeϙ!Ѐt2G!i@>U:q7Z(%O`>1;-DkWӫ5q?z1TuKM#Rcc^}UjiPF#C'rE%?A]z5'@[ U2JÌOΟh<3F7-SA1߰~Wy&OYK{gQlrG%IjsG7I[;jPAyS7F0T}8;r 3ECPsxMtVJUj(䴬V{DtdqKۅZ߆#zdQ}RW#icNwAlWcZ{x+D_lضZi#t򒼨{kA>_@#M6,u%>ǶIL,Y K!-,PF#Un~FԈ^W˸fkBilITqg/%OsѹT{u >lÜY4RkLtѱJs,kz+PRC$BМ{5Ε8xJ>_%E[ \Eou^pЬ#>XQ 4jܣO v ?} $G>fMx6f`G*q8W )P{rOMa f`}tvߥ22pΐ^tv/L=1q骥B(E|>^j @ҡNױr=$iSGR:rJ>z:~;/r¤zk4LeT2p8^31lȣD })7d;PYATB{KV밗p[L4+;P;E ޞ@?}7#K).d,-:ssƹ[Ni<:r*t]f' }oRt.p´Q;JJ'Io=D+u- ~?4_ y  [9o}5Ld_&fgQ}N+:XlSURZ(ꀆe@c/H8=F+\^׸A PԽ~HБGu\G%l>⌕;nWeI qӝ c ?B/EPDEC厓+ꇒїhۑiΎnߙ`WT${-L&Gi jVUhd8`tFIH_##cTYKYјⅅ~8M7NJ[Tt"$Qs5" wr #}ig:]G L1_uXP9JZA{šc[=ۓvʒpyC®4nOI:vߣTSW,EWq03=sMKMQE2c?_S{LTS<WASwq<u9ime{jXpiz)ɍh |lI8;a_)-5u6잃1aljWO%ޑb*: ?Qy'6ךMEr0UF3MtXf e$B31f9B;7i04H5(mZ_',qmkkP+*N/Yϊ 6=(I*:XjL-qB!\qcWn5@JB;r.B@Ai>E )wM0ܒd)wI?mq67AQ0$uRŔ`O+jὊſlSNC ZcG8<4GbA#KfO(@{kV(@$ ),qx4s:E58fbTH<Yvb$7;n@f(A©$K~2X@~RF:ҏH' Fpn$~GOCci 7-$H,O˒{}s0mCh[M$O1h3ZȞXUu;`.>OLԩ۾/:xoSÅtv)~*h, GK#*gAq>)j!?PRS|/(iYP׶tgӑ}|K.q0B1ԎG=jq䭠IӏMK$'#穀V,;o{PHN;[Vo]E;)S$Z dƧ܌T]7Y ϶ ~j1A%Z44YCC?Q<,B:5+)P׭]SQ"7n0?!-%ʞ1Ml\.jRa g+RkABYc&hY)O %c |ƲQZ$IJ<> oڜǮ_۵QEЭVۓZb[Jك+8}o,$M%MFcEc%t-v] @0f=b8練2Wn J!LW`3Ƙۗ*j: $69F<~Y<`nY+;XIB=Ǿa3λnDʞmAɪSiNObFF[5=~ݭr7jB}7R@:,5Ƴ.cTYNe8|ZmL/_TYd@OS5;{^? O &~RW7mt#8niq<1R4cJ=L~S dW$AZ5 }OZC&QJ *Ya)`qV5;fC{|%V3jW6/Ǒਝh  8o\+?κ)Յě+Z_O9f}4}tbP!*X䫃'Υsd~V,O/taJڅ 8֥[;t36Nc{j9o魈ᕔ`zc/[&7úJmGYhdd`I?RlK5Ў{A&5}Ujh4SF7 ΖoTFEߧ }Z:~e*%Ϲ~z ?}pټ@،Χ_e4a#~CDfݕ% $lu.0==sRWxp&†WyeAM0C+t?@.LSߟ"B+drTʥQr> Tu=^nR+/$sß 诖*k(1JxSVDesc]lMH̴%k4P:HҐ? <́ڴѕd0y86G/_J5zmys_26_ v:"[6U4e3igec:U,䏚LŻAJm*nq=>5MfS)i=4q\*3jk-Y$.bOQ+.ӯaó|73-QjZ˧_97LfS mVq2EmMcaLz~=N`m?$mP+ X?i5ăƨ~ nР$qǫXJۄ1uk8xv̛,@;N;.ΥDN$zPϾZ:TqMWU4Ok,w[ D&H^._u<{d2<ɤ>[IQ͡6yac[]lu=ͅuihA^>&iCqZښx/p~]Kd YU!"2p ~"{:h.^è>[oXpQ rQӁ/S֞S*ͺQa! Gۿ}2[jG Τ,㌟K|E9&uWL_@Q?o;l;ŞqSN>E1@P3hx/&ݚUF§78=<}FXGn/.Q14qJ'#~_lxOq'̋c{eW՞=ȎoTz` j*jҧ c:bDw -OnhCU;ƓϱRO.(p~38E\ƴ&[Y?Z:)~oR~>c'fb1lnYFət~bQl{~I["H%ܖbX"pTauOqP6Di΃59R{6ܦb?l~?Bۻ]a((X~!e p;dco|ۺc[N ԏRG!,!-g{"^LcQT}֡ߔ A vx:SDj#Lgڲ#QM^X:j$t7%MOWe2l?.tj)`o*Y$9G`?jMcl[; i)'Y8LY1mU;a.wRp] ;$.SO,w m3G_[9:K}G.m tMr3:\ =eLspml8$ս%*/B| _[*3=؍Ϸp4bJD+q+߇rzH^mRoPhR:w'J^<ۗz]R}m5,@( Gڥ3ۮpʅ[5A{ȓ' 4w4+;h_|G!k}"D!@yqNdw镱˟31G|fW>2t"Dg b)@v΄\iLfJ+HIsE-_8g@4hl.)JO! '5_"mɼ9thU 3*,KtFgF{0ƥ@ʃ'm9-qyN="6l<~zg upb͢fFݽEB SxC8ϱnzm["8Pd@uPi6tӷBr_k"z ]7?׿FrzЊie]ZHΣ~ԍxaxy)Qw%D@ӤC#^I mFMi#9uz =1QnχrZJx# rRu";+VᥖOO}to~-IWOW|Kuѐ'KrVGiRH\؝N_&ҽ=_▙[dbqKPX^BԫǦG|%CZ8D{Y!BgBb]Nɋ^|Mz%L1n{aF{ȷm8^:W T?.=aS/vz ~^J!~ǾQ[<*Sf~C>ɉGQܷҽTL?uh(˥DpƄPciGwoGn_Pr}GleG2< 5c-zXm[h xQ#\N׎ ڢL|Ψr2[4Cy_p[-iKg:xUbٖP:pumΚϏ)YMU"JavaHamcrest-2.2/docs/index.md000066400000000000000000000015021355170103300163020ustar00rootroot00000000000000--- title: Java Hamcrest layout: default --- # ![Hamcrest Surfer](http://hamcrest.org/images/logo.jpg){:.logo}Java Hamcrest ## Matchers that can be combined to create flexible expressions of intent ### Documentation * [Getting Started](tutorial) * [API Documentation (JavaDoc)](javadoc/) ### Downloads * [Distributables and Dependency Configuration](distributables) * [Source Repository](http://github.com/hamcrest/JavaHamcrest) * [Project License](http://opensource.org/licenses/BSD-3-Clause) * [Extensions and Related Projects](related) ### User Support * [Hamcrest Java Users Mailing List](https://groups.google.com/forum/?fromgroups#!forum/hamcrest-java) * [Hamcrest Developer Mailing List](https://groups.google.com/forum/?fromgroups#!forum/hamcrest-dev) * [Issue Tracker](https://github.com/hamcrest/JavaHamcrest/issues) JavaHamcrest-2.2/docs/related.md000066400000000000000000000053361355170103300166240ustar00rootroot00000000000000--- title: Hamcrest Related Projects layout: default --- [Java Hamcrest Home](index) # Related Projects Here are some projects that provide additional features and matchers * [Awaitility](https://github.com/jayway/awaitility) (a DSL that allows you to express expectations of an asynchronous system in a concise and easy to read manner) * [EZ Testing](https://github.com/EZGames/ez-testing) (contains base classes for defining chainable matchers that have a similar style to AssertJ) * [Hamcrest 1.3 Utility Matchers](https://github.com/NitorCreations/matchers) (Java matchers like CollectionMatchers, MapMatchers, FieldMatcher, SerializableMatcher etc) * [Hamcrest avro](https://github.com/Byhiras/avro-utils) * [Hamcrest Composites](https://github.com/Cornutum/hamcrest-composites) (for comparing complex Java objects with better testability) * [Hamcrest Date](https://github.com/modularit/hamcrest-date) (for comparing dates) * [Hamcrest HAR](https://github.com/roydekleijn/har-assert) (for HTTP archive files) * [Hamcrest Java Extras](https://github.com/sf105/hamcrest-java-extras) (currently only a couple of Json matchers) * [Hamcrest JSON](https://github.com/hertzsprung/hamcrest-json) (for comparing entire JSON documents) * [Hamcrest Path](https://github.com/seinesoftware/hamcrest-path) (for testing path existence and permissions) * [Hamcrest Querydsl](https://github.com/beloglazov/hamcrest-querydsl) (for checking query results: hasResultSize, hasColumnRange, hasColumnMax, hasColumnMin, hasColumnContainingAll, hasColumnContainingAny) * [Hamcrest Text Patterns](http://code.google.com/p/hamcrest-text-patterns/) * [hamcrest-pojo-matcher-generator](https://github.com/yandex-qatools/hamcrest-pojo-matcher-generator) (Annotation processor to generate feature-matchers based on your POJOs) * [http-matchers](https://github.com/valid4j/http-matchers) (Matchers to test your web service via the standard Java API for RESTful Services (JAX-RS)) * [json-path-matchers](https://github.com/jayway/JsonPath/tree/master/json-path-assert) (for evaluating JSON path expressions) * [JsonUnit](https://github.com/lukas-krecan/JsonUnit) (for comparing JSON structures jsonEquals, jsonPartEquals) * [Proboscis](https://github.com/sf105/proboscis) (a tiny java library for polling for a result, originally intended for tested asynchronous systems) * [Shazamcrest](https://github.com/shazam/shazamcrest) (Matchers for beans with custom field matching and nice failure messages) * [Spotify's hamcrest matchers](https://github.com/spotify/java-hamcrest) (Matchers for POJOs, JSON, and some of the types introduced in Java 8) * [valid4j](https://github.com/valid4j/valid4j) (assertion and validation library, i.e supporting design-by-contract style and/or recoverable input validation) JavaHamcrest-2.2/docs/tutorial.md000066400000000000000000000176321355170103300170510ustar00rootroot00000000000000--- title: Hamcrest Tutorial layout: default --- [Java Hamcrest Home](index) # Hamcrest Tutorial ## Introduction Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluble, such as UI validation, or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used. This tutorial shows you how to use Hamcrest for unit testing. When writing tests it is sometimes difficult to get the balance right between overspecifying the test (and making it brittle to changes), and not specifying enough (making the test less valuable since it continues to pass even when the thing being tested is broken). Having a tool that allows you to pick out precisely the aspect under test and describe the values it should have, to a controlled level of precision, helps greatly in writing tests that are "just right". Such tests fail when the behaviour of the aspect under test deviates from the expected behaviour, yet continue to pass when minor, unrelated changes to the behaviour are made. ### My first Hamcrest test We'll start by writing a very simple JUnit 5 test, but instead of using JUnit's `assertEquals` methods, we use Hamcrest's `assertThat` construct and the standard set of matchers, both of which we statically import: ```java import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class BiscuitTest { @Test public void testEquals() { Biscuit theBiscuit = new Biscuit("Ginger"); Biscuit myBiscuit = new Biscuit("Ginger"); assertThat(theBiscuit, equalTo(myBiscuit)); } } ``` The `assertThat` method is a stylized sentence for making a test assertion. In this example, the subject of the assertion is the object biscuit that is the first method parameter. The second method parameter is a matcher for Biscuit objects, here a matcher that checks one object is equal to another using the Object equals method. The test passes since the Biscuit class defines an equals method. If you have more than one assertion in your test you can include an identifier for the tested value in the assertion: ```java assertThat("chocolate chips", theBiscuit.getChocolateChipCount(), equalTo(10)); assertThat("hazelnuts", theBiscuit.getHazelnutCount(), equalTo(3)); ``` ### Other test frameworks Hamcrest has been designed from the outset to integrate with different unit testing frameworks. For example, Hamcrest can be used with JUnit (all versions) and TestNG. (For details have a look at the examples that come with the full Hamcrest distribution.) It is easy enough to migrate to using Hamcrest-style assertions in an existing test suite, since other assertion styles can co-exist with Hamcrest's. Hamcrest can also be used with mock objects frameworks by using adaptors to bridge from the mock objects framework's concept of a matcher to a Hamcrest matcher. For example, JMock 1's constraints are Hamcrest's matchers. Hamcrest provides a JMock 1 adaptor to allow you to use Hamcrest matchers in your JMock 1 tests. JMock 2 doesn't need such an adaptor layer since it is designed to use Hamcrest as its matching library. Hamcrest also provides adaptors for EasyMock 2. Again, see the Hamcrest examples for more details. ### A tour of common matchers Hamcrest comes with a library of useful matchers. Here are some of the most important ones. #### Core `anything` - always matches, useful if you don't care what the object under test is `describedAs` - decorator to adding custom failure description `is` - decorator to improve readability - see "Sugar", below #### Logical `allOf` - matches if all matchers match, short circuits (like Java &&) `anyOf` - matches if any matchers match, short circuits (like Java \|\|) `not` - matches if the wrapped matcher doesn't match and vice versa #### Object `equalTo` - test object equality using Object.equals `hasToString` - test Object.toString `instanceOf`, `isCompatibleType` - test type `notNullValue`, `nullValue` - test for null `sameInstance` - test object identity #### Beans `hasProperty` - test JavaBeans properties #### Collections `array` - test an array's elements against an array of matchers `hasEntry`, `hasKey`, `hasValue` - test a map contains an entry, key or value `hasItem`, `hasItems` - test a collection contains elements `hasItemInArray` - test an array contains an element #### Number `closeTo` - test floating point values are close to a given value `greaterThan`, `greaterThanOrEqualTo`, `lessThan`, `lessThanOrEqualTo` - test ordering #### Text `equalToIgnoringCase` - test string equality ignoring case `equalToIgnoringWhiteSpace` - test string equality ignoring differences in runs of whitespace `containsString`, `endsWith`, `startsWith` - test string matching #### Sugar Hamcrest strives to make your tests as readable as possible. For example, the is matcher is a wrapper that doesn't add any extra behavior to the underlying matcher. The following assertions are all equivalent: ```java assertThat(theBiscuit, equalTo(myBiscuit)); assertThat(theBiscuit, is(equalTo(myBiscuit))); assertThat(theBiscuit, is(myBiscuit)); ``` The last form is allowed since is(T value) is overloaded to return `is(equalTo(value))`. ### Writing custom matchers Hamcrest comes bundled with lots of useful matchers, but you'll probably find that you need to create your own from time to time to fit your testing needs. This commonly occurs when you find a fragment of code that tests the same set of properties over and over again (and in different tests), and you want to bundle the fragment into a single assertion. By writing your own matcher you'll eliminate code duplication and make your tests more readable! Let's write our own matcher for testing if a double value has the value NaN (not a number). This is the test we want to write: ```java @Test public void testSquareRootOfMinusOneIsNotANumber() { assertThat(Math.sqrt(-1), is(notANumber())); } ``` And here's the implementation: ```java package org.hamcrest.examples.tutorial; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class IsNotANumber extends TypeSafeMatcher { @Override public boolean matchesSafely(Double number) { return number.isNaN(); } public void describeTo(Description description) { description.appendText("not a number"); } public static Matcher notANumber() { return new IsNotANumber(); } } ``` The `assertThat` method is a generic method which takes a Matcher parameterized by the type of the subject of the assertion. We are asserting things about Double values, so we know that we need a `Matcher`. For our Matcher implementation it is most convenient to subclass `TypeSafeMatcher`, which does the cast to a Double for us. We need only implement the `matchesSafely` method - which simply checks to see if the Double is NaN - and the `describeTo` method - which is used to produce a failure message when a test fails. Here's an example of how the failure message looks: ```java assertThat(1.0, is(notANumber())); // fails with the message java.lang.AssertionError: Expected: is not a number got : <1.0> ``` The third method in our matcher is a convenience factory method. We statically import this method to use the matcher in our test: ```java import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.examples.tutorial.IsNotANumber.notANumber; public class NumberTest { @Test public void testSquareRootOfMinusOneIsNotANumber() { assertThat(Math.sqrt(-1), is(notANumber())); } } ``` Even though the `notANumber` method creates a new matcher each time it is called, you should not assume this is the only usage pattern for your matcher. Therefore you should make sure your matcher is stateless, so a single instance can be reused between matches. JavaHamcrest-2.2/gradle/000077500000000000000000000000001355170103300151615ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/000077500000000000000000000000001355170103300164575ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/hamcrest-core.gradle000066400000000000000000000006531355170103300223770ustar00rootroot00000000000000dependencies { api project(':hamcrest') } jar { manifest { attributes 'Implementation-Title': project.name, 'Implementation-Vendor': 'hamcrest.org', 'Implementation-Version': version, 'Automatic-Module-Name': 'org.hamcrest.core.deprecated' } } javadoc { title = "Hamcrest Core $version API" options.showFromPackage() options.showFromPrivate() } JavaHamcrest-2.2/hamcrest-core/src/000077500000000000000000000000001355170103300172465ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/000077500000000000000000000000001355170103300201725ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/java/000077500000000000000000000000001355170103300211135ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/java/org/000077500000000000000000000000001355170103300217025ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/java/org/hamcrest/000077500000000000000000000000001355170103300235105ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/java/org/hamcrest/core/000077500000000000000000000000001355170103300244405ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/java/org/hamcrest/core/deprecated/000077500000000000000000000000001355170103300265405ustar00rootroot00000000000000HamcrestCoreIsDeprecated.java000066400000000000000000000003431355170103300341600ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/java/org/hamcrest/core/deprecatedpackage org.hamcrest.core.deprecated; /** * All the classes in hamcrest-core.jar have moved to * hamcrest.jar. Please use that dependency instead. */ @Deprecated class HamcrestCoreIsDeprecated { } JavaHamcrest-2.2/hamcrest-core/src/main/java/org/hamcrest/core/deprecated/package-info.java000066400000000000000000000002661355170103300317330ustar00rootroot00000000000000/** * All classes in hamcrest-core.jar have been migrated to * hamcrest.jar. Please use that dependency instead. */ package org.hamcrest.core.deprecated;JavaHamcrest-2.2/hamcrest-core/src/main/resources/000077500000000000000000000000001355170103300222045ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-core/src/main/resources/hamcrest-core-is-deprecated.txt000066400000000000000000000002301355170103300302030ustar00rootroot00000000000000Hamcrest Core ============= All the classes in hamcrest-core.jar and hamcrest-library.jar has moved into hamcrest.jar. Please update your dependencies.JavaHamcrest-2.2/hamcrest-integration/000077500000000000000000000000001355170103300200525ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-integration/hamcrest-integration.gradle000066400000000000000000000005351355170103300253640ustar00rootroot00000000000000version = '1.3.1-SNAPSHOT' dependencies { api 'org.hamcrest:hamcrest-library:1.3' api 'org.easymock:easymock:2.2' api('jmock:jmock:1.1.0') { transitive = false } testImplementation(group: 'junit', name: 'junit', version: '4.12') { transitive = false } } javadoc.title = "Hamcrest Integration $version API" JavaHamcrest-2.2/hamcrest-integration/src/000077500000000000000000000000001355170103300206415ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-integration/src/main/000077500000000000000000000000001355170103300215655ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-integration/src/main/java/000077500000000000000000000000001355170103300225065ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/000077500000000000000000000000001355170103300232755ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/hamcrest/000077500000000000000000000000001355170103300251035ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java000066400000000000000000000005111355170103300312270ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.integration.EasyMock2Adapter; import org.hamcrest.core.IsEqual; /** * * @author Joe Walnes */ public class EasyMock2Matchers { public static String equalTo(String string) { EasyMock2Adapter.adapt(IsEqual.equalTo(string)); return null; } } JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java000066400000000000000000000004611355170103300305220ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.integration.JMock1Adapter; import org.hamcrest.core.IsEqual; import org.jmock.core.Constraint; public class JMock1Matchers { public static Constraint equalTo(String string) { return JMock1Adapter.adapt(IsEqual.equalTo(string)); } } JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java000066400000000000000000000006441355170103300321230ustar00rootroot00000000000000package org.hamcrest; /** * Integration method for use with Java's assert keyword. * Example: *
 * assert that("Foo", startsWith("f"));
 * 
* * @author Neil Dunn */ public class JavaLangMatcherAssert { private JavaLangMatcherAssert() {}; public static boolean that(T argument, Matcher matcher) { return matcher.matches(argument); } } JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/hamcrest/integration/000077500000000000000000000000001355170103300274265ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.java000066400000000000000000000024271355170103300333740ustar00rootroot00000000000000package org.hamcrest.integration; import org.easymock.IArgumentMatcher; import org.easymock.EasyMock; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; /** * An adapter allowing a Hamcrest {@link org.hamcrest.Matcher} * to act as an EasyMock {@link org.easymock.IArgumentMatcher}. * * @author Joe Walnes */ public class EasyMock2Adapter implements IArgumentMatcher { /** * Convenience factory method that will adapt a * Hamcrest {@link org.hamcrest.Matcher} to act as an * EasyMock {@link org.easymock.IArgumentMatcher} and * report it to EasyMock so it can be kept track of. */ public static IArgumentMatcher adapt(Matcher matcher) { EasyMock2Adapter easyMock2Matcher = new EasyMock2Adapter(matcher); EasyMock.reportMatcher(easyMock2Matcher); return easyMock2Matcher; } private final Matcher hamcrestMatcher; public EasyMock2Adapter(Matcher matcher) { this.hamcrestMatcher = matcher; } @Override public boolean matches(Object argument) { return hamcrestMatcher.matches(argument); } @Override public void appendTo(StringBuffer buffer) { hamcrestMatcher.describeTo(new StringDescription(buffer)); } } JavaHamcrest-2.2/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java000066400000000000000000000022131355170103300326540ustar00rootroot00000000000000package org.hamcrest.integration; import org.jmock.core.Constraint; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; /** * An adapter allowing a Hamcrest {@link org.hamcrest.Matcher} * to act as an jMock1 {@link org.jmock.core.Constraint}. * Note, this is not necessary for jMock2 as it supports Hamcrest * out of the box. * * @author Joe Walnes */ public class JMock1Adapter implements Constraint { /** * Convenience factory method that will adapt a * Hamcrest {@link org.hamcrest.Matcher} to act as an * jMock {@link org.jmock.core.Constraint}. */ public static Constraint adapt(Matcher matcher) { return new JMock1Adapter(matcher); } private final Matcher hamcrestMatcher; public JMock1Adapter(Matcher matcher) { this.hamcrestMatcher = matcher; } @Override public boolean eval(Object o) { return hamcrestMatcher.matches(o); } @Override public StringBuffer describeTo(StringBuffer buffer) { hamcrestMatcher.describeTo(new StringDescription(buffer)); return buffer; } } JavaHamcrest-2.2/hamcrest-library/000077500000000000000000000000001355170103300171735ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/hamcrest-library.gradle000066400000000000000000000006301355170103300236220ustar00rootroot00000000000000dependencies { api project(':hamcrest-core') } jar { manifest { attributes 'Implementation-Title': project.name, 'Implementation-Vendor': 'hamcrest.org', 'Implementation-Version': version, 'Automatic-Module-Name': 'org.hamcrest.library.deprecated' } } javadoc { title = "Hamcrest Library $version API" options.showFromPackage() } JavaHamcrest-2.2/hamcrest-library/src/000077500000000000000000000000001355170103300177625ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/000077500000000000000000000000001355170103300207065ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/java/000077500000000000000000000000001355170103300216275ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/java/org/000077500000000000000000000000001355170103300224165ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/java/org/hamcrest/000077500000000000000000000000001355170103300242245ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/java/org/hamcrest/library/000077500000000000000000000000001355170103300256705ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/java/org/hamcrest/library/deprecated/000077500000000000000000000000001355170103300277705ustar00rootroot00000000000000HamcrestLibraryIsDeprecated.java000066400000000000000000000003541355170103300361260ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/java/org/hamcrest/library/deprecatedpackage org.hamcrest.library.deprecated; /** * All the classes in hamcrest-library.jar have moved to * hamcrest.jar. Please use that dependency instead. */ @Deprecated class HamcrestLibraryIsDeprecated { } JavaHamcrest-2.2/hamcrest-library/src/main/java/org/hamcrest/library/deprecated/package-info.java000066400000000000000000000002741355170103300331620ustar00rootroot00000000000000/** * All classes in hamcrest-library.jar have been migrated to * hamcrest.jar. Please use that dependency instead. */ package org.hamcrest.library.deprecated;JavaHamcrest-2.2/hamcrest-library/src/main/resources/000077500000000000000000000000001355170103300227205ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest-library/src/main/resources/hamcrest-library-is-deprecated.txt000066400000000000000000000002361355170103300314410ustar00rootroot00000000000000Hamcrest Library ================ All the classes in hamcrest-core.jar and hamcrest-library.jar has moved into hamcrest.jar. Please update your dependencies.JavaHamcrest-2.2/hamcrest/000077500000000000000000000000001355170103300155315ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/hamcrest.gradle000066400000000000000000000013621355170103300205210ustar00rootroot00000000000000apply plugin: 'osgi' version = rootProject.version dependencies { testImplementation(group: 'junit', name: 'junit', version: '4.12') { transitive = false } } jar { manifest { attributes 'Implementation-Title': project.name, 'Implementation-Vendor': 'hamcrest.org', 'Implementation-Version': version, 'Automatic-Module-Name': 'org.hamcrest' instruction 'Import-Package', '''javax.xml.namespace; resolution:=optional, javax.xml.xpath; resolution:=optional, org.w3c.dom; resolution:=optional, *''' } } javadoc.title = "Hamcrest $version API" JavaHamcrest-2.2/hamcrest/src/000077500000000000000000000000001355170103300163205ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/000077500000000000000000000000001355170103300172445ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/000077500000000000000000000000001355170103300201655ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/000077500000000000000000000000001355170103300207545ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/000077500000000000000000000000001355170103300225625ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/BaseDescription.java000066400000000000000000000106451355170103300265110ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.internal.ArrayIterator; import org.hamcrest.internal.SelfDescribingValueIterator; import java.util.Arrays; import java.util.Iterator; import static java.lang.String.valueOf; /** * A {@link Description} that is stored as a string. */ public abstract class BaseDescription implements Description { @Override public Description appendText(String text) { append(text); return this; } @Override public Description appendDescriptionOf(SelfDescribing value) { value.describeTo(this); return this; } @Override public Description appendValue(Object value) { if (value == null) { append("null"); } else if (value instanceof String) { toJavaSyntax((String) value); } else if (value instanceof Character) { append('"'); toJavaSyntax((Character) value); append('"'); } else if (value instanceof Byte) { append('<'); append(descriptionOf(value)); append("b>"); } else if (value instanceof Short) { append('<'); append(descriptionOf(value)); append("s>"); } else if (value instanceof Long) { append('<'); append(descriptionOf(value)); append("L>"); } else if (value instanceof Float) { append('<'); append(descriptionOf(value)); append("F>"); } else if (value.getClass().isArray()) { appendValueList("[",", ","]", new ArrayIterator(value)); } else { append('<'); append(descriptionOf(value)); append('>'); } return this; } private String descriptionOf(Object value) { try { return valueOf(value); } catch (Exception e) { return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); } } @SafeVarargs @Override public final Description appendValueList(String start, String separator, String end, T... values) { return appendValueList(start, separator, end, Arrays.asList(values)); } @Override public Description appendValueList(String start, String separator, String end, Iterable values) { return appendValueList(start, separator, end, values.iterator()); } private Description appendValueList(String start, String separator, String end, Iterator values) { return appendList(start, separator, end, new SelfDescribingValueIterator<>(values)); } @Override public Description appendList(String start, String separator, String end, Iterable values) { return appendList(start, separator, end, values.iterator()); } private Description appendList(String start, String separator, String end, Iterator i) { boolean separate = false; append(start); while (i.hasNext()) { if (separate) append(separator); appendDescriptionOf(i.next()); separate = true; } append(end); return this; } /** * Append the String str to the description. * The default implementation passes every character to {@link #append(char)}. * Override in subclasses to provide an efficient implementation. */ protected void append(String str) { for (int i = 0; i < str.length(); i++) { append(str.charAt(i)); } } /** * Append the char c to the description. */ protected abstract void append(char c); private void toJavaSyntax(String unformatted) { append('"'); for (int i = 0; i < unformatted.length(); i++) { toJavaSyntax(unformatted.charAt(i)); } append('"'); } private void toJavaSyntax(char ch) { switch (ch) { case '"': append("\\\""); break; case '\n': append("\\n"); break; case '\r': append("\\r"); break; case '\t': append("\\t"); break; case '\\': append("\\\\"); break; default: append(ch); } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/BaseMatcher.java000066400000000000000000000022311355170103300256010ustar00rootroot00000000000000package org.hamcrest; /** * BaseClass for all Matcher implementations. * * @see Matcher */ public abstract class BaseMatcher implements Matcher { /** * @see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_() */ @Override @Deprecated public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() { // See Matcher interface for an explanation of this method. } @Override public void describeMismatch(Object item, Description description) { description.appendText("was ").appendValue(item); } @Override public String toString() { return StringDescription.toString(this); } /** * Useful null-check method. Writes a mismatch description if the actual object is null * @param actual the object to check * @param mismatch where to write the mismatch description, if any * @return false iff the actual object is null */ protected static boolean isNotNull(Object actual, Description mismatch) { if (actual == null) { mismatch.appendText("was null"); return false; } return true; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/Condition.java000066400000000000000000000044461355170103300253630ustar00rootroot00000000000000package org.hamcrest; /** * A Condition implements part of a multi-step match. We sometimes need to write matchers * that have a sequence of steps, where each step depends on the result of the previous * step and we can stop processing as soon as a step fails. These classes provide * infrastructure for writing such a sequence. * * Based on https://github.com/npryce/maybe-java * @author Steve Freeman 2012 http://www.hamcrest.com */ public abstract class Condition { public static final NotMatched NOT_MATCHED = new NotMatched(); public interface Step { Condition apply(I value, Description mismatch); } private Condition() { } public abstract boolean matching(Matcher match, String message); public abstract Condition and(Step mapping); public final boolean matching(Matcher match) { return matching(match, ""); } public final Condition then(Step mapping) { return and(mapping); } @SuppressWarnings("unchecked") public static Condition notMatched() { return (Condition) NOT_MATCHED; } public static Condition matched(final T theValue, final Description mismatch) { return new Matched(theValue, mismatch); } private static final class Matched extends Condition { private final T theValue; private final Description mismatch; private Matched(T theValue, Description mismatch) { this.theValue = theValue; this.mismatch = mismatch; } @Override public boolean matching(Matcher matcher, String message) { if (matcher.matches(theValue)) { return true; } mismatch.appendText(message); matcher.describeMismatch(theValue, mismatch); return false; } @Override public Condition and(Step next) { return next.apply(theValue, mismatch); } } private static final class NotMatched extends Condition { @Override public boolean matching(Matcher match, String message) { return false; } @Override public Condition and(Step mapping) { return notMatched(); } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/CoreMatchers.java000066400000000000000000000430361355170103300260120ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.core.IsIterableContaining; @SuppressWarnings("UnusedDeclaration") public class CoreMatchers { /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static org.hamcrest.Matcher allOf(java.lang.Iterable> matchers) { return org.hamcrest.core.AllOf.allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @SafeVarargs public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher... matchers) { return org.hamcrest.core.AllOf.allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static org.hamcrest.core.AnyOf anyOf(java.lang.Iterable> matchers) { return org.hamcrest.core.AnyOf.anyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @SafeVarargs public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher... matchers) { return org.hamcrest.core.AnyOf.anyOf(matchers); } /** * Creates a matcher that matches when both of the specified matchers match the examined object. * For example: *
assertThat("fab", both(containsString("a")).and(containsString("b")))
*/ public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcher both(org.hamcrest.Matcher matcher) { return org.hamcrest.core.CombinableMatcher.both(matcher); } /** * Creates a matcher that matches when either of the specified matchers match the examined object. * For example: *
assertThat("fan", either(containsString("a")).or(containsString("b")))
*/ public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher either(org.hamcrest.Matcher matcher) { return org.hamcrest.core.CombinableMatcher.either(matcher); } /** * Wraps an existing matcher, overriding its description with that specified. All other functions are * delegated to the decorated matcher, including its mismatch description. * For example: *
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
* * @param description * the new description for the wrapped matcher * @param matcher * the matcher to wrap * @param values * optional values to insert into the tokenised description */ public static org.hamcrest.Matcher describedAs(java.lang.String description, org.hamcrest.Matcher matcher, java.lang.Object... values) { return org.hamcrest.core.DescribedAs.describedAs(description, matcher, values); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields items that are all matched by the specified * itemMatcher. * For example: *
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to every item provided by the examined {@link Iterable} */ public static org.hamcrest.Matcher> everyItem(org.hamcrest.Matcher itemMatcher) { return org.hamcrest.core.Every.everyItem(itemMatcher); } /** * Decorates another Matcher, retaining its behaviour, but allowing tests * to be slightly more expressive. * For example: *
assertThat(cheese, is(equalTo(smelly)))
* instead of: *
assertThat(cheese, equalTo(smelly))
*/ public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) { return org.hamcrest.core.Is.is(matcher); } /** * A shortcut to the frequently used is(equalTo(x)). * For example: *
assertThat(cheese, is(smelly))
* instead of: *
assertThat(cheese, is(equalTo(smelly)))
*/ public static org.hamcrest.Matcher is(T value) { return org.hamcrest.core.Is.is(value); } /** * A shortcut to the frequently used is(instanceOf(SomeClass.class)). * For example: *
assertThat(cheese, isA(Cheddar.class))
* instead of: *
assertThat(cheese, is(instanceOf(Cheddar.class)))
*/ public static org.hamcrest.Matcher isA(java.lang.Class type) { return org.hamcrest.core.Is.isA(type); } /** * Creates a matcher that always matches, regardless of the examined object. */ public static org.hamcrest.Matcher anything() { return org.hamcrest.core.IsAnything.anything(); } /** * Creates a matcher that always matches, regardless of the examined object, but describes * itself with the specified {@link String}. * * @param description * a meaningful {@link String} used when describing itself */ public static org.hamcrest.Matcher anything(java.lang.String description) { return org.hamcrest.core.IsAnything.anything(description); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is matched by the specified * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ public static org.hamcrest.Matcher> hasItem(org.hamcrest.Matcher itemMatcher) { return IsIterableContaining.hasItem(itemMatcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is equal to the specified * item. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
* * @param item * the item to compare against the items provided by the examined {@link Iterable} */ public static org.hamcrest.Matcher> hasItem(T item) { return IsIterableContaining.hasItem(item); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is matched by the corresponding * matcher from the specified itemMatchers. Whilst matching, each traversal of * the examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
* * @param itemMatchers * the matchers to apply to items provided by the examined {@link Iterable} */ @SafeVarargs public static org.hamcrest.Matcher> hasItems(org.hamcrest.Matcher... itemMatchers) { return IsIterableContaining.hasItems(itemMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is equal to the corresponding * item from the specified items. Whilst matching, each traversal of the * examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
* * @param items * the items to compare against the items provided by the examined {@link Iterable} */ @SafeVarargs public static org.hamcrest.Matcher> hasItems(T... items) { return IsIterableContaining.hasItems(items); } /** * Creates a matcher that matches when the examined object is logically equal to the specified * operand, as determined by calling the {@link java.lang.Object#equals} method on * the examined object. * *

If the specified operand is null then the created matcher will only match if * the examined object's equals method returns true when passed a * null (which would be a violation of the equals contract), unless the * examined object itself is null, in which case the matcher will return a positive * match.

* *

The created matcher provides a special behaviour when examining Arrays, whereby * it will match if both the operand and the examined object are arrays of the same length and * contain items that are equal to each other (according to the above rules) in the same * indexes.

* For example: *
   * assertThat("foo", equalTo("foo"));
   * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
   * 
*/ public static org.hamcrest.Matcher equalTo(T operand) { return org.hamcrest.core.IsEqual.equalTo(operand); } /** * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being * compared to be of the same static type. */ public static org.hamcrest.Matcher equalToObject(java.lang.Object operand) { return org.hamcrest.core.IsEqual.equalToObject(operand); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher forces a relationship between specified type and the examined object, and should be * used when it is necessary to make generics conform, for example in the JMock clause * with(any(Thing.class))

* For example: *
assertThat(new Canoe(), instanceOf(Canoe.class));
*/ public static org.hamcrest.Matcher any(java.lang.Class type) { return org.hamcrest.core.IsInstanceOf.any(type); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher assumes no relationship between specified type and the examined object.

* For example: *
assertThat(new Canoe(), instanceOf(Paddlable.class));
*/ public static org.hamcrest.Matcher instanceOf(java.lang.Class type) { return org.hamcrest.core.IsInstanceOf.instanceOf(type); } /** * Creates a matcher that wraps an existing matcher, but inverts the logic by which * it will match. * For example: *
assertThat(cheese, is(not(equalTo(smelly))))
* * @param matcher * the matcher whose sense should be inverted */ public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) { return org.hamcrest.core.IsNot.not(matcher); } /** * A shortcut to the frequently used not(equalTo(x)). * For example: *
assertThat(cheese, is(not(smelly)))
* instead of: *
assertThat(cheese, is(not(equalTo(smelly))))
* * @param value * the value that any examined object should not equal */ public static org.hamcrest.Matcher not(T value) { return org.hamcrest.core.IsNot.not(value); } /** * A shortcut to the frequently used not(nullValue()). * For example: *
assertThat(cheese, is(notNullValue()))
* instead of: *
assertThat(cheese, is(not(nullValue())))
*/ public static org.hamcrest.Matcher notNullValue() { return org.hamcrest.core.IsNull.notNullValue(); } /** * A shortcut to the frequently used not(nullValue(X.class)). Accepts a * single dummy argument to facilitate type inference.. * For example: *
assertThat(cheese, is(notNullValue(X.class)))
* instead of: *
assertThat(cheese, is(not(nullValue(X.class))))
* * @param type * dummy parameter used to infer the generic type of the returned matcher */ public static org.hamcrest.Matcher notNullValue(java.lang.Class type) { return org.hamcrest.core.IsNull.notNullValue(type); } /** * Creates a matcher that matches if examined object is null. * For example: *
assertThat(cheese, is(nullValue())
*/ public static org.hamcrest.Matcher nullValue() { return org.hamcrest.core.IsNull.nullValue(); } /** * Creates a matcher that matches if examined object is null. Accepts a * single dummy argument to facilitate type inference. * For example: *
assertThat(cheese, is(nullValue(Cheese.class))
* * @param type * dummy parameter used to infer the generic type of the returned matcher */ public static org.hamcrest.Matcher nullValue(java.lang.Class type) { return org.hamcrest.core.IsNull.nullValue(type); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ public static org.hamcrest.Matcher sameInstance(T target) { return org.hamcrest.core.IsSame.sameInstance(target); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ public static org.hamcrest.Matcher theInstance(T target) { return org.hamcrest.core.IsSame.theInstance(target); } /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere. * For example: *
assertThat("myStringOfNote", containsString("ring"))
* * @param substring * the substring that the returned matcher will expect to find within any examined string */ public static org.hamcrest.Matcher containsString(java.lang.String substring) { return org.hamcrest.core.StringContains.containsString(substring); } /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere, ignoring case. * For example: *
assertThat("myStringOfNote", containsString("ring"))
* * @param substring * the substring that the returned matcher will expect to find within any examined string */ public static org.hamcrest.Matcher containsStringIgnoringCase(java.lang.String substring) { return org.hamcrest.core.StringContains.containsStringIgnoringCase(substring); } /** *

* Creates a matcher that matches if the examined {@link String} starts with the specified * {@link String}. *

* For example: *
assertThat("myStringOfNote", startsWith("my"))
* * @param prefix * the substring that the returned matcher will expect at the start of any examined string */ public static org.hamcrest.Matcher startsWith(java.lang.String prefix) { return org.hamcrest.core.StringStartsWith.startsWith(prefix); } /** *

* Creates a matcher that matches if the examined {@link String} starts with the specified * {@link String}, ignoring case *

* For example: *
assertThat("myStringOfNote", startsWith("my"))
* * @param prefix * the substring that the returned matcher will expect at the start of any examined string */ public static org.hamcrest.Matcher startsWithIgnoringCase(java.lang.String prefix) { return org.hamcrest.core.StringStartsWith.startsWithIgnoringCase(prefix); } /** * Creates a matcher that matches if the examined {@link String} ends with the specified * {@link String}. * For example: *
assertThat("myStringOfNote", endsWith("Note"))
* * @param suffix * the substring that the returned matcher will expect at the end of any examined string */ public static org.hamcrest.Matcher endsWith(java.lang.String suffix) { return org.hamcrest.core.StringEndsWith.endsWith(suffix); } /** * Creates a matcher that matches if the examined {@link String} ends with the specified * {@link String}, ignoring case. * For example: *
assertThat("myStringOfNote", endsWith("Note"))
* * @param suffix * the substring that the returned matcher will expect at the end of any examined string */ public static org.hamcrest.Matcher endsWithIgnoringCase(java.lang.String suffix) { return org.hamcrest.core.StringEndsWith.endsWithIgnoringCase(suffix); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java000066400000000000000000000022121355170103300262000ustar00rootroot00000000000000package org.hamcrest; /** * Utility class for writing one off matchers. * For example: *
 * Matcher<String> aNonEmptyString = new CustomMatcher<String>("a non empty string") {
 *   public boolean matches(Object object) {
 *     return ((object instanceof String) && !((String) object).isEmpty();
 *   }
 * };
 * 
*

* This class is designed for scenarios where an anonymous inner class * matcher makes sense. It should not be used by API designers implementing * matchers. * * @author Neil Dunn * @see CustomTypeSafeMatcher for a type safe variant of this class that you probably * want to use. * @param The type of object being matched. */ public abstract class CustomMatcher extends BaseMatcher { private final String fixedDescription; public CustomMatcher(String description) { if (description == null) { throw new IllegalArgumentException("Description should be non null!"); } this.fixedDescription = description; } @Override public final void describeTo(Description description) { description.appendText(fixedDescription); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java000066400000000000000000000023531355170103300276470ustar00rootroot00000000000000package org.hamcrest; /** * Utility class for writing one off matchers. * For example: *

 * Matcher<String> aNonEmptyString = new CustomTypeSafeMatcher<String>("a non empty string") {
 *   public boolean matchesSafely(String string) {
 *     return !string.isEmpty();
 *   }
 *   public void describeMismatchSafely(String string, Description mismatchDescription) {
 *     mismatchDescription.appendText("was empty");
 *   }
 * };
 * 
* This is a variant of {@link CustomMatcher} that first type checks * the argument being matched. By the time {@link TypeSafeMatcher#matchesSafely} is * is called the argument is guaranteed to be non-null and of the correct * type. * * @author Neil Dunn * @param The type of object being matched */ public abstract class CustomTypeSafeMatcher extends TypeSafeMatcher { private final String fixedDescription; public CustomTypeSafeMatcher(String description) { if (description == null) { throw new IllegalArgumentException("Description must be non null!"); } this.fixedDescription = description; } @Override public final void describeTo(Description description) { description.appendText(fixedDescription); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/Description.java000066400000000000000000000045151355170103300257150ustar00rootroot00000000000000package org.hamcrest; /** * A description of a Matcher. A Matcher will describe itself to a description * which can later be used for reporting. * * @see Matcher#describeTo(Description) */ public interface Description { /** * A description that consumes input but does nothing. */ static final Description NONE = new NullDescription(); /** * Appends some plain text to the description. */ Description appendText(String text); /** * Appends the description of a {@link SelfDescribing} value to this description. */ Description appendDescriptionOf(SelfDescribing value); /** * Appends an arbitrary value to the description. */ Description appendValue(Object value); /** * Appends a list of values to the description. */ Description appendValueList(String start, String separator, String end, T... values); /** * Appends a list of values to the description. */ Description appendValueList(String start, String separator, String end, Iterable values); /** * Appends a list of {@link org.hamcrest.SelfDescribing} objects * to the description. */ Description appendList(String start, String separator, String end, Iterable values); public static final class NullDescription implements Description { @Override public Description appendDescriptionOf(SelfDescribing value) { return this; } @Override public Description appendList(String start, String separator, String end, Iterable values) { return this; } @Override public Description appendText(String text) { return this; } @Override public Description appendValue(Object value) { return this; } @Override public Description appendValueList(String start, String separator, String end, T... values) { return this; } @Override public Description appendValueList(String start, String separator, String end, Iterable values) { return this; } @Override public String toString() { return ""; } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/DiagnosingMatcher.java000066400000000000000000000007621355170103300270200ustar00rootroot00000000000000package org.hamcrest; /** * TODO(ngd): Document. * * @param */ public abstract class DiagnosingMatcher extends BaseMatcher { @Override public final boolean matches(Object item) { return matches(item, Description.NONE); } @Override public final void describeMismatch(Object item, Description mismatchDescription) { matches(item, mismatchDescription); } protected abstract boolean matches(Object item, Description mismatchDescription); } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/FeatureMatcher.java000066400000000000000000000035201355170103300263240ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.internal.ReflectiveTypeFinder; /** * Supporting class for matching a feature of an object. Implement featureValueOf() * in a subclass to pull out the feature to be matched against. * * @param The type of the object to be matched * @param The type of the feature to be matched */ public abstract class FeatureMatcher extends TypeSafeDiagnosingMatcher { private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("featureValueOf", 1, 0); private final Matcher subMatcher; private final String featureDescription; private final String featureName; /** * Constructor * @param subMatcher The matcher to apply to the feature * @param featureDescription Descriptive text to use in describeTo * @param featureName Identifying text for mismatch message */ public FeatureMatcher(Matcher subMatcher, String featureDescription, String featureName) { super(TYPE_FINDER); this.subMatcher = subMatcher; this.featureDescription = featureDescription; this.featureName = featureName; } /** * Implement this to extract the interesting feature. * @param actual the target object * @return the feature to be matched */ protected abstract U featureValueOf(T actual); @Override protected boolean matchesSafely(T actual, Description mismatch) { final U featureValue = featureValueOf(actual); if (!subMatcher.matches(featureValue)) { mismatch.appendText(featureName).appendText(" "); subMatcher.describeMismatch(featureValue, mismatch); return false; } return true; } @Override public final void describeTo(Description description) { description.appendText(featureDescription).appendText(" ") .appendDescriptionOf(subMatcher); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/Matcher.java000066400000000000000000000047051355170103300250160ustar00rootroot00000000000000package org.hamcrest; /** *

* A matcher over acceptable values. * A matcher is able to describe itself to give feedback when it fails. *

*

* Matcher implementations should NOT directly implement this interface. * Instead, extend the {@link BaseMatcher} abstract class, * which will ensure that the Matcher API can grow to support * new features and remain compatible with all Matcher implementations. *

*

* When using Hamcrest, there is no guarantee as to how often matches() or * describeMismatch() will be called, so the objects passed as * actual arguments should not change when referenced. If you're testing a * stream, a good practice is to collect the contents of the stream before matching. *

*

* N.B. Well designed matchers should be immutable. *

* * @see BaseMatcher */ public interface Matcher extends SelfDescribing { /** * Evaluates the matcher for argument item. * * This method matches against Object, instead of the generic type T. This is * because the caller of the Matcher does not know at runtime what the type is * (because of type erasure with Java generics). It is down to the implementations * to check the correct type. * * @param actual the object against which the matcher is evaluated. * @return true if item matches, otherwise false. * * @see BaseMatcher */ boolean matches(Object actual); /** * Generate a description of why the matcher has not accepted the item. * The description will be part of a larger description of why a matching * failed, so it should be concise. * This method assumes that matches(item) is false, but * will not check this. * * @param actual The item that the Matcher has rejected. * @param mismatchDescription * The description to be built or appended to. */ void describeMismatch(Object actual, Description mismatchDescription); /** * This method simply acts a friendly reminder not to implement Matcher directly and * instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore * compile errors . * * @see Matcher for reasons why. * @see BaseMatcher * @deprecated to make */ @Deprecated void _dont_implement_Matcher___instead_extend_BaseMatcher_(); } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/MatcherAssert.java000066400000000000000000000017571355170103300262040ustar00rootroot00000000000000package org.hamcrest; public class MatcherAssert { public static void assertThat(T actual, Matcher matcher) { assertThat("", actual, matcher); } public static void assertThat(String reason, T actual, Matcher matcher) { if (!matcher.matches(actual)) { Description description = new StringDescription(); description.appendText(reason) .appendText(System.lineSeparator()) .appendText("Expected: ") .appendDescriptionOf(matcher) .appendText(System.lineSeparator()) .appendText(" but: "); matcher.describeMismatch(actual, description); throw new AssertionError(description.toString()); } } public static void assertThat(String reason, boolean assertion) { if (!assertion) { throw new AssertionError(reason); } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/Matchers.java000066400000000000000000002150771355170103300252070ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.collection.ArrayMatching; import org.hamcrest.core.IsIterableContaining; import org.hamcrest.core.StringRegularExpression; import org.hamcrest.text.IsEqualCompressingWhiteSpace; import java.util.regex.Pattern; @SuppressWarnings({"unused", "WeakerAccess"}) public class Matchers { /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static org.hamcrest.Matcher allOf(java.lang.Iterable> matchers) { return org.hamcrest.core.AllOf.allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @SafeVarargs public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher... matchers) { return org.hamcrest.core.AllOf.allOf(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second) { return org.hamcrest.core.AllOf.allOf(first, second); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third) { return org.hamcrest.core.AllOf.allOf(first, second, third); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth) { return org.hamcrest.core.AllOf.allOf(first, second, third, fourth); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth) { return org.hamcrest.core.AllOf.allOf(first, second, third, fourth, fifth); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth, org.hamcrest.Matcher sixth) { return org.hamcrest.core.AllOf.allOf(first, second, third, fourth, fifth, sixth); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static org.hamcrest.core.AnyOf anyOf(java.lang.Iterable> matchers) { return org.hamcrest.core.AnyOf.anyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @SafeVarargs public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher... matchers) { return org.hamcrest.core.AnyOf.anyOf(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second) { return org.hamcrest.core.AnyOf.anyOf(first, second); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third) { return org.hamcrest.core.AnyOf.anyOf(first, second, third); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth) { return org.hamcrest.core.AnyOf.anyOf(first, second, third, fourth); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth) { return org.hamcrest.core.AnyOf.anyOf(first, second, third, fourth, fifth); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth, org.hamcrest.Matcher sixth) { return org.hamcrest.core.AnyOf.anyOf(first, second, third, fourth, fifth, sixth); } /** * Creates a matcher that matches when both of the specified matchers match the examined object. * For example: *
assertThat("fab", both(containsString("a")).and(containsString("b")))
*/ public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcher both(org.hamcrest.Matcher matcher) { return org.hamcrest.core.CombinableMatcher.both(matcher); } /** * Creates a matcher that matches when either of the specified matchers match the examined object. * For example: *
assertThat("fan", either(containsString("a")).or(containsString("b")))
*/ public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher either(org.hamcrest.Matcher matcher) { return org.hamcrest.core.CombinableMatcher.either(matcher); } /** * Wraps an existing matcher, overriding its description with that specified. All other functions are * delegated to the decorated matcher, including its mismatch description. * For example: *
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
* * @param description * the new description for the wrapped matcher * @param matcher * the matcher to wrap * @param values * optional values to insert into the tokenized description */ public static org.hamcrest.Matcher describedAs(java.lang.String description, org.hamcrest.Matcher matcher, java.lang.Object... values) { return org.hamcrest.core.DescribedAs.describedAs(description, matcher, values); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields items that are all matched by the specified * itemMatcher. * For example: *
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to every item provided by the examined {@link Iterable} */ public static org.hamcrest.Matcher> everyItem(org.hamcrest.Matcher itemMatcher) { return org.hamcrest.core.Every.everyItem(itemMatcher); } /** * Decorates another Matcher, retaining its behaviour, but allowing tests * to be slightly more expressive. * For example: *
assertThat(cheese, is(equalTo(smelly)))
* instead of: *
assertThat(cheese, equalTo(smelly))
*/ public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) { return org.hamcrest.core.Is.is(matcher); } /** * A shortcut to the frequently used is(equalTo(x)). * For example: *
assertThat(cheese, is(smelly))
* instead of: *
assertThat(cheese, is(equalTo(smelly)))
*/ public static org.hamcrest.Matcher is(T value) { return org.hamcrest.core.Is.is(value); } /** * A shortcut to the frequently used is(instanceOf(SomeClass.class)). * For example: *
assertThat(cheese, isA(Cheddar.class))
* instead of: *
assertThat(cheese, is(instanceOf(Cheddar.class)))
*/ public static org.hamcrest.Matcher isA(java.lang.Class type) { return org.hamcrest.core.Is.isA(type); } /** * Creates a matcher that always matches, regardless of the examined object. */ public static org.hamcrest.Matcher anything() { return org.hamcrest.core.IsAnything.anything(); } /** * Creates a matcher that always matches, regardless of the examined object, but describes * itself with the specified {@link String}. * * @param description * a meaningful {@link String} used when describing itself */ public static org.hamcrest.Matcher anything(java.lang.String description) { return org.hamcrest.core.IsAnything.anything(description); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is matched by the specified * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ public static org.hamcrest.Matcher> hasItem(org.hamcrest.Matcher itemMatcher) { return IsIterableContaining.hasItem(itemMatcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is equal to the specified * item. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
* * @param item * the item to compare against the items provided by the examined {@link Iterable} */ public static org.hamcrest.Matcher> hasItem(T item) { return IsIterableContaining.hasItem(item); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is matched by the corresponding * matcher from the specified itemMatchers. Whilst matching, each traversal of * the examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
* * @param itemMatchers * the matchers to apply to items provided by the examined {@link Iterable} */ @SafeVarargs public static org.hamcrest.Matcher> hasItems(org.hamcrest.Matcher... itemMatchers) { return IsIterableContaining.hasItems(itemMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is equal to the corresponding * item from the specified items. Whilst matching, each traversal of the * examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
* * @param items * the items to compare against the items provided by the examined {@link Iterable} */ @SafeVarargs public static org.hamcrest.Matcher> hasItems(T... items) { return IsIterableContaining.hasItems(items); } /** * Creates a matcher that matches when the examined object is logically equal to the specified * operand, as determined by calling the {@link java.lang.Object#equals} method on * the examined object. * *

If the specified operand is null then the created matcher will only match if * the examined object's equals method returns true when passed a * null (which would be a violation of the equals contract), unless the * examined object itself is null, in which case the matcher will return a positive * match.

* *

The created matcher provides a special behaviour when examining Arrays, whereby * it will match if both the operand and the examined object are arrays of the same length and * contain items that are equal to each other (according to the above rules) in the same * indexes.

* For example: *
   * assertThat("foo", equalTo("foo"));
   * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
   * 
*/ public static org.hamcrest.Matcher equalTo(T operand) { return org.hamcrest.core.IsEqual.equalTo(operand); } /** * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being * compared to be of the same static type. */ public static org.hamcrest.Matcher equalToObject(java.lang.Object operand) { return org.hamcrest.core.IsEqual.equalToObject(operand); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher forces a relationship between specified type and the examined object, and should be * used when it is necessary to make generics conform, for example in the JMock clause * with(any(Thing.class))

* For example: *
assertThat(new Canoe(), instanceOf(Canoe.class));
*/ public static org.hamcrest.Matcher any(java.lang.Class type) { return org.hamcrest.core.IsInstanceOf.any(type); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher assumes no relationship between specified type and the examined object.

* For example: *
assertThat(new Canoe(), instanceOf(Paddlable.class));
*/ public static org.hamcrest.Matcher instanceOf(java.lang.Class type) { return org.hamcrest.core.IsInstanceOf.instanceOf(type); } /** * Creates a matcher that wraps an existing matcher, but inverts the logic by which * it will match. * For example: *
assertThat(cheese, is(not(equalTo(smelly))))
* * @param matcher * the matcher whose sense should be inverted */ public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) { return org.hamcrest.core.IsNot.not(matcher); } /** * A shortcut to the frequently used not(equalTo(x)). * For example: *
assertThat(cheese, is(not(smelly)))
* instead of: *
assertThat(cheese, is(not(equalTo(smelly))))
* * @param value * the value that any examined object should not equal */ public static org.hamcrest.Matcher not(T value) { return org.hamcrest.core.IsNot.not(value); } /** * A shortcut to the frequently used not(nullValue()). * For example: *
assertThat(cheese, is(notNullValue()))
* instead of: *
assertThat(cheese, is(not(nullValue())))
*/ public static org.hamcrest.Matcher notNullValue() { return org.hamcrest.core.IsNull.notNullValue(); } /** * A shortcut to the frequently used not(nullValue(X.class)). Accepts a * single dummy argument to facilitate type inference.. * For example: *
assertThat(cheese, is(notNullValue(X.class)))
* instead of: *
assertThat(cheese, is(not(nullValue(X.class))))
* * @param type * dummy parameter used to infer the generic type of the returned matcher */ public static org.hamcrest.Matcher notNullValue(java.lang.Class type) { return org.hamcrest.core.IsNull.notNullValue(type); } /** * Creates a matcher that matches if examined object is null. * For example: *
assertThat(cheese, is(nullValue())
*/ public static org.hamcrest.Matcher nullValue() { return org.hamcrest.core.IsNull.nullValue(); } /** * Creates a matcher that matches if examined object is null. Accepts a * single dummy argument to facilitate type inference. * For example: *
assertThat(cheese, is(nullValue(Cheese.class))
* * @param type * dummy parameter used to infer the generic type of the returned matcher */ public static org.hamcrest.Matcher nullValue(java.lang.Class type) { return org.hamcrest.core.IsNull.nullValue(type); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ public static org.hamcrest.Matcher sameInstance(T target) { return org.hamcrest.core.IsSame.sameInstance(target); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ public static org.hamcrest.Matcher theInstance(T target) { return org.hamcrest.core.IsSame.theInstance(target); } /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere. * For example: *
assertThat("myStringOfNote", containsString("ring"))
* * @param substring * the substring that the returned matcher will expect to find within any examined string */ public static Matcher containsString(java.lang.String substring) { return org.hamcrest.core.StringContains.containsString(substring); } /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere, ignoring case. * For example: *
assertThat("myStringOfNote", containsStringIgnoringCase("Ring"))
* * @param substring * the substring that the returned matcher will expect to find within any examined string */ public static Matcher containsStringIgnoringCase(java.lang.String substring) { return org.hamcrest.core.StringContains.containsStringIgnoringCase(substring); } /** *

* Creates a matcher that matches if the examined {@link String} starts with the specified * {@link String}. *

* For example: *
assertThat("myStringOfNote", startsWith("my"))
* * @param prefix * the substring that the returned matcher will expect at the start of any examined string */ public static Matcher startsWith(java.lang.String prefix) { return org.hamcrest.core.StringStartsWith.startsWith(prefix); } /** *

* Creates a matcher that matches if the examined {@link String} starts with the specified * {@link String}, ignoring case *

* For example: *
assertThat("myStringOfNote", startsWithIgnoringCase("My"))
* * @param prefix * the substring that the returned matcher will expect at the start of any examined string */ public static Matcher startsWithIgnoringCase(java.lang.String prefix) { return org.hamcrest.core.StringStartsWith.startsWithIgnoringCase(prefix); } /** * Creates a matcher that matches if the examined {@link String} ends with the specified * {@link String}. * For example: *
assertThat("myStringOfNote", endsWith("Note"))
* * @param suffix * the substring that the returned matcher will expect at the end of any examined string */ public static Matcher endsWith(java.lang.String suffix) { return org.hamcrest.core.StringEndsWith.endsWith(suffix); } /** * Creates a matcher that matches if the examined {@link String} ends with the specified * {@link String}, ignoring case. * For example: *
assertThat("myStringOfNote", endsWithIgnoringCase("note"))
* * @param suffix * the substring that the returned matcher will expect at the end of any examined string */ public static Matcher endsWithIgnoringCase(java.lang.String suffix) { return org.hamcrest.core.StringEndsWith.endsWithIgnoringCase(suffix); } /** * Validate a string with a {@link java.util.regex.Pattern}. * *
   * assertThat("abc", matchesRegex(Pattern.compile("ˆ[a-z]$"));
   * 
* * @param pattern * the pattern to be used. * @return The matcher. */ public static Matcher matchesRegex(Pattern pattern) { return StringRegularExpression.matchesRegex(pattern); } /** * Validate a string with a regex. * *
   * assertThat("abc", matchesRegex("ˆ[a-z]+$"));
   * 
* * @param regex * The regex to be used for the validation. * @return The matcher. */ public static Matcher matchesRegex(String regex) { return StringRegularExpression.matchesRegex(Pattern.compile(regex)); } /** * Creates a matcher that matches arrays whose elements are satisfied by the specified matchers. Matches * positively only if the number of matchers specified is equal to the length of the examined array and * each matcher[i] is satisfied by array[i]. * For example: *
assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))
* * @param elementMatchers * the matchers that the elements of examined arrays should satisfy */ @SafeVarargs public static org.hamcrest.collection.IsArray array(org.hamcrest.Matcher... elementMatchers) { return org.hamcrest.collection.IsArray.array(elementMatchers); } /** * Creates a matcher for arrays that matches when the examined array contains at least one item * that is matched by the specified elementMatcher. Whilst matching, the traversal * of the examined array will stop as soon as a matching element is found. * For example: *
assertThat(new String[] {"foo", "bar"}, hasItemInArray(startsWith("ba")))
* * @param elementMatcher * the matcher to apply to elements in examined arrays */ public static org.hamcrest.Matcher hasItemInArray(org.hamcrest.Matcher elementMatcher) { return ArrayMatching.hasItemInArray(elementMatcher); } /** * A shortcut to the frequently used hasItemInArray(equalTo(x)). * For example: *
assertThat(hasItemInArray(x))
* instead of: *
assertThat(hasItemInArray(equalTo(x)))
* * @param element * the element that should be present in examined arrays */ public static org.hamcrest.Matcher hasItemInArray(T element) { return ArrayMatching.hasItemInArray(element); } /** * Creates a matcher for arrays that matches when each item in the examined array is * logically equal to the corresponding item in the specified items. For a positive match, * the examined array must be of the same length as the number of specified items. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining("foo", "bar"))
* * @param items * the items that must equal the items within an examined array */ @SafeVarargs public static org.hamcrest.Matcher arrayContaining(E... items) { return ArrayMatching.arrayContaining(items); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified matchers. For a positive match, the examined array * must be of the same length as the number of specified matchers. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining(equalTo("foo"), equalTo("bar")))
* * @param itemMatchers * the matchers that must be satisfied by the items in the examined array */ @SafeVarargs public static org.hamcrest.Matcher arrayContaining(org.hamcrest.Matcher... itemMatchers) { return ArrayMatching.arrayContaining(itemMatchers); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified list of matchers. For a positive match, the examined array * must be of the same length as the specified list of matchers. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining(Arrays.asList(equalTo("foo"), equalTo("bar"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item in an examined array */ public static org.hamcrest.Matcher arrayContaining(java.util.List> itemMatchers) { return ArrayMatching.arrayContaining(itemMatchers); } /** *

* Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified matchers. * For a positive match, the examined array must be of the same length as the number of * specified matchers. *

*

* N.B. each of the specified matchers will only be used once during a given examination, so be * careful when specifying matchers that may be satisfied by more than one entry in an examined * array. *

*

* For example: *

*
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(equalTo("bar"), equalTo("foo")))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an entry in an examined array */ @SafeVarargs public static org.hamcrest.Matcher arrayContainingInAnyOrder(org.hamcrest.Matcher... itemMatchers) { return ArrayMatching.arrayContainingInAnyOrder(itemMatchers); } /** *

* Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified collection of matchers. * For a positive match, the examined array must be of the same length as the specified collection * of matchers. *

*

* N.B. each matcher in the specified collection will only be used once during a given * examination, so be careful when specifying matchers that may be satisfied by more than * one entry in an examined array. *

*

* For example: *

*
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined array */ public static org.hamcrest.Matcher arrayContainingInAnyOrder(java.util.Collection> itemMatchers) { return ArrayMatching.arrayContainingInAnyOrder(itemMatchers); } /** *

Creates an order agnostic matcher for arrays that matches when each item in the * examined array is logically equal to one item anywhere in the specified items. * For a positive match, the examined array must be of the same length as the number of * specified items. *

*

N.B. each of the specified items will only be used once during a given examination, so be * careful when specifying items that may be equal to more than one entry in an examined * array. *

*

* For example: *

*
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder("bar", "foo"))
* * @param items * the items that must equal the entries of an examined array, in any order */ @SafeVarargs public static org.hamcrest.Matcher arrayContainingInAnyOrder(E... items) { return ArrayMatching.arrayContainingInAnyOrder(items); } /** * Creates a matcher for arrays that matches when the length of the array * satisfies the specified matcher. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the length of an examined array */ public static org.hamcrest.Matcher arrayWithSize(org.hamcrest.Matcher sizeMatcher) { return org.hamcrest.collection.IsArrayWithSize.arrayWithSize(sizeMatcher); } /** * Creates a matcher for arrays that matches when the length of the array * equals the specified size. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(2))
* * @param size * the length that an examined array must have for a positive match */ public static org.hamcrest.Matcher arrayWithSize(int size) { return org.hamcrest.collection.IsArrayWithSize.arrayWithSize(size); } /** * Creates a matcher for arrays that matches when the length of the array * is zero. * For example: *
assertThat(new String[0], emptyArray())
*/ public static org.hamcrest.Matcher emptyArray() { return org.hamcrest.collection.IsArrayWithSize.emptyArray(); } /** * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns * a value that satisfies the specified matcher. * For example: *
assertThat(myMap, is(aMapWithSize(equalTo(2))))
* * @param sizeMatcher * a matcher for the size of an examined {@link java.util.Map} */ public static org.hamcrest.Matcher> aMapWithSize(org.hamcrest.Matcher sizeMatcher) { return org.hamcrest.collection.IsMapWithSize.aMapWithSize(sizeMatcher); } /** * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns * a value equal to the specified size. * For example: *
assertThat(myMap, is(aMapWithSize(2)))
* * @param size * the expected size of an examined {@link java.util.Map} */ public static org.hamcrest.Matcher> aMapWithSize(int size) { return org.hamcrest.collection.IsMapWithSize.aMapWithSize(size); } /** * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns * zero. * For example: *
assertThat(myMap, is(anEmptyMap()))
*/ public static org.hamcrest.Matcher> anEmptyMap() { return org.hamcrest.collection.IsMapWithSize.anEmptyMap(); } /** * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns * a value that satisfies the specified matcher. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the size of an examined {@link java.util.Collection} */ public static org.hamcrest.Matcher> hasSize(org.hamcrest.Matcher sizeMatcher) { return org.hamcrest.collection.IsCollectionWithSize.hasSize(sizeMatcher); } /** * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns * a value equal to the specified size. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasSize(2))
* * @param size * the expected size of an examined {@link java.util.Collection} */ public static org.hamcrest.Matcher> hasSize(int size) { return org.hamcrest.collection.IsCollectionWithSize.hasSize(size); } /** * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty * method returns true. * For example: *
assertThat(new ArrayList<String>(), is(empty()))
*/ public static org.hamcrest.Matcher> empty() { return org.hamcrest.collection.IsEmptyCollection.empty(); } /** * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty * method returns true. * For example: *
assertThat(new ArrayList<String>(), is(emptyCollectionOf(String.class)))
* * @param unusedToForceReturnType * the type of the collection's content */ public static org.hamcrest.Matcher> emptyCollectionOf(java.lang.Class unusedToForceReturnType) { return org.hamcrest.collection.IsEmptyCollection.emptyCollectionOf(unusedToForceReturnType); } /** * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. * For example: *
assertThat(new ArrayList<String>(), is(emptyIterable()))
*/ public static org.hamcrest.Matcher> emptyIterable() { return org.hamcrest.collection.IsEmptyIterable.emptyIterable(); } /** * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. * For example: *
assertThat(new ArrayList<String>(), is(emptyIterableOf(String.class)))
* * @param unusedToForceReturnType * the type of the iterable's content */ public static org.hamcrest.Matcher> emptyIterableOf(java.lang.Class unusedToForceReturnType) { return org.hamcrest.collection.IsEmptyIterable.emptyIterableOf(unusedToForceReturnType); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each logically equal to the * corresponding item in the specified items. For a positive match, the examined iterable * must be of the same length as the number of specified items. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains("foo", "bar"))
* * @param items * the items that must equal the items provided by an examined {@link Iterable} */ @SafeVarargs public static org.hamcrest.Matcher> contains(E... items) { return org.hamcrest.collection.IsIterableContainingInOrder.contains(items); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a single item that satisfies the specified matcher. * For a positive match, the examined iterable must only yield one item. * For example: *
assertThat(Arrays.asList("foo"), contains(equalTo("foo")))
* * @param itemMatcher * the matcher that must be satisfied by the single item provided by an * examined {@link Iterable} */ public static org.hamcrest.Matcher> contains(org.hamcrest.Matcher itemMatcher) { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatcher); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each satisfying the corresponding * matcher in the specified matchers. For a positive match, the examined iterable * must be of the same length as the number of specified matchers. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains(equalTo("foo"), equalTo("bar")))
* * @param itemMatchers * the matchers that must be satisfied by the items provided by an examined {@link Iterable} */ @SafeVarargs public static org.hamcrest.Matcher> contains(org.hamcrest.Matcher... itemMatchers) { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each satisfying the corresponding * matcher in the specified list of matchers. For a positive match, the examined iterable * must be of the same length as the specified list of matchers. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item provided by * an examined {@link Iterable} */ public static org.hamcrest.Matcher> contains(java.util.List> itemMatchers) { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatchers); } /** *

* Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere * in the specified matchers. For a positive match, the examined iterable must be of the same * length as the number of specified matchers. *

*

* N.B. each of the specified matchers will only be used once during a given examination, so be * careful when specifying matchers that may be satisfied by more than one entry in an examined * iterable. *

*

* For example: *

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(equalTo("bar"), equalTo("foo")))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ @SafeVarargs public static org.hamcrest.Matcher> containsInAnyOrder(org.hamcrest.Matcher... itemMatchers) { return org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder(itemMatchers); } /** *

* Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each logically equal to one item * anywhere in the specified items. For a positive match, the examined iterable * must be of the same length as the number of specified items. *

*

* N.B. each of the specified items will only be used once during a given examination, so be * careful when specifying items that may be equal to more than one entry in an examined * iterable. *

*

* For example: *

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder("bar", "foo"))
* * @param items * the items that must equal the items provided by an examined {@link Iterable} in any order */ @SafeVarargs public static org.hamcrest.Matcher> containsInAnyOrder(T... items) { return org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder(items); } /** *

* Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere * in the specified collection of matchers. For a positive match, the examined iterable * must be of the same length as the specified collection of matchers. *

*

* N.B. each matcher in the specified collection will only be used once during a given * examination, so be careful when specifying matchers that may be satisfied by more than * one entry in an examined iterable. *

*

For example:

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ public static org.hamcrest.Matcher> containsInAnyOrder(java.util.Collection> itemMatchers) { return org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder(itemMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, that contains items logically equal to the * corresponding item in the specified items, in the same relative order * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder("b", "d"))
* * @param items * the items that must be contained within items provided by an examined {@link Iterable} in the same relative order */ @SafeVarargs public static org.hamcrest.Matcher> containsInRelativeOrder(E... items) { return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(items); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, that each satisfying the corresponding * matcher in the specified matchers, in the same relative order. * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))
* * @param itemMatchers * the matchers that must be satisfied by the items provided by an examined {@link Iterable} in the same relative order */ @SafeVarargs public static org.hamcrest.Matcher> containsInRelativeOrder(org.hamcrest.Matcher... itemMatchers) { return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(itemMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, that contains items satisfying the corresponding * matcher in the specified list of matchers, in the same relative order. * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), contains(Arrays.asList(equalTo("b"), equalTo("d"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the items provided by * an examined {@link Iterable} in the same relative order */ public static org.hamcrest.Matcher> containsInRelativeOrder(java.util.List> itemMatchers) { return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(itemMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields an item count that satisfies the specified * matcher. * For example: *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the number of items that should be yielded by an examined {@link Iterable} */ public static org.hamcrest.Matcher> iterableWithSize(org.hamcrest.Matcher sizeMatcher) { return org.hamcrest.collection.IsIterableWithSize.iterableWithSize(sizeMatcher); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields an item count that is equal to the specified * size argument. * For example: *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(2))
* * @param size * the number of items that should be yielded by an examined {@link Iterable} */ public static org.hamcrest.Matcher> iterableWithSize(int size) { return org.hamcrest.collection.IsIterableWithSize.iterableWithSize(size); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one entry whose key satisfies the specified keyMatcher and whose * value satisfies the specified valueMatcher. * For example: *
assertThat(myMap, hasEntry(equalTo("bar"), equalTo("foo")))
* * @param keyMatcher * the key matcher that, in combination with the valueMatcher, must be satisfied by at least one entry * @param valueMatcher * the value matcher that, in combination with the keyMatcher, must be satisfied by at least one entry */ public static org.hamcrest.Matcher> hasEntry(org.hamcrest.Matcher keyMatcher, org.hamcrest.Matcher valueMatcher) { return org.hamcrest.collection.IsMapContaining.hasEntry(keyMatcher, valueMatcher); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one entry whose key equals the specified key and whose value equals the * specified value. * For example: *
assertThat(myMap, hasEntry("bar", "foo"))
* * @param key * the key that, in combination with the value, must be describe at least one entry * @param value * the value that, in combination with the key, must be describe at least one entry */ public static org.hamcrest.Matcher> hasEntry(K key, V value) { return org.hamcrest.collection.IsMapContaining.hasEntry(key, value); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one key that satisfies the specified matcher. * For example: *
assertThat(myMap, hasKey(equalTo("bar")))
* * @param keyMatcher * the matcher that must be satisfied by at least one key */ public static org.hamcrest.Matcher> hasKey(org.hamcrest.Matcher keyMatcher) { return org.hamcrest.collection.IsMapContaining.hasKey(keyMatcher); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one key that is equal to the specified key. * For example: *
assertThat(myMap, hasKey("bar"))
* * @param key * the key that satisfying maps must contain */ public static org.hamcrest.Matcher> hasKey(K key) { return org.hamcrest.collection.IsMapContaining.hasKey(key); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one value that satisfies the specified valueMatcher. * For example: *
assertThat(myMap, hasValue(equalTo("foo")))
* * @param valueMatcher * the matcher that must be satisfied by at least one value */ public static org.hamcrest.Matcher> hasValue(org.hamcrest.Matcher valueMatcher) { return org.hamcrest.collection.IsMapContaining.hasValue(valueMatcher); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one value that is equal to the specified value. * For example: *
assertThat(myMap, hasValue("foo"))
* * @param value * the value that satisfying maps must contain */ public static org.hamcrest.Matcher> hasValue(V value) { return org.hamcrest.collection.IsMapContaining.hasValue(value); } /** * Creates a matcher that matches when the examined object is found within the * specified collection. * For example: *
assertThat("foo", is(in(Arrays.asList("bar", "foo"))))
* * @param collection * the collection in which matching items must be found */ public static org.hamcrest.Matcher in(java.util.Collection collection) { return org.hamcrest.collection.IsIn.in(collection); } /** * Creates a matcher that matches when the examined object is found within the * specified array. * For example: *
assertThat("foo", is(in(new String[]{"bar", "foo"})))
* * @param elements * the array in which matching items must be found */ public static org.hamcrest.Matcher in(T[] elements) { return org.hamcrest.collection.IsIn.in(elements); } /** * Creates a matcher that matches when the examined object is found within the * specified collection. * For example: *
assertThat("foo", isIn(Arrays.asList("bar", "foo")))
* * @deprecated use is(in(...)) instead * @param collection * the collection in which matching items must be found */ @SuppressWarnings("deprecation") public static org.hamcrest.Matcher isIn(java.util.Collection collection) { return org.hamcrest.collection.IsIn.isIn(collection); } /** * Creates a matcher that matches when the examined object is found within the * specified array. * For example: *
assertThat("foo", isIn(new String[]{"bar", "foo"}))
* * @deprecated use is(in(...)) instead * @param elements * the array in which matching items must be found */ @SuppressWarnings("deprecation") public static org.hamcrest.Matcher isIn(T[] elements) { return org.hamcrest.collection.IsIn.isIn(elements); } /** * Creates a matcher that matches when the examined object is equal to one of the * specified elements. * For example: *
assertThat("foo", isOneOf("bar", "foo"))
* * @deprecated use is(oneOf(...)) instead * @param elements * the elements amongst which matching items will be found */ @SuppressWarnings("deprecation") @SafeVarargs public static org.hamcrest.Matcher isOneOf(T... elements) { return org.hamcrest.collection.IsIn.isOneOf(elements); } /** * Creates a matcher that matches when the examined object is equal to one of the * specified elements. * For example: *
assertThat("foo", is(oneOf("bar", "foo")))
* * @param elements * the elements amongst which matching items will be found */ @SafeVarargs public static org.hamcrest.Matcher oneOf(T... elements) { return org.hamcrest.collection.IsIn.oneOf(elements); } /** * Creates a matcher of {@link Double}s that matches when an examined double is equal * to the specified operand, within a range of +/- error. * For example: *
assertThat(1.03, is(closeTo(1.0, 0.03)))
* * @param operand * the expected value of matching doubles * @param error * the delta (+/-) within which matches will be allowed */ public static org.hamcrest.Matcher closeTo(double operand, double error) { return org.hamcrest.number.IsCloseTo.closeTo(operand, error); } /** * Creates a matcher of {@link Double}s that matches when an examined double is not a number. * For example: *
assertThat(Double.NaN, is(notANumber()))
*/ public static org.hamcrest.Matcher notANumber() { return org.hamcrest.number.IsNaN.notANumber(); } /** * Creates a matcher of {@link java.math.BigDecimal}s that matches when an examined BigDecimal is equal * to the specified operand, within a range of +/- error. The comparison for equality * is done by BigDecimals {@link java.math.BigDecimal#compareTo(java.math.BigDecimal)} method. * For example: *
assertThat(new BigDecimal("1.03"), is(closeTo(new BigDecimal("1.0"), new BigDecimal("0.03"))))
* * @param operand * the expected value of matching BigDecimals * @param error * the delta (+/-) within which matches will be allowed */ public static org.hamcrest.Matcher closeTo(java.math.BigDecimal operand, java.math.BigDecimal error) { return org.hamcrest.number.BigDecimalCloseTo.closeTo(operand, error); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * equal to the specified value, as reported by the compareTo method of the * examined object. * For example: *
assertThat(1, comparesEqualTo(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return zero */ public static > org.hamcrest.Matcher comparesEqualTo(T value) { return org.hamcrest.number.OrderingComparison.comparesEqualTo(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * greater than the specified value, as reported by the compareTo method of the * examined object. * For example: *
assertThat(2, greaterThan(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return greater * than zero */ public static > org.hamcrest.Matcher greaterThan(T value) { return org.hamcrest.number.OrderingComparison.greaterThan(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * greater than or equal to the specified value, as reported by the compareTo method * of the examined object. * For example: *
assertThat(1, greaterThanOrEqualTo(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return greater * than or equal to zero */ public static > org.hamcrest.Matcher greaterThanOrEqualTo(T value) { return org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * less than the specified value, as reported by the compareTo method of the * examined object. * For example: *
assertThat(1, lessThan(2))
* * @param value the value which, when passed to the compareTo method of the examined object, should return less * than zero */ public static > org.hamcrest.Matcher lessThan(T value) { return org.hamcrest.number.OrderingComparison.lessThan(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * less than or equal to the specified value, as reported by the compareTo method * of the examined object. * For example: *
assertThat(1, lessThanOrEqualTo(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return less * than or equal to zero */ public static > org.hamcrest.Matcher lessThanOrEqualTo(T value) { return org.hamcrest.number.OrderingComparison.lessThanOrEqualTo(value); } /** * Creates a matcher of {@link String} that matches when the examined string is equal to * the specified expectedString, ignoring case. * For example: *
assertThat("Foo", equalToIgnoringCase("FOO"))
* * @param expectedString * the expected value of matched strings */ public static Matcher equalToIgnoringCase(java.lang.String expectedString) { return org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase(expectedString); } /** * @deprecated {@link #equalToCompressingWhiteSpace(String)} * @param expectedString * the expected value of matched strings */ public static Matcher equalToIgnoringWhiteSpace(java.lang.String expectedString) { return equalToCompressingWhiteSpace(expectedString); } /** * Creates a matcher of {@link String} that matches when the examined string is equal to * the specified expectedString, when whitespace differences are (mostly) ignored. To be * exact, the following whitespace rules are applied: *
    *
  • all leading and trailing whitespace of both the expectedString and the examined string are ignored
  • *
  • any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
  • *
* For example: *
assertThat("   my\tfoo  bar ", equalToIgnoringWhiteSpace(" my  foo bar"))
* * @param expectedString * the expected value of matched strings */ public static Matcher equalToCompressingWhiteSpace(java.lang.String expectedString) { return IsEqualCompressingWhiteSpace.equalToCompressingWhiteSpace(expectedString); } /** * Creates a matcher of {@link String} that matches when the examined string is null, or * has zero length. * For example: *
assertThat(((String)null), is(emptyOrNullString()))
*/ public static Matcher emptyOrNullString() { return org.hamcrest.text.IsEmptyString.emptyOrNullString(); } /** * Creates a matcher of {@link String} that matches when the examined string has zero length. * For example: *
assertThat("", is(emptyString()))
*/ public static Matcher emptyString() { return org.hamcrest.text.IsEmptyString.emptyString(); } /** * Creates a matcher of {@link String} that matches when the examined string is null, or * has zero length. * For example: *
assertThat(((String)null), isEmptyOrNullString())
* * @deprecated use is(emptyOrNullString()) instead */ @SuppressWarnings("deprecation") public static Matcher isEmptyOrNullString() { return org.hamcrest.text.IsEmptyString.isEmptyOrNullString(); } /** * Creates a matcher of {@link String} that matches when the examined string has zero length. * For example: *
assertThat("", isEmptyString())
* * @deprecated use is(emptyString()) instead */ @SuppressWarnings("deprecation") public static Matcher isEmptyString() { return org.hamcrest.text.IsEmptyString.isEmptyString(); } /** * Creates a matcher of {@link String} that matches when the examined string is null, or * contains zero or more whitespace characters and nothing else. * For example: *
assertThat(((String)null), is(blankOrNullString()))
*/ public static Matcher blankOrNullString() { return org.hamcrest.text.IsBlankString.blankOrNullString(); } /** * Creates a matcher of {@link String} that matches when the examined string contains * zero or more whitespace characters and nothing else. * For example: *
assertThat("  ", is(blankString()))
*/ public static Matcher blankString() { return org.hamcrest.text.IsBlankString.blankString(); } /** * Creates a matcher of {@link java.lang.String} that matches when the examined string * exactly matches the given {@link java.util.regex.Pattern}. */ public static Matcher matchesPattern(java.util.regex.Pattern pattern) { return org.hamcrest.text.MatchesPattern.matchesPattern(pattern); } /** * Creates a matcher of {@link java.lang.String} that matches when the examined string * exactly matches the given regular expression, treated as a {@link java.util.regex.Pattern}. */ public static Matcher matchesPattern(java.lang.String regex) { return org.hamcrest.text.MatchesPattern.matchesPattern(regex); } /** * Creates a matcher of {@link String} that matches when the examined string contains all of * the specified substrings, considering the order of their appearance. * For example: *
assertThat("myfoobarbaz", stringContainsInOrder(Arrays.asList("bar", "foo")))
* fails as "foo" occurs before "bar" in the string "myfoobarbaz" * * @param substrings * the substrings that must be contained within matching strings */ public static Matcher stringContainsInOrder(java.lang.Iterable substrings) { return org.hamcrest.text.StringContainsInOrder.stringContainsInOrder(substrings); } /** * Creates a matcher of {@link String} that matches when the examined string contains all of * the specified substrings, considering the order of their appearance. * For example: *
assertThat("myfoobarbaz", stringContainsInOrder("bar", "foo"))
* fails as "foo" occurs before "bar" in the string "myfoobarbaz" * * @param substrings * the substrings that must be contained within matching strings */ public static Matcher stringContainsInOrder(java.lang.String... substrings) { return org.hamcrest.text.StringContainsInOrder.stringContainsInOrder(substrings); } /** * Creates a matcher of {@link CharSequence} that matches when a char sequence has the length * of the specified argument. * For example: * *
     * assertThat("text", length(4))
     * 
* * @param length the expected length of the string */ public static Matcher hasLength(int length) { return org.hamcrest.text.CharSequenceLength.hasLength(length); } /** * Creates a matcher that matches any examined object whose toString method * returns a value that satisfies the specified matcher. * For example: *
assertThat(true, hasToString(equalTo("TRUE")))
* * @param toStringMatcher * the matcher used to verify the toString result */ public static org.hamcrest.Matcher hasToString(org.hamcrest.Matcher toStringMatcher) { return org.hamcrest.object.HasToString.hasToString(toStringMatcher); } /** * Creates a matcher that matches any examined object whose toString method * returns a value equalTo the specified string. * For example: *
assertThat(true, hasToString("TRUE"))
* * @param expectedToString * the expected toString result */ public static org.hamcrest.Matcher hasToString(java.lang.String expectedToString) { return org.hamcrest.object.HasToString.hasToString(expectedToString); } /** * Creates a matcher of {@link Class} that matches when the specified baseType is * assignable from the examined class. * For example: *
assertThat(Integer.class, typeCompatibleWith(Number.class))
* * @param baseType * the base class to examine classes against */ public static org.hamcrest.Matcher> typeCompatibleWith(java.lang.Class baseType) { return org.hamcrest.object.IsCompatibleType.typeCompatibleWith(baseType); } /** * Creates a matcher of {@link java.util.EventObject} that matches any object * derived from eventClass announced by source. * For example: *
assertThat(myEvent, is(eventFrom(PropertyChangeEvent.class, myBean)))
* * @param eventClass * the class of the event to match on * @param source * the source of the event */ public static org.hamcrest.Matcher eventFrom(java.lang.Class eventClass, java.lang.Object source) { return org.hamcrest.object.IsEventFrom.eventFrom(eventClass, source); } /** * Creates a matcher of {@link java.util.EventObject} that matches any EventObject * announced by source. * For example: *
assertThat(myEvent, is(eventFrom(myBean)))
* * @param source * the source of the event */ public static org.hamcrest.Matcher eventFrom(java.lang.Object source) { return org.hamcrest.object.IsEventFrom.eventFrom(source); } /** * Creates a matcher that matches when the examined object has a JavaBean property * with the specified name. * For example: *
assertThat(myBean, hasProperty("foo"))
* * @param propertyName * the name of the JavaBean property that examined beans should possess */ public static org.hamcrest.Matcher hasProperty(java.lang.String propertyName) { return org.hamcrest.beans.HasProperty.hasProperty(propertyName); } /** * Creates a matcher that matches when the examined object has a JavaBean property * with the specified name whose value satisfies the specified matcher. * For example: *
assertThat(myBean, hasProperty("foo", equalTo("bar"))
* * @param propertyName * the name of the JavaBean property that examined beans should possess * @param valueMatcher * a matcher for the value of the specified property of the examined bean */ public static org.hamcrest.Matcher hasProperty(java.lang.String propertyName, org.hamcrest.Matcher valueMatcher) { return org.hamcrest.beans.HasPropertyWithValue.hasProperty(propertyName, valueMatcher); } /** * Creates a matcher that matches when the examined object has values for all of * its JavaBean properties that are equal to the corresponding values of the * specified bean. If any properties are marked as ignored, they will be dropped from * both the expected and actual bean. Note that the ignored properties use JavaBean * display names, for example
age
rather than method names such as
getAge
. * For example: *
assertThat(myBean, samePropertyValuesAs(myExpectedBean))
*
assertThat(myBean, samePropertyValuesAs(myExpectedBean), "age", "height")
* * @param expectedBean * the bean against which examined beans are compared * @param ignoredProperties * do not check any of these named properties. */ public static Matcher samePropertyValuesAs(B expectedBean, String... ignoredProperties) { return org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs(expectedBean, ignoredProperties); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the * specified xPath that satisfies the specified valueMatcher. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", equalTo("Cheddar")))
* * @param xPath * the target xpath * @param valueMatcher * matcher for the value at the specified xpath */ public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, Matcher valueMatcher) { return org.hamcrest.xml.HasXPath.hasXPath(xPath, valueMatcher); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the * specified xPath, within the specified namespaceContext, that satisfies * the specified valueMatcher. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs, equalTo("Cheddar")))
* * @param xPath * the target xpath * @param namespaceContext * the namespace for matching nodes * @param valueMatcher * matcher for the value at the specified xpath */ public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, javax.xml.namespace.NamespaceContext namespaceContext, Matcher valueMatcher) { return org.hamcrest.xml.HasXPath.hasXPath(xPath, namespaceContext, valueMatcher); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node * at the specified xPath, with any content. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese"))
* * @param xPath * the target xpath */ public static org.hamcrest.Matcher hasXPath(java.lang.String xPath) { return org.hamcrest.xml.HasXPath.hasXPath(xPath); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node * at the specified xPath within the specified namespace context, with any content. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs))
* * @param xPath * the target xpath * @param namespaceContext * the namespace for matching nodes */ public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, javax.xml.namespace.NamespaceContext namespaceContext) { return org.hamcrest.xml.HasXPath.hasXPath(xPath, namespaceContext); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java000066400000000000000000000007221355170103300263110ustar00rootroot00000000000000package org.hamcrest; /** * The ability of an object to describe itself. */ public interface SelfDescribing { /** * Generates a description of the object. The description may be part of a * a description of a larger object of which this is just a component, so it * should be worded appropriately. * * @param description * The description to be built or appended to. */ void describeTo(Description description); }JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/StringDescription.java000066400000000000000000000027531355170103300271060ustar00rootroot00000000000000package org.hamcrest; import java.io.IOException; /** * A {@link Description} that is stored as a string. */ public class StringDescription extends BaseDescription { private final Appendable out; public StringDescription() { this(new StringBuilder()); } public StringDescription(Appendable out) { this.out = out; } /** * Return the description of a {@link SelfDescribing} object as a String. * * @param selfDescribing * The object to be described. * @return * The description of the object. */ public static String toString(SelfDescribing selfDescribing) { return new StringDescription().appendDescriptionOf(selfDescribing).toString(); } /** * Alias for {@link #toString(SelfDescribing)}. */ public static String asString(SelfDescribing selfDescribing) { return toString(selfDescribing); } @Override protected void append(String str) { try { out.append(str); } catch (IOException e) { throw new RuntimeException("Could not write description", e); } } @Override protected void append(char c) { try { out.append(c); } catch (IOException e) { throw new RuntimeException("Could not write description", e); } } /** * Returns the description as a string. */ @Override public String toString() { return out.toString(); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java000066400000000000000000000047511355170103300304630ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.internal.ReflectiveTypeFinder; /** * Convenient base class for Matchers that require a non-null value of a specific type * and that will report why the received value has been rejected. * This implements the null check, checks the type and then casts. * To use, implement
matchesSafely()
. * * @param * @author Neil Dunn * @author Nat Pryce * @author Steve Freeman */ public abstract class TypeSafeDiagnosingMatcher extends BaseMatcher { private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 2, 0); private final Class expectedType; /** * Subclasses should implement this. The item will already have been checked * for the specific type and will never be null. */ protected abstract boolean matchesSafely(T item, Description mismatchDescription); /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param expectedType The expectedType of the actual value. */ protected TypeSafeDiagnosingMatcher(Class expectedType) { this.expectedType = expectedType; } /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param typeFinder A type finder to extract the type */ protected TypeSafeDiagnosingMatcher(ReflectiveTypeFinder typeFinder) { this.expectedType = typeFinder.findExpectedType(getClass()); } /** * The default constructor for simple sub types */ protected TypeSafeDiagnosingMatcher() { this(TYPE_FINDER); } @Override @SuppressWarnings("unchecked") public final boolean matches(Object item) { return item != null && expectedType.isInstance(item) && matchesSafely((T) item, new Description.NullDescription()); } @SuppressWarnings("unchecked") @Override public final void describeMismatch(Object item, Description mismatchDescription) { if (item == null) { mismatchDescription.appendText("was null"); } else if (!expectedType.isInstance(item)) { mismatchDescription.appendText("was ") .appendText(item.getClass().getSimpleName()) .appendText(" ") .appendValue(item); } else { matchesSafely((T) item, mismatchDescription); } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/TypeSafeMatcher.java000066400000000000000000000055611355170103300264600ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.internal.ReflectiveTypeFinder; /** * Convenient base class for Matchers that require a non-null value of a specific type. * This simply implements the null check, checks the type and then casts. * * @author Joe Walnes * @author Steve Freeman * @author Nat Pryce */ public abstract class TypeSafeMatcher extends BaseMatcher { private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 1, 0); final private Class expectedType; /** * The default constructor for simple sub types */ protected TypeSafeMatcher() { this(TYPE_FINDER); } /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param expectedType The expectedType of the actual value. */ protected TypeSafeMatcher(Class expectedType) { this.expectedType = expectedType; } /** * Use this constructor if the subclass that implements matchesSafely * is not the class that binds <T> to a type. * @param typeFinder A type finder to extract the type */ protected TypeSafeMatcher(ReflectiveTypeFinder typeFinder) { this.expectedType = typeFinder.findExpectedType(getClass()); } /** * Subclasses should implement this. The item will already have been checked for * the specific type and will never be null. */ protected abstract boolean matchesSafely(T item); /** * Subclasses should override this. The item will already have been checked for * the specific type and will never be null. */ protected void describeMismatchSafely(T item, Description mismatchDescription) { super.describeMismatch(item, mismatchDescription); } /** * Methods made final to prevent accidental override. * If you need to override this, there's no point on extending TypeSafeMatcher. * Instead, extend the {@link BaseMatcher}. */ @Override @SuppressWarnings({"unchecked"}) public final boolean matches(Object item) { return item != null && expectedType.isInstance(item) && matchesSafely((T) item); } @SuppressWarnings("unchecked") @Override final public void describeMismatch(Object item, Description description) { if (item == null) { super.describeMismatch(null, description); } else if (! expectedType.isInstance(item)) { description.appendText("was a ") .appendText(item.getClass().getName()) .appendText(" (") .appendValue(item) .appendText(")"); } else { describeMismatchSafely((T)item, description); } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/beans/000077500000000000000000000000001355170103300236525ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/beans/HasProperty.java000066400000000000000000000031771355170103300270050ustar00rootroot00000000000000package org.hamcrest.beans; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * A Matcher that checks that an object has a JavaBean property * with the specified name. If an error occurs during introspection * of the object then this is treated as a mismatch. * * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman */ public class HasProperty extends TypeSafeMatcher { private final String propertyName; public HasProperty(String propertyName) { this.propertyName = propertyName; } @Override public boolean matchesSafely(T obj) { try { return PropertyUtil.getPropertyDescriptor(propertyName, obj) != null; } catch (IllegalArgumentException e) { return false; } } @Override public void describeMismatchSafely(T item, Description mismatchDescription) { mismatchDescription.appendText("no ").appendValue(propertyName).appendText(" in ").appendValue(item); } @Override public void describeTo(Description description) { description.appendText("hasProperty(").appendValue(propertyName).appendText(")"); } /** * Creates a matcher that matches when the examined object has a JavaBean property * with the specified name. * For example: *
assertThat(myBean, hasProperty("foo"))
* * @param propertyName * the name of the JavaBean property that examined beans should possess */ public static Matcher hasProperty(String propertyName) { return new HasProperty(propertyName); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/beans/HasPropertyWithValue.java000066400000000000000000000172341355170103300306350ustar00rootroot00000000000000package org.hamcrest.beans; import org.hamcrest.Condition; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import static org.hamcrest.Condition.matched; import static org.hamcrest.Condition.notMatched; import static org.hamcrest.beans.PropertyUtil.NO_ARGUMENTS; /** *

Matcher that asserts that a JavaBean property on an argument passed to the * mock object meets the provided matcher. This is useful for when objects * are created within code under test and passed to a mock object, and you wish * to assert that the created object has certain properties. *

* *

Example Usage

* Consider the situation where we have a class representing a person, which * follows the basic JavaBean convention of having get() and possibly set() * methods for it's properties: *
 * public class Person {
 *   private String name;
 *   public Person(String person) {
 *     this.person = person;
 *   }
 *   public String getName() {
 *     return name;
 *   }
 * }
* * And that these person objects are generated within a piece of code under test * (a class named PersonGenerator). This object is sent to one of our mock objects * which overrides the PersonGenerationListener interface: *
 * public interface PersonGenerationListener {
 *   public void personGenerated(Person person);
 * }
* * In order to check that the code under test generates a person with name * "Iain" we would do the following: *
 * Mock personGenListenerMock = mock(PersonGenerationListener.class);
 * personGenListenerMock.expects(once()).method("personGenerated").with(and(isA(Person.class), hasProperty("Name", eq("Iain")));
 * PersonGenerationListener listener = (PersonGenerationListener)personGenListenerMock.proxy();
* *

If an exception is thrown by the getter method for a property, the property * does not exist, is not readable, or a reflection related exception is thrown * when trying to invoke it then this is treated as an evaluation failure and * the matches method will return false. *

*

This matcher class will also work with JavaBean objects that have explicit * bean descriptions via an associated BeanInfo description class. See the * JavaBeans specification for more information: * http://java.sun.com/products/javabeans/docs/index.html *

* * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman * @author cristcost at github */ public class HasPropertyWithValue extends TypeSafeDiagnosingMatcher { private static final Condition.Step WITH_READ_METHOD = withReadMethod(); private final String propertyName; private final Matcher valueMatcher; private final String messageFormat; public HasPropertyWithValue(String propertyName, Matcher valueMatcher) { this(propertyName, valueMatcher, " property '%s' "); } public HasPropertyWithValue(String propertyName, Matcher valueMatcher, String messageFormat) { this.propertyName = propertyName; this.valueMatcher = nastyGenericsWorkaround(valueMatcher); this.messageFormat = messageFormat; } @Override public boolean matchesSafely(T bean, Description mismatch) { return propertyOn(bean, mismatch) .and(WITH_READ_METHOD) .and(withPropertyValue(bean)) .matching(valueMatcher, String.format(messageFormat, propertyName)); } @Override public void describeTo(Description description) { description.appendText("hasProperty(").appendValue(propertyName).appendText(", ") .appendDescriptionOf(valueMatcher).appendText(")"); } private Condition propertyOn(T bean, Description mismatch) { PropertyDescriptor property = PropertyUtil.getPropertyDescriptor(propertyName, bean); if (property == null) { mismatch.appendText("No property \"" + propertyName + "\""); return notMatched(); } return matched(property, mismatch); } private Condition.Step withPropertyValue(final T bean) { return new Condition.Step() { @Override public Condition apply(Method readMethod, Description mismatch) { try { return matched(readMethod.invoke(bean, NO_ARGUMENTS), mismatch); } catch (InvocationTargetException e) { mismatch .appendText("Calling '") .appendText(readMethod.toString()) .appendText("': ") .appendValue(e.getTargetException().getMessage()); return notMatched(); } catch (Exception e) { throw new IllegalStateException( "Calling: '" + readMethod + "' should not have thrown " + e); } } }; } @SuppressWarnings("unchecked") private static Matcher nastyGenericsWorkaround(Matcher valueMatcher) { return (Matcher) valueMatcher; } private static Condition.Step withReadMethod() { return new Condition.Step() { @Override public Condition apply(PropertyDescriptor property, Description mismatch) { final Method readMethod = property.getReadMethod(); if (null == readMethod) { mismatch.appendText("property \"" + property.getName() + "\" is not readable"); return notMatched(); } return matched(readMethod, mismatch); } }; } /** * Creates a matcher that matches when the examined object has a JavaBean property * with the specified name whose value satisfies the specified matcher. * For example: *
assertThat(myBean, hasProperty("foo", equalTo("bar"))
* * @param propertyName * the name of the JavaBean property that examined beans should possess * @param valueMatcher * a matcher for the value of the specified property of the examined bean */ public static Matcher hasProperty(String propertyName, Matcher valueMatcher) { return new HasPropertyWithValue<>(propertyName, valueMatcher); } /** * Creates a matcher that matches when the examined object is a graph of * JavaBean objects that can be navigated along the declared dot-separated path * and the final element of that path is a JavaBean property whose value satisfies the * specified matcher. * For example: *
assertThat(myBean, hasProperty("foo.bar.baz", equalTo("a property value"))
* * @param path * the dot-separated path from the examined object to the JavaBean property * @param valueMatcher * a matcher for the value of the specified property of the examined bean */ public static Matcher hasPropertyAtPath(String path, Matcher valueMatcher) { List properties = Arrays.asList(path.split("\\.")); ListIterator iterator = properties.listIterator(properties.size()); Matcher ret = valueMatcher; while (iterator.hasPrevious()) { ret = new HasPropertyWithValue<>(iterator.previous(), ret, "%s."); } return ret; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java000066400000000000000000000035701355170103300272040ustar00rootroot00000000000000package org.hamcrest.beans; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; /** * Utility class for accessing properties on JavaBean objects. * See http://java.sun.com/products/javabeans/docs/index.html for * more information on JavaBeans. * * @author Iain McGinniss * @author Steve Freeman * @since 1.1.0 */ public class PropertyUtil { /** * Returns the description of the property with the provided * name on the provided object's interface. * * @return the descriptor of the property, or null if the property does not exist. * @throws IllegalArgumentException if there's a introspection failure */ public static PropertyDescriptor getPropertyDescriptor(String propertyName, Object fromObj) throws IllegalArgumentException { for (PropertyDescriptor property : propertyDescriptorsFor(fromObj, null)) { if (property.getName().equals(propertyName)) { return property; } } return null; } /** * Returns all the property descriptors for the class associated with the given object * * @param fromObj Use the class of this object * @param stopClass Don't include any properties from this ancestor class upwards. * @return Property descriptors * @throws IllegalArgumentException if there's a introspection failure */ public static PropertyDescriptor[] propertyDescriptorsFor(Object fromObj, Class stopClass) throws IllegalArgumentException { try { return Introspector.getBeanInfo(fromObj.getClass(), stopClass).getPropertyDescriptors(); } catch (IntrospectionException e) { throw new IllegalArgumentException("Could not get property descriptors for " + fromObj.getClass(), e); } } public static final Object[] NO_ARGUMENTS = new Object[0]; } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java000066400000000000000000000147051355170103300306220ustar00rootroot00000000000000package org.hamcrest.beans; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; import org.hamcrest.Matcher; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.*; import static java.util.Arrays.asList; import static org.hamcrest.beans.PropertyUtil.NO_ARGUMENTS; import static org.hamcrest.beans.PropertyUtil.propertyDescriptorsFor; import static org.hamcrest.core.IsEqual.equalTo; public class SamePropertyValuesAs extends DiagnosingMatcher { private final T expectedBean; private final Set propertyNames; private final List propertyMatchers; private final List ignoredFields; @SuppressWarnings("WeakerAccess") public SamePropertyValuesAs(T expectedBean, List ignoredProperties) { PropertyDescriptor[] descriptors = propertyDescriptorsFor(expectedBean, Object.class); this.expectedBean = expectedBean; this.ignoredFields = ignoredProperties; this.propertyNames = propertyNamesFrom(descriptors, ignoredProperties); this.propertyMatchers = propertyMatchersFor(expectedBean, descriptors, ignoredProperties); } @Override protected boolean matches(Object actual, Description mismatch) { return isNotNull(actual, mismatch) && isCompatibleType(actual, mismatch) && hasNoExtraProperties(actual, mismatch) && hasMatchingValues(actual, mismatch); } @Override public void describeTo(Description description) { description.appendText("same property values as " + expectedBean.getClass().getSimpleName()) .appendList(" [", ", ", "]", propertyMatchers); if (! ignoredFields.isEmpty()) { description.appendText(" ignoring ") .appendValueList("[", ", ", "]", ignoredFields); } } private boolean isCompatibleType(Object actual, Description mismatchDescription) { if (expectedBean.getClass().isAssignableFrom(actual.getClass())) { return true; } mismatchDescription.appendText("is incompatible type: " + actual.getClass().getSimpleName()); return false; } private boolean hasNoExtraProperties(Object actual, Description mismatchDescription) { Set actualPropertyNames = propertyNamesFrom(propertyDescriptorsFor(actual, Object.class), ignoredFields); actualPropertyNames.removeAll(propertyNames); if (!actualPropertyNames.isEmpty()) { mismatchDescription.appendText("has extra properties called " + actualPropertyNames); return false; } return true; } private boolean hasMatchingValues(Object actual, Description mismatchDescription) { for (PropertyMatcher propertyMatcher : propertyMatchers) { if (!propertyMatcher.matches(actual)) { propertyMatcher.describeMismatch(actual, mismatchDescription); return false; } } return true; } private static List propertyMatchersFor(T bean, PropertyDescriptor[] descriptors, List ignoredFields) { List result = new ArrayList<>(descriptors.length); for (PropertyDescriptor propertyDescriptor : descriptors) { if (isIgnored(ignoredFields, propertyDescriptor)) { result.add(new PropertyMatcher(propertyDescriptor, bean)); } } return result; } private static Set propertyNamesFrom(PropertyDescriptor[] descriptors, List ignoredFields) { HashSet result = new HashSet<>(); for (PropertyDescriptor propertyDescriptor : descriptors) { if (isIgnored(ignoredFields, propertyDescriptor)) { result.add(propertyDescriptor.getDisplayName()); } } return result; } private static boolean isIgnored(List ignoredFields, PropertyDescriptor propertyDescriptor) { return ! ignoredFields.contains(propertyDescriptor.getDisplayName()); } @SuppressWarnings("WeakerAccess") private static class PropertyMatcher extends DiagnosingMatcher { private final Method readMethod; private final Matcher matcher; private final String propertyName; public PropertyMatcher(PropertyDescriptor descriptor, Object expectedObject) { this.propertyName = descriptor.getDisplayName(); this.readMethod = descriptor.getReadMethod(); this.matcher = equalTo(readProperty(readMethod, expectedObject)); } @Override public boolean matches(Object actual, Description mismatch) { final Object actualValue = readProperty(readMethod, actual); if (!matcher.matches(actualValue)) { mismatch.appendText(propertyName + " "); matcher.describeMismatch(actualValue, mismatch); return false; } return true; } @Override public void describeTo(Description description) { description.appendText(propertyName + ": ").appendDescriptionOf(matcher); } } private static Object readProperty(Method method, Object target) { try { return method.invoke(target, NO_ARGUMENTS); } catch (Exception e) { throw new IllegalArgumentException("Could not invoke " + method + " on " + target, e); } } /** * Creates a matcher that matches when the examined object has values for all of * its JavaBean properties that are equal to the corresponding values of the * specified bean. If any properties are marked as ignored, they will be dropped from * both the expected and actual bean. Note that the ignored properties use JavaBean * display names, for example
age
rather than method names such as
getAge
. * For example: *
assertThat(myBean, samePropertyValuesAs(myExpectedBean))
*
assertThat(myBean, samePropertyValuesAs(myExpectedBean), "age", "height")
* * @param expectedBean * the bean against which examined beans are compared * @param ignoredProperties * do not check any of these named properties. */ public static Matcher samePropertyValuesAs(B expectedBean, String... ignoredProperties) { return new SamePropertyValuesAs<>(expectedBean, asList(ignoredProperties)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/beans/package.html000066400000000000000000000001511355170103300261300ustar00rootroot00000000000000

Matchers of Java Bean properties and their values.

JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/000077500000000000000000000000001355170103300247155ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/ArrayAsIterableMatcher.java000066400000000000000000000024331355170103300321000ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.TypeSafeMatcher; import java.util.Collection; import static java.util.Arrays.asList; /** * @author Steve Freeman 2016 http://www.hamcrest.com */ public class ArrayAsIterableMatcher extends TypeSafeMatcher { protected final TypeSafeDiagnosingMatcher> iterableMatcher; private final String message; protected final Collection> matchers; public ArrayAsIterableMatcher( TypeSafeDiagnosingMatcher> iterableMatcher, Collection> matchers, String message) { this.matchers = matchers; this.iterableMatcher = iterableMatcher; this.message = message; } @Override public boolean matchesSafely(E[] item) { return iterableMatcher.matches(asList(item)); } @Override public void describeMismatchSafely(E[] item, Description mismatchDescription) { iterableMatcher.describeMismatch(asList(item), mismatchDescription); } @Override public void describeTo(Description description) { description.appendList("[", ", ", "]", matchers) .appendText(" ").appendText(message); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/ArrayMatching.java000066400000000000000000000154461355170103300303230ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Matcher; import org.hamcrest.internal.NullSafety; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.core.IsEqual.equalTo; /** * @author Steve Freeman 2016 http://www.hamcrest.com * Collected helper code for converting matchers between lists and iterables. */ public class ArrayMatching { /** * Creates a matcher for arrays that matches when the examined array contains at least one item * that is matched by the specified elementMatcher. Whilst matching, the traversal * of the examined array will stop as soon as a matching element is found. * For example: *
assertThat(new String[] {"foo", "bar"}, hasItemInArray(startsWith("ba")))
* * @param elementMatcher * the matcher to apply to elements in examined arrays */ public static Matcher hasItemInArray(Matcher elementMatcher) { return new HasItemInArray<>(elementMatcher); } /** * A shortcut to the frequently used hasItemInArray(equalTo(x)). * For example: *
assertThat(hasItemInArray(x))
* instead of: *
assertThat(hasItemInArray(equalTo(x)))
* * @param element * the element that should be present in examined arrays */ public static Matcher hasItemInArray(T element) { return hasItemInArray(equalTo(element)); } /** *

* Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified matchers. * For a positive match, the examined array must be of the same length as the number of * specified matchers. *

*

* N.B. each of the specified matchers will only be used once during a given examination, so be * careful when specifying matchers that may be satisfied by more than one entry in an examined * array. *

*

* For example: *

*
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(equalTo("bar"), equalTo("foo")))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an entry in an examined array */ @SafeVarargs public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) { return arrayContainingInAnyOrder(asList(itemMatchers)); } /** *

* Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified collection of matchers. * For a positive match, the examined array must be of the same length as the specified collection * of matchers. *

*

* N.B. each matcher in the specified collection will only be used once during a given * examination, so be careful when specifying matchers that may be satisfied by more than * one entry in an examined array. *

*

* For example: *

*
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined array */ public static Matcher arrayContainingInAnyOrder(Collection> itemMatchers) { return new ArrayAsIterableMatcher<>(new IsIterableContainingInAnyOrder<>(itemMatchers), itemMatchers, "in any order"); } /** *

Creates an order agnostic matcher for arrays that matches when each item in the * examined array is logically equal to one item anywhere in the specified items. * For a positive match, the examined array must be of the same length as the number of * specified items. *

*

N.B. each of the specified items will only be used once during a given examination, so be * careful when specifying items that may be equal to more than one entry in an examined * array. *

*

* For example: *

*
assertThat(new String[]{"foo", "bar"}, containsInAnyOrder("bar", "foo"))
* * @param items * the items that must equal the entries of an examined array, in any order */ @SafeVarargs public static Matcher arrayContainingInAnyOrder(E... items) { return arrayContainingInAnyOrder(asEqualMatchers(items)); } /** * Creates a matcher for arrays that matches when each item in the examined array is * logically equal to the corresponding item in the specified items. For a positive match, * the examined array must be of the same length as the number of specified items. * For example: *
assertThat(new String[]{"foo", "bar"}, contains("foo", "bar"))
* * @param items * the items that must equal the items within an examined array */ @SafeVarargs public static Matcher arrayContaining(E... items) { return arrayContaining(asEqualMatchers(items)); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified matchers. For a positive match, the examined array * must be of the same length as the number of specified matchers. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining(equalTo("foo"), equalTo("bar")))
* * @param itemMatchers * the matchers that must be satisfied by the items in the examined array */ @SafeVarargs public static Matcher arrayContaining(Matcher... itemMatchers) { //required for JDK 1.6 //noinspection RedundantTypeArguments final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); return arrayContaining(nullSafeWithExplicitTypeMatchers); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified list of matchers. For a positive match, the examined array * must be of the same length as the specified list of matchers. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining(Arrays.asList(equalTo("foo"), equalTo("bar"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item in an examined array */ public static Matcher arrayContaining(List> itemMatchers) { return new ArrayAsIterableMatcher<>(new IsIterableContainingInOrder<>(itemMatchers), itemMatchers, ""); } public static List> asEqualMatchers(E[] items) { final List> matchers = new ArrayList<>(); for (E item : items) { matchers.add(equalTo(item)); } return matchers; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java000066400000000000000000000023431355170103300304020ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.core.IsIterableContaining; import static java.util.Arrays.asList; /** * Matches if an array contains an item satisfying a nested matcher. */ public class HasItemInArray extends TypeSafeMatcher { private final Matcher elementMatcher; private final TypeSafeDiagnosingMatcher> collectionMatcher; public HasItemInArray(Matcher elementMatcher) { this.elementMatcher = elementMatcher; this.collectionMatcher = new IsIterableContaining<>(elementMatcher); } @Override public boolean matchesSafely(T[] actual) { return collectionMatcher.matches(asList(actual)); } @Override public void describeMismatchSafely(T[] actual, Description mismatchDescription) { collectionMatcher.describeMismatch(asList(actual), mismatchDescription); } @Override public void describeTo(Description description) { description .appendText("an array containing ") .appendDescriptionOf(elementMatcher); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsArray.java000066400000000000000000000060521355170103300271350ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Arrays; /** * Matcher for array whose elements satisfy a sequence of matchers. * The array size must equal the number of element matchers. */ public class IsArray extends TypeSafeMatcher { private final Matcher[] elementMatchers; public IsArray(Matcher[] elementMatchers) { this.elementMatchers = elementMatchers.clone(); } @Override public boolean matchesSafely(T[] array) { if (array.length != elementMatchers.length) return false; for (int i = 0; i < array.length; i++) { if (!elementMatchers[i].matches(array[i])) return false; } return true; } @Override public void describeMismatchSafely(T[] actual, Description mismatchDescription) { if (actual.length != elementMatchers.length) { mismatchDescription.appendText("array length was ").appendValue(actual.length); return; } for (int i = 0; i < actual.length; i++) { if (!elementMatchers[i].matches(actual[i])) { mismatchDescription.appendText("element ").appendValue(i).appendText(" "); elementMatchers[i].describeMismatch(actual[i], mismatchDescription); return; } } } @Override @SuppressWarnings("unchecked") public void describeTo(Description description) { description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(), Arrays.asList(elementMatchers)); } /** * Returns the string that starts the description. * * Can be overridden in subclasses to customise how the matcher is * described. */ protected String descriptionStart() { return "["; } /** * Returns the string that separates the elements in the description. * * Can be overridden in subclasses to customise how the matcher is * described. */ protected String descriptionSeparator() { return ", "; } /** * Returns the string that ends the description. * * Can be overridden in subclasses to customise how the matcher is * described. */ protected String descriptionEnd() { return "]"; } /** * Creates a matcher that matches arrays whose elements are satisfied by the specified matchers. Matches * positively only if the number of matchers specified is equal to the length of the examined array and * each matcher[i] is satisfied by array[i]. * For example: *
assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))
* * @param elementMatchers * the matchers that the elements of examined arrays should satisfy */ public static IsArray array(Matcher... elementMatchers) { return new IsArray(elementMatchers); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.java000066400000000000000000000111001355170103300330700ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.hamcrest.core.IsEqual.equalTo; /** * @deprecated As of release 2.1, replaced by {@link ArrayMatching}. */ @Deprecated public class IsArrayContainingInAnyOrder extends TypeSafeMatcher { private final IsIterableContainingInAnyOrder iterableMatcher; private final Collection> matchers; public IsArrayContainingInAnyOrder(Collection> matchers) { this.iterableMatcher = new IsIterableContainingInAnyOrder(matchers); this.matchers = matchers; } @Override public boolean matchesSafely(E[] item) { return iterableMatcher.matches(Arrays.asList(item)); } @Override public void describeMismatchSafely(E[] item, Description mismatchDescription) { iterableMatcher.describeMismatch(Arrays.asList(item), mismatchDescription); }; @Override public void describeTo(Description description) { description.appendList("[", ", ", "]", matchers) .appendText(" in any order"); } /** * Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified matchers. * For a positive match, the examined array must be of the same length as the number of * specified matchers. *

* N.B. each of the specified matchers will only be used once during a given examination, so be * careful when specifying matchers that may be satisfied by more than one entry in an examined * array. *

* For example: *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(equalTo("bar"), equalTo("foo")))
* * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Matcher[])}. * * @param itemMatchers * a list of matchers, each of which must be satisfied by an entry in an examined array */ public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) { return arrayContainingInAnyOrder(Arrays.asList(itemMatchers)); } /** * Creates an order agnostic matcher for arrays that matches when each item in the * examined array satisfies one matcher anywhere in the specified collection of matchers. * For a positive match, the examined array must be of the same length as the specified collection * of matchers. *

* N.B. each matcher in the specified collection will only be used once during a given * examination, so be careful when specifying matchers that may be satisfied by more than * one entry in an examined array. *

* For example: *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
* * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Collection)}. * * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined array */ public static Matcher arrayContainingInAnyOrder(Collection> itemMatchers) { return new IsArrayContainingInAnyOrder(itemMatchers); } /** * Creates an order agnostic matcher for arrays that matches when each item in the * examined array is logically equal to one item anywhere in the specified items. * For a positive match, the examined array must be of the same length as the number of * specified items. *

* N.B. each of the specified items will only be used once during a given examination, so be * careful when specifying items that may be equal to more than one entry in an examined * array. *

* For example: *

assertThat(new String[]{"foo", "bar"}, containsInAnyOrder("bar", "foo"))
* * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Object[])}. * * @param items * the items that must equal the entries of an examined array, in any order */ public static Matcher arrayContainingInAnyOrder(E... items) { List> matchers = new ArrayList>(); for (E item : items) { matchers.add(equalTo(item)); } return new IsArrayContainingInAnyOrder(matchers); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.java000066400000000000000000000071601355170103300324330ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.core.IsEqual.equalTo; /** * @deprecated As of release 2.1, replaced by {@link ArrayMatching}. */ public class IsArrayContainingInOrder extends TypeSafeMatcher { private final Collection> matchers; private final IsIterableContainingInOrder iterableMatcher; public IsArrayContainingInOrder(List> matchers) { this.iterableMatcher = new IsIterableContainingInOrder(matchers); this.matchers = matchers; } @Override public boolean matchesSafely(E[] item) { return iterableMatcher.matches(asList(item)); } @Override public void describeMismatchSafely(E[] item, Description mismatchDescription) { iterableMatcher.describeMismatch(asList(item), mismatchDescription); } @Override public void describeTo(Description description) { description.appendList("[", ", ", "]", matchers); } /** * Creates a matcher for arrays that matcheswhen each item in the examined array is * logically equal to the corresponding item in the specified items. For a positive match, * the examined array must be of the same length as the number of specified items. *

* For example: *

assertThat(new String[]{"foo", "bar"}, contains("foo", "bar"))
* * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(Object[])}. * * @param items * the items that must equal the items within an examined array */ public static Matcher arrayContaining(E... items) { List> matchers = new ArrayList>(); for (E item : items) { matchers.add(equalTo(item)); } return arrayContaining(matchers); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified matchers. For a positive match, the examined array * must be of the same length as the number of specified matchers. *

* For example: *

assertThat(new String[]{"foo", "bar"}, contains(equalTo("foo"), equalTo("bar")))
* * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(Matcher[])}. * * @param itemMatchers * the matchers that must be satisfied by the items in the examined array */ public static Matcher arrayContaining(Matcher... itemMatchers) { return arrayContaining(asList(itemMatchers)); } /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified list of matchers. For a positive match, the examined array * must be of the same length as the specified list of matchers. *

* For example: *

assertThat(new String[]{"foo", "bar"}, contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
* * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(List)}. * * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item in an examined array */ public static Matcher arrayContaining(List> itemMatchers) { return new IsArrayContainingInOrder(itemMatchers); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsArrayWithSize.java000066400000000000000000000035301355170103300306220ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import static org.hamcrest.core.DescribedAs.describedAs; import static org.hamcrest.core.IsEqual.equalTo; /** * Matches if array size satisfies a nested matcher. */ public class IsArrayWithSize extends FeatureMatcher { public IsArrayWithSize(Matcher sizeMatcher) { super(sizeMatcher, "an array with size","array size"); } @Override protected Integer featureValueOf(E[] actual) { return actual.length; } /** * Creates a matcher for arrays that matches when the length of the array * satisfies the specified matcher. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the length of an examined array */ public static Matcher arrayWithSize(Matcher sizeMatcher) { return new IsArrayWithSize<>(sizeMatcher); } /** * Creates a matcher for arrays that matches when the length of the array * equals the specified size. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(2))
* * @param size * the length that an examined array must have for a positive match */ public static Matcher arrayWithSize(int size) { return arrayWithSize(equalTo(size)); } /** * Creates a matcher for arrays that matches when the length of the array * is zero. * For example: *
assertThat(new String[0], emptyArray())
* */ public static Matcher emptyArray() { return describedAs("an empty array", IsArrayWithSize.arrayWithSize(0)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsCollectionWithSize.java000066400000000000000000000033361355170103300316430ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import java.util.Collection; import static org.hamcrest.core.IsEqual.equalTo; /** * Matches if collection size satisfies a nested matcher. */ public class IsCollectionWithSize extends FeatureMatcher, Integer> { public IsCollectionWithSize(Matcher sizeMatcher) { super(sizeMatcher, "a collection with size", "collection size"); } @Override protected Integer featureValueOf(Collection actual) { return actual.size(); } /** * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns * a value that satisfies the specified matcher. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the size of an examined {@link java.util.Collection} */ public static Matcher> hasSize(Matcher sizeMatcher) { return new IsCollectionWithSize(sizeMatcher); } /** * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns * a value equal to the specified size. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasSize(2))
* * @param size * the expected size of an examined {@link java.util.Collection} */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Matcher> hasSize(int size) { return (Matcher)IsCollectionWithSize.hasSize(equalTo(size)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyCollection.java000066400000000000000000000032141355170103300311660ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Collection; /** * Tests if collection is empty. */ public class IsEmptyCollection extends TypeSafeMatcher> { @Override public boolean matchesSafely(Collection item) { return item.isEmpty(); } @Override public void describeMismatchSafely(Collection item, Description mismatchDescription) { mismatchDescription.appendValue(item); } @Override public void describeTo(Description description) { description.appendText("an empty collection"); } /** * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty * method returns true. * For example: *
assertThat(new ArrayList<String>(), is(empty()))
* */ public static Matcher> empty() { return new IsEmptyCollection(); } /** * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty * method returns true. * For example: *
assertThat(new ArrayList<String>(), is(emptyCollectionOf(String.class)))
* * @param unusedToForceReturnType * the type of the collection's content */ @SuppressWarnings({"unchecked", "UnusedParameters"}) public static Matcher> emptyCollectionOf(Class unusedToForceReturnType) { return (Matcher)empty(); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyIterable.java000066400000000000000000000030361355170103300306240ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Tests if collection is empty. */ public class IsEmptyIterable extends TypeSafeMatcher> { @Override public boolean matchesSafely(Iterable iterable) { return !iterable.iterator().hasNext(); } @Override public void describeMismatchSafely(Iterable iter, Description mismatchDescription) { mismatchDescription.appendValueList("[", ",", "]", iter); } @Override public void describeTo(Description description) { description.appendText("an empty iterable"); } /** * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. * For example: *
assertThat(new ArrayList<String>(), is(emptyIterable()))
* */ public static Matcher> emptyIterable() { return new IsEmptyIterable(); } /** * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. * For example: *
assertThat(new ArrayList<String>(), is(emptyIterableOf(String.class)))
* * @param unusedToForceReturnType * the type of the iterable's content */ @SuppressWarnings({"unchecked", "UnusedParameters"}) public static Matcher> emptyIterableOf(Class unusedToForceReturnType) { return (Matcher)emptyIterable(); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsIn.java000066400000000000000000000067071355170103300264340ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import java.util.Arrays; import java.util.Collection; public class IsIn extends BaseMatcher { private final Collection collection; public IsIn(Collection collection) { this.collection = collection; } public IsIn(T[] elements) { collection = Arrays.asList(elements); } @SuppressWarnings("SuspiciousMethodCalls") @Override public boolean matches(Object o) { return collection.contains(o); } @Override public void describeTo(Description buffer) { buffer.appendText("one of "); buffer.appendValueList("{", ", ", "}", collection); } /** * Creates a matcher that matches when the examined object is found within the * specified collection. * For example: *
assertThat("foo", isIn(Arrays.asList("bar", "foo")))
* * @deprecated use is(in(...)) instead * * @param collection * the collection in which matching items must be found * */ @Deprecated public static Matcher isIn(Collection collection) { return in(collection); } /** * Creates a matcher that matches when the examined object is found within the * specified collection. * For example: *
assertThat("foo", is(in(Arrays.asList("bar", "foo"))))
* * @param collection * the collection in which matching items must be found * */ public static Matcher in(Collection collection) { return new IsIn<>(collection); } /** * Creates a matcher that matches when the examined object is found within the * specified array. * For example: *
assertThat("foo", isIn(new String[]{"bar", "foo"}))
* * @deprecated use is(in(...)) instead * * @param elements * the array in which matching items must be found * */ @Deprecated public static Matcher isIn(T[] elements) { return in(elements); } /** * Creates a matcher that matches when the examined object is found within the * specified array. * For example: *
assertThat("foo", is(in(new String[]{"bar", "foo"})))
* * @param elements * the array in which matching items must be found * */ public static Matcher in(T[] elements) { return new IsIn<>(elements); } /** * Creates a matcher that matches when the examined object is equal to one of the * specified elements. * For example: *
assertThat("foo", isOneOf("bar", "foo"))
* * @deprecated use is(oneOf(...)) instead * * @param elements * the elements amongst which matching items will be found * */ @SafeVarargs @Deprecated public static Matcher isOneOf(T... elements) { return oneOf(elements); } /** * Creates a matcher that matches when the examined object is equal to one of the * specified elements. * For example: *
assertThat("foo", is(oneOf("bar", "foo")))
* * @param elements * the elements amongst which matching items will be found * */ @SafeVarargs public static Matcher oneOf(T... elements) { return in(elements); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.java000066400000000000000000000134641355170103300335600ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableContainingInAnyOrder extends TypeSafeDiagnosingMatcher> { private final Collection> matchers; public IsIterableContainingInAnyOrder(Collection> matchers) { this.matchers = matchers; } @Override protected boolean matchesSafely(Iterable items, Description mismatchDescription) { final Matching matching = new Matching<>(matchers, mismatchDescription); for (T item : items) { if (! matching.matches(item)) { return false; } } return matching.isFinished(items); } @Override public void describeTo(Description description) { description.appendText("iterable with items ") .appendList("[", ", ", "]", matchers) .appendText(" in any order"); } private static class Matching { private final Collection> matchers; private final Description mismatchDescription; public Matching(Collection> matchers, Description mismatchDescription) { this.matchers = new ArrayList<>(matchers); this.mismatchDescription = mismatchDescription; } public boolean matches(S item) { if (matchers.isEmpty()) { mismatchDescription.appendText("no match for: ").appendValue(item); return false; } return isMatched(item); } public boolean isFinished(Iterable items) { if (matchers.isEmpty()) { return true; } mismatchDescription .appendText("no item matches: ").appendList("", ", ", "", matchers) .appendText(" in ").appendValueList("[", ", ", "]", items); return false; } private boolean isMatched(S item) { for (Matcher matcher : matchers) { if (matcher.matches(item)) { matchers.remove(matcher); return true; } } mismatchDescription.appendText("not matched: ").appendValue(item); return false; } } /** *

* Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere * in the specified matchers. For a positive match, the examined iterable must be of the same * length as the number of specified matchers. *

*

* N.B. each of the specified matchers will only be used once during a given examination, so be * careful when specifying matchers that may be satisfied by more than one entry in an examined * iterable. *

*

* For example: *

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(equalTo("bar"), equalTo("foo")))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ @SafeVarargs public static Matcher> containsInAnyOrder(Matcher... itemMatchers) { return containsInAnyOrder(Arrays.asList(itemMatchers)); } /** *

* Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each logically equal to one item * anywhere in the specified items. For a positive match, the examined iterable * must be of the same length as the number of specified items. *

*

* N.B. each of the specified items will only be used once during a given examination, so be * careful when specifying items that may be equal to more than one entry in an examined * iterable. *

*

* For example: *

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder("bar", "foo"))
* * @param items * the items that must equal the items provided by an examined {@link Iterable} in any order */ @SafeVarargs public static Matcher> containsInAnyOrder(T... items) { List> matchers = new ArrayList<>(); for (T item : items) { matchers.add(equalTo(item)); } return new IsIterableContainingInAnyOrder<>(matchers); } /** *

* Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere * in the specified collection of matchers. For a positive match, the examined iterable * must be of the same length as the specified collection of matchers. *

*

* N.B. each matcher in the specified collection will only be used once during a given * examination, so be careful when specifying matchers that may be satisfied by more than * one entry in an examined iterable. *

*

For example:

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ public static Matcher> containsInAnyOrder(Collection> itemMatchers) { return new IsIterableContainingInAnyOrder<>(itemMatchers); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.java000066400000000000000000000137541355170103300331120ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.internal.NullSafety; import java.util.ArrayList; import java.util.List; import static java.util.Collections.singletonList; import static org.hamcrest.collection.ArrayMatching.asEqualMatchers; public class IsIterableContainingInOrder extends TypeSafeDiagnosingMatcher> { private final List> matchers; public IsIterableContainingInOrder(List> matchers) { this.matchers = matchers; } @Override protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) { final MatchSeries matchSeries = new MatchSeries<>(matchers, mismatchDescription); for (E item : iterable) { if (!matchSeries.matches(item)) { return false; } } return matchSeries.isFinished(); } @Override public void describeTo(Description description) { description.appendText("iterable containing ").appendList("[", ", ", "]", matchers); } private static class MatchSeries { private final List> matchers; private final Description mismatchDescription; private int nextMatchIx = 0; public MatchSeries(List> matchers, Description mismatchDescription) { this.mismatchDescription = mismatchDescription; if (matchers.isEmpty()) { throw new IllegalArgumentException("Should specify at least one expected element"); } this.matchers = matchers; } public boolean matches(F item) { if (matchers.size() <= nextMatchIx) { mismatchDescription.appendText("not matched: ").appendValue(item); return false; } return isMatched(item); } public boolean isFinished() { if (nextMatchIx < matchers.size()) { mismatchDescription.appendText("no item was ").appendDescriptionOf(matchers.get(nextMatchIx)); return false; } return true; } private boolean isMatched(F item) { final Matcher matcher = matchers.get(nextMatchIx); if (!matcher.matches(item)) { describeMismatch(matcher, item); return false; } nextMatchIx++; return true; } private void describeMismatch(Matcher matcher, F item) { mismatchDescription.appendText("item " + nextMatchIx + ": "); matcher.describeMismatch(item, mismatchDescription); } } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each logically equal to the * corresponding item in the specified items. For a positive match, the examined iterable * must be of the same length as the number of specified items. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains("foo", "bar"))
* * @param items * the items that must equal the items provided by an examined {@link Iterable} */ @SafeVarargs public static Matcher> contains(E... items) { return contains(asEqualMatchers(items)); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a single item that satisfies the specified matcher. * For a positive match, the examined iterable must only yield one item. * For example: *
assertThat(Arrays.asList("foo"), contains(equalTo("foo")))
* * @param itemMatcher * the matcher that must be satisfied by the single item provided by an * examined {@link Iterable} */ @SuppressWarnings("unchecked") public static Matcher> contains(final Matcher itemMatcher) { return contains(new ArrayList>(singletonList(itemMatcher))); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each satisfying the corresponding * matcher in the specified matchers. For a positive match, the examined iterable * must be of the same length as the number of specified matchers. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains(equalTo("foo"), equalTo("bar")))
* * @param itemMatchers * the matchers that must be satisfied by the items provided by an examined {@link Iterable} */ @SafeVarargs public static Matcher> contains(Matcher... itemMatchers) { // required for JDK 1.6 //noinspection RedundantTypeArguments final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); return contains(nullSafeWithExplicitTypeMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, each satisfying the corresponding * matcher in the specified list of matchers. For a positive match, the examined iterable * must be of the same length as the specified list of matchers. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item provided by * an examined {@link Iterable} */ public static Matcher> contains(List> itemMatchers) { return new IsIterableContainingInOrder<>(itemMatchers); } } IsIterableContainingInRelativeOrder.java000066400000000000000000000117561355170103300345270ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collectionpackage org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableContainingInRelativeOrder extends TypeSafeDiagnosingMatcher> { private final List> matchers; public IsIterableContainingInRelativeOrder(List> matchers) { this.matchers = matchers; } @Override protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) { MatchSeriesInRelativeOrder matchSeriesInRelativeOrder = new MatchSeriesInRelativeOrder<>(matchers, mismatchDescription); matchSeriesInRelativeOrder.processItems(iterable); return matchSeriesInRelativeOrder.isFinished(); } public void describeTo(Description description) { description.appendText("iterable containing ").appendList("[", ", ", "]", matchers).appendText(" in relative order"); } private static class MatchSeriesInRelativeOrder { public final List> matchers; private final Description mismatchDescription; private int nextMatchIx = 0; private F lastMatchedItem = null; public MatchSeriesInRelativeOrder(List> matchers, Description mismatchDescription) { this.mismatchDescription = mismatchDescription; if (matchers.isEmpty()) { throw new IllegalArgumentException("Should specify at least one expected element"); } this.matchers = matchers; } public void processItems(Iterable iterable) { for (F item : iterable) { if (nextMatchIx < matchers.size()) { Matcher matcher = matchers.get(nextMatchIx); if (matcher.matches(item)) { lastMatchedItem = item; nextMatchIx++; } } } } public boolean isFinished() { if (nextMatchIx < matchers.size()) { mismatchDescription.appendDescriptionOf(matchers.get(nextMatchIx)).appendText(" was not found"); if (lastMatchedItem != null) { mismatchDescription.appendText(" after ").appendValue(lastMatchedItem); } return false; } return true; } } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, that contains items logically equal to the * corresponding item in the specified items, in the same relative order * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder("b", "d"))
* * @param items * the items that must be contained within items provided by an examined {@link Iterable} in the same relative order */ @SafeVarargs public static Matcher> containsInRelativeOrder(E... items) { List> matchers = new ArrayList<>(); for (E item : items) { matchers.add(equalTo(item)); } return containsInRelativeOrder(matchers); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, that each satisfying the corresponding * matcher in the specified matchers, in the same relative order. * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))
* * @param itemMatchers * the matchers that must be satisfied by the items provided by an examined {@link Iterable} in the same relative order */ @SafeVarargs public static Matcher> containsInRelativeOrder(Matcher... itemMatchers) { return containsInRelativeOrder(asList(itemMatchers)); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields a series of items, that contains items satisfying the corresponding * matcher in the specified list of matchers, in the same relative order. * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), contains(Arrays.asList(equalTo("b"), equalTo("d"))))
* * @param itemMatchers * a list of matchers, each of which must be satisfied by the items provided by * an examined {@link Iterable} in the same relative order */ public static Matcher> containsInRelativeOrder(List> itemMatchers) { return new IsIterableContainingInRelativeOrder<>(itemMatchers); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsIterableWithSize.java000066400000000000000000000034331355170103300312750ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import java.util.Iterator; import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableWithSize extends FeatureMatcher, Integer> { public IsIterableWithSize(Matcher sizeMatcher) { super(sizeMatcher, "an iterable with size", "iterable size"); } @Override protected Integer featureValueOf(Iterable actual) { int size = 0; for (Iterator iterator = actual.iterator(); iterator.hasNext(); iterator.next()) { size++; } return size; } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields an item count that satisfies the specified * matcher. * For example: *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(equalTo(2)))
* * @param sizeMatcher * a matcher for the number of items that should be yielded by an examined {@link Iterable} */ public static Matcher> iterableWithSize(Matcher sizeMatcher) { return new IsIterableWithSize(sizeMatcher); } /** * Creates a matcher for {@link Iterable}s that matches when a single pass over the * examined {@link Iterable} yields an item count that is equal to the specified * size argument. * For example: *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(2))
* * @param size * the number of items that should be yielded by an examined {@link Iterable} */ public static Matcher> iterableWithSize(int size) { return iterableWithSize(equalTo(size)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsMapContaining.java000066400000000000000000000121121355170103300306000ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Map; import java.util.Map.Entry; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; public class IsMapContaining extends TypeSafeMatcher> { private final Matcher keyMatcher; private final Matcher valueMatcher; public IsMapContaining(Matcher keyMatcher, Matcher valueMatcher) { this.keyMatcher = keyMatcher; this.valueMatcher = valueMatcher; } @Override public boolean matchesSafely(Map map) { for (Entry entry : map.entrySet()) { if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) { return true; } } return false; } @Override public void describeMismatchSafely(Map map, Description mismatchDescription) { mismatchDescription.appendText("map was ").appendValueList("[", ", ", "]", map.entrySet()); } @Override public void describeTo(Description description) { description.appendText("map containing [") .appendDescriptionOf(keyMatcher) .appendText("->") .appendDescriptionOf(valueMatcher) .appendText("]"); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one entry whose key satisfies the specified keyMatcher and whose * value satisfies the specified valueMatcher. * For example: *
assertThat(myMap, hasEntry(equalTo("bar"), equalTo("foo")))
* * @param keyMatcher * the key matcher that, in combination with the valueMatcher, must be satisfied by at least one entry * @param valueMatcher * the value matcher that, in combination with the keyMatcher, must be satisfied by at least one entry */ public static Matcher> hasEntry(Matcher keyMatcher, Matcher valueMatcher) { return new IsMapContaining<>(keyMatcher, valueMatcher); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one entry whose key equals the specified key and whose value equals the * specified value. * For example: *
assertThat(myMap, hasEntry("bar", "foo"))
* * @param key * the key that, in combination with the value, must be describe at least one entry * @param value * the value that, in combination with the key, must be describe at least one entry */ public static Matcher> hasEntry(K key, V value) { return new IsMapContaining<>(equalTo(key), equalTo(value)); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one key that satisfies the specified matcher. * For example: *
assertThat(myMap, hasKey(equalTo("bar")))
* * @param keyMatcher * the matcher that must be satisfied by at least one key */ public static Matcher> hasKey(Matcher keyMatcher) { return new IsMapContaining<>(keyMatcher, anything()); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one key that is equal to the specified key. * For example: *
assertThat(myMap, hasKey("bar"))
* * @param key * the key that satisfying maps must contain */ public static Matcher> hasKey(K key) { return new IsMapContaining<>(equalTo(key), anything()); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one value that satisfies the specified valueMatcher. * For example: *
assertThat(myMap, hasValue(equalTo("foo")))
* * @param valueMatcher * the matcher that must be satisfied by at least one value */ public static Matcher> hasValue(Matcher valueMatcher) { return new IsMapContaining<>(anything(), valueMatcher); } /** * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains * at least one value that is equal to the specified value. * For example: *
assertThat(myMap, hasValue("foo"))
* * @param value * the value that satisfying maps must contain */ public static Matcher> hasValue(V value) { return new IsMapContaining<>(anything(), equalTo(value)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/IsMapWithSize.java000066400000000000000000000037731355170103300302720ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import java.util.Map; import static org.hamcrest.core.IsEqual.equalTo; /** * Matches if map size satisfies a nested matcher. */ public final class IsMapWithSize extends FeatureMatcher, Integer> { @SuppressWarnings("WeakerAccess") public IsMapWithSize(Matcher sizeMatcher) { super(sizeMatcher, "a map with size", "map size"); } @Override protected Integer featureValueOf(Map actual) { return actual.size(); } /** * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns * a value that satisfies the specified matcher. * For example: *
assertThat(myMap, is(aMapWithSize(equalTo(2))))
* * @param sizeMatcher * a matcher for the size of an examined {@link java.util.Map} */ public static Matcher> aMapWithSize(Matcher sizeMatcher) { return new IsMapWithSize<>(sizeMatcher); } /** * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns * a value equal to the specified size. * For example: *
assertThat(myMap, is(aMapWithSize(2)))
* * @param size * the expected size of an examined {@link java.util.Map} */ public static Matcher> aMapWithSize(int size) { return IsMapWithSize.aMapWithSize(equalTo(size)); } /** * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns * zero. * For example: *
assertThat(myMap, is(anEmptyMap()))
* */ public static Matcher> anEmptyMap() { return IsMapWithSize.aMapWithSize(equalTo(0)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/collection/package.html000066400000000000000000000001321355170103300271720ustar00rootroot00000000000000

Matchers of arrays and collections.

JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/comparator/000077500000000000000000000000001355170103300247315ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/comparator/ComparatorMatcherBuilder.java000066400000000000000000000167731355170103300325340ustar00rootroot00000000000000package org.hamcrest.comparator; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Comparator; import static java.lang.Integer.signum; public final class ComparatorMatcherBuilder { private final Comparator comparator; private final boolean includeComparatorInDescription; /** * Creates a matcher factory for matchers of {@code Comparable}s. * For example: *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThanOrEqualTo(1))
*/ public static > ComparatorMatcherBuilder usingNaturalOrdering() { return new ComparatorMatcherBuilder(new Comparator() { @Override public int compare(T o1, T o2) { return o1.compareTo(o2); } }, false); } /** * Creates a matcher factory for matchers of {@code Comparators}s of {@code T}. * For example: *
assertThat(5, comparedBy(new Comparator<Integer>() {
     * public int compare(Integer o1, Integer o2) {
     * return -o1.compareTo(o2);
     * }
     * }).lessThan(4))
*/ public static ComparatorMatcherBuilder comparedBy(Comparator comparator) { return new ComparatorMatcherBuilder(comparator, true); } private ComparatorMatcherBuilder(Comparator comparator, boolean includeComparatorInDescription) { this.comparator = comparator; this.includeComparatorInDescription = includeComparatorInDescription; } private static final class ComparatorMatcher extends TypeSafeMatcher { private static final int LESS_THAN = -1; private static final int GREATER_THAN = 1; private static final int EQUAL = 0; private final Comparator comparator; private final T expected; private final int minCompare; private final int maxCompare; private final boolean includeComparatorInDescription; private static final String[] comparisonDescriptions = { "less than", "equal to", "greater than" }; private ComparatorMatcher(Comparator comparator, T expected, int minCompare, int maxCompare, boolean includeComparatorInDescription) { this.comparator = comparator; this.expected = expected; this.minCompare = minCompare; this.maxCompare = maxCompare; this.includeComparatorInDescription = includeComparatorInDescription; } @Override public boolean matchesSafely(T actual) { try { int compare = signum(comparator.compare(actual, expected)); return minCompare <= compare && compare <= maxCompare; } catch (ClassCastException e) { return false; // type erasure means someone can shonk in a non-T :( } } @Override public void describeMismatchSafely(T actual, Description mismatchDescription) { mismatchDescription.appendValue(actual).appendText(" was ") .appendText(asText(comparator.compare(actual, expected))) .appendText(" ").appendValue(expected); if (includeComparatorInDescription) { mismatchDescription.appendText(" when compared by ").appendValue(comparator); } } @Override public void describeTo(Description description) { description.appendText("a value ").appendText(asText(minCompare)); if (minCompare != maxCompare) { description.appendText(" or ").appendText(asText(maxCompare)); } description.appendText(" ").appendValue(expected); if (includeComparatorInDescription) { description.appendText(" when compared by ").appendValue(comparator); } } private static String asText(int comparison) { return comparisonDescriptions[signum(comparison) + 1]; } } /** * Creates a matcher of {@code T} object that matches when the examined object is * equal to the specified value, as reported by the {@code Comparator} used to * create this builder. * For example: *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().comparesEqualTo(1))
* * @param value the value which, when passed to the Comparator supplied to this builder, should return zero */ public Matcher comparesEqualTo(T value) { return new ComparatorMatcher(comparator, value, ComparatorMatcher.EQUAL, ComparatorMatcher.EQUAL, includeComparatorInDescription); } /** * Creates a matcher of {@code T} object that matches when the examined object is * greater than the specified value, as reported by the {@code Comparator} used to * create this builder. * For example: *
assertThat(2, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().greaterThan(1))
* * @param value the value which, when passed to the Comparator supplied to this builder, should return greater * than zero */ public Matcher greaterThan(T value) { return new ComparatorMatcher(comparator, value, ComparatorMatcher.GREATER_THAN, ComparatorMatcher.GREATER_THAN, includeComparatorInDescription); } /** * Creates a matcher of {@code T} object that matches when the examined object is * greater than or equal to the specified value, as reported by the {@code Comparator} used to * create this builder. * For example: *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().greaterThanOrEqualTo(1))
* * @param value the value which, when passed to the Comparator supplied to this builder, should return greater * than or equal to zero */ public Matcher greaterThanOrEqualTo(T value) { return new ComparatorMatcher(comparator, value, ComparatorMatcher.EQUAL, ComparatorMatcher.GREATER_THAN, includeComparatorInDescription); } /** * Creates a matcher of {@code T} object that matches when the examined object is * less than the specified value, as reported by the {@code Comparator} used to * create this builder. * For example: *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThan(2))
* * @param value the value which, when passed to the Comparator supplied to this builder, should return less * than zero */ public Matcher lessThan(T value) { return new ComparatorMatcher(comparator, value, ComparatorMatcher.LESS_THAN, ComparatorMatcher.LESS_THAN, includeComparatorInDescription); } /** * Creates a matcher of {@code T} object that matches when the examined object is * less than or equal to the specified value, as reported by the {@code Comparator} used to * create this builder. * For example: *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThanOrEqualTo(1))
* * @param value the value which, when passed to the Comparator supplied to this builder, should return less * than or equal to zero */ public Matcher lessThanOrEqualTo(T value) { return new ComparatorMatcher(comparator, value, ComparatorMatcher.LESS_THAN, ComparatorMatcher.EQUAL, includeComparatorInDescription); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/000077500000000000000000000000001355170103300235125ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/AllOf.java000066400000000000000000000035751355170103300253640ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; import org.hamcrest.Matcher; import java.util.Arrays; /** * Calculates the logical conjunction of multiple matchers. Evaluation is shortcut, so * subsequent matchers are not called if an earlier matcher returns false. */ public class AllOf extends DiagnosingMatcher { private final Iterable> matchers; @SafeVarargs public AllOf(Matcher ... matchers) { this(Arrays.asList(matchers)); } public AllOf(Iterable> matchers) { this.matchers = matchers; } @Override public boolean matches(Object o, Description mismatch) { for (Matcher matcher : matchers) { if (!matcher.matches(o)) { mismatch.appendDescriptionOf(matcher).appendText(" "); matcher.describeMismatch(o, mismatch); return false; } } return true; } @Override public void describeTo(Description description) { description.appendList("(", " " + "and" + " ", ")", matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ public static Matcher allOf(Iterable> matchers) { return new AllOf<>(matchers); } /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ @SafeVarargs public static Matcher allOf(Matcher... matchers) { return allOf(Arrays.asList(matchers)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/AnyOf.java000066400000000000000000000027351355170103300254000ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import java.util.Arrays; /** * Calculates the logical disjunction of multiple matchers. Evaluation is shortcut, so * subsequent matchers are not called if an earlier matcher returns true. */ public class AnyOf extends ShortcutCombination { @SafeVarargs public AnyOf(Matcher ... matchers) { this(Arrays.asList(matchers)); } public AnyOf(Iterable> matchers) { super(matchers); } @Override public boolean matches(Object o) { return matches(o, true); } @Override public void describeTo(Description description) { describeTo(description, "or"); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ public static AnyOf anyOf(Iterable> matchers) { return new AnyOf<>(matchers); } /** * Creates a matcher that matches if the examined object matches ANY of the specified matchers. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ @SafeVarargs public static AnyOf anyOf(Matcher... matchers) { return anyOf(Arrays.asList(matchers)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/CombinableMatcher.java000066400000000000000000000050411355170103300277140ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; public class CombinableMatcher extends TypeSafeDiagnosingMatcher { private final Matcher matcher; public CombinableMatcher(Matcher matcher) { this.matcher = matcher; } @Override protected boolean matchesSafely(T item, Description mismatch) { if (!matcher.matches(item)) { matcher.describeMismatch(item, mismatch); return false; } return true; } @Override public void describeTo(Description description) { description.appendDescriptionOf(matcher); } public CombinableMatcher and(Matcher other) { return new CombinableMatcher<>(new AllOf<>(templatedListWith(other))); } public CombinableMatcher or(Matcher other) { return new CombinableMatcher<>(new AnyOf<>(templatedListWith(other))); } private ArrayList> templatedListWith(Matcher other) { ArrayList> matchers = new ArrayList<>(); matchers.add(matcher); matchers.add(other); return matchers; } /** * Creates a matcher that matches when both of the specified matchers match the examined object. * For example: *
assertThat("fab", both(containsString("a")).and(containsString("b")))
*/ public static CombinableBothMatcher both(Matcher matcher) { return new CombinableBothMatcher<>(matcher); } public static final class CombinableBothMatcher { private final Matcher first; public CombinableBothMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher and(Matcher other) { return new CombinableMatcher<>(first).and(other); } } /** * Creates a matcher that matches when either of the specified matchers match the examined object. * For example: *
assertThat("fan", either(containsString("a")).or(containsString("b")))
*/ public static CombinableEitherMatcher either(Matcher matcher) { return new CombinableEitherMatcher<>(matcher); } public static final class CombinableEitherMatcher { private final Matcher first; public CombinableEitherMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher or(Matcher other) { return new CombinableMatcher<>(first).or(other); } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/DescribedAs.java000066400000000000000000000044141355170103300265300ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import java.util.regex.Pattern; import static java.lang.Integer.parseInt; /** * Provides a custom description to another matcher. */ public class DescribedAs extends BaseMatcher { private final String descriptionTemplate; private final Matcher matcher; private final Object[] values; private final static Pattern ARG_PATTERN = Pattern.compile("%([0-9]+)"); public DescribedAs(String descriptionTemplate, Matcher matcher, Object[] values) { this.descriptionTemplate = descriptionTemplate; this.matcher = matcher; this.values = values.clone(); } @Override public boolean matches(Object o) { return matcher.matches(o); } @Override public void describeTo(Description description) { java.util.regex.Matcher arg = ARG_PATTERN.matcher(descriptionTemplate); int textStart = 0; while (arg.find()) { description.appendText(descriptionTemplate.substring(textStart, arg.start())); description.appendValue(values[parseInt(arg.group(1))]); textStart = arg.end(); } if (textStart < descriptionTemplate.length()) { description.appendText(descriptionTemplate.substring(textStart)); } } @Override public void describeMismatch(Object item, Description description) { matcher.describeMismatch(item, description); } /** * Wraps an existing matcher, overriding its description with that specified. All other functions are * delegated to the decorated matcher, including its mismatch description. * For example: *
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
* * @param description * the new description for the wrapped matcher * @param matcher * the matcher to wrap * @param values * optional values to insert into the tokenised description */ public static Matcher describedAs(String description, Matcher matcher, Object... values) { return new DescribedAs(description, matcher, values); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/Every.java000066400000000000000000000027341355170103300254550ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; public class Every extends TypeSafeDiagnosingMatcher> { private final Matcher matcher; public Every(Matcher matcher) { this.matcher= matcher; } @Override public boolean matchesSafely(Iterable collection, Description mismatchDescription) { for (T t : collection) { if (!matcher.matches(t)) { mismatchDescription.appendText("an item "); matcher.describeMismatch(t, mismatchDescription); return false; } } return true; } @Override public void describeTo(Description description) { description.appendText("every item is ").appendDescriptionOf(matcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields items that are all matched by the specified * itemMatcher. * For example: *
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to every item provided by the examined {@link Iterable} */ public static Matcher> everyItem(final Matcher itemMatcher) { return new Every<>(itemMatcher); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/Is.java000066400000000000000000000040341355170103300247310ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import static org.hamcrest.core.IsEqual.equalTo; /** * Decorates another Matcher, retaining the behaviour but allowing tests * to be slightly more expressive. * * For example: assertThat(cheese, equalTo(smelly)) * vs. assertThat(cheese, is(equalTo(smelly))) */ public class Is extends BaseMatcher { private final Matcher matcher; public Is(Matcher matcher) { this.matcher = matcher; } @Override public boolean matches(Object arg) { return matcher.matches(arg); } @Override public void describeTo(Description description) { description.appendText("is ").appendDescriptionOf(matcher); } @Override public void describeMismatch(Object item, Description mismatchDescription) { matcher.describeMismatch(item, mismatchDescription); } /** * Decorates another Matcher, retaining its behaviour, but allowing tests * to be slightly more expressive. * For example: *
assertThat(cheese, is(equalTo(smelly)))
* instead of: *
assertThat(cheese, equalTo(smelly))
* */ public static Matcher is(Matcher matcher) { return new Is<>(matcher); } /** * A shortcut to the frequently used is(equalTo(x)). * For example: *
assertThat(cheese, is(smelly))
* instead of: *
assertThat(cheese, is(equalTo(smelly)))
* */ public static Matcher is(T value) { return is(equalTo(value)); } /** * A shortcut to the frequently used is(instanceOf(SomeClass.class)). * For example: *
assertThat(cheese, isA(Cheddar.class))
* instead of: *
assertThat(cheese, is(instanceOf(Cheddar.class)))
* */ public static Matcher isA(Class type) { return is(IsInstanceOf.instanceOf(type)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsAnything.java000066400000000000000000000022111355170103300264260ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; /** * A matcher that always returns true. */ public class IsAnything extends BaseMatcher { private final String message; public IsAnything() { this("ANYTHING"); } public IsAnything(String message) { this.message = message; } @Override public boolean matches(Object o) { return true; } @Override public void describeTo(Description description) { description.appendText(message); } /** * Creates a matcher that always matches, regardless of the examined object. */ public static Matcher anything() { return new IsAnything<>(); } /** * Creates a matcher that always matches, regardless of the examined object, but describes * itself with the specified {@link String}. * * @param description * a meaningful {@link String} used when describing itself */ public static Matcher anything(String description) { return new IsAnything<>(description); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsCollectionContaining.java000066400000000000000000000102721355170103300307600ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; /** * @deprecated As of release 2.1, replaced by {@link IsIterableContaining}. */ @Deprecated public class IsCollectionContaining extends TypeSafeDiagnosingMatcher> { private final IsIterableContaining delegate; public IsCollectionContaining(Matcher elementMatcher) { this.delegate = new IsIterableContaining<>(elementMatcher); } @Override protected boolean matchesSafely(Iterable collection, Description mismatchDescription) { return delegate.matchesSafely(collection, mismatchDescription); } @Override public void describeTo(Description description) { delegate.describeTo(description); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is matched by the specified * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
* * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItem(Matcher)}. * * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ public static Matcher> hasItem(Matcher itemMatcher) { return IsIterableContaining.hasItem(itemMatcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is equal to the specified * item. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
* * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItem(Object)}. * * @param item * the item to compare against the items provided by the examined {@link Iterable} */ public static Matcher> hasItem(T item) { // Doesn't forward to hasItem() method so compiler can sort out generics. return IsIterableContaining.hasItem(item); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is matched by the corresponding * matcher from the specified itemMatchers. Whilst matching, each traversal of * the examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
* * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItems(Matcher[])}}. * * @param itemMatchers * the matchers to apply to items provided by the examined {@link Iterable} */ @SafeVarargs public static Matcher> hasItems(Matcher... itemMatchers) { return IsIterableContaining.hasItems(itemMatchers); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is equal to the corresponding * item from the specified items. Whilst matching, each traversal of the * examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
* * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItems(Object[])}}. * * @param items * the items to compare against the items provided by the examined {@link Iterable} */ @SafeVarargs public static Matcher> hasItems(T... items) { return IsIterableContaining.hasItems(items); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsEqual.java000066400000000000000000000065111355170103300257230ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import java.lang.reflect.Array; /** * Is the value equal to another value, as tested by the * {@link java.lang.Object#equals} invokedMethod? */ public class IsEqual extends BaseMatcher { private final Object expectedValue; public IsEqual(T equalArg) { expectedValue = equalArg; } @Override public boolean matches(Object actualValue) { return areEqual(actualValue, expectedValue); } @Override public void describeTo(Description description) { description.appendValue(expectedValue); } private static boolean areEqual(Object actual, Object expected) { if (actual == null) { return expected == null; } if (expected != null && isArray(actual)) { return isArray(expected) && areArraysEqual(actual, expected); } return actual.equals(expected); } private static boolean areArraysEqual(Object actualArray, Object expectedArray) { return areArrayLengthsEqual(actualArray, expectedArray) && areArrayElementsEqual(actualArray, expectedArray); } private static boolean areArrayLengthsEqual(Object actualArray, Object expectedArray) { return Array.getLength(actualArray) == Array.getLength(expectedArray); } private static boolean areArrayElementsEqual(Object actualArray, Object expectedArray) { for (int i = 0; i < Array.getLength(actualArray); i++) { if (!areEqual(Array.get(actualArray, i), Array.get(expectedArray, i))) { return false; } } return true; } private static boolean isArray(Object o) { return o.getClass().isArray(); } /** * Creates a matcher that matches when the examined object is logically equal to the specified * operand, as determined by calling the {@link java.lang.Object#equals} method on * the examined object. * *

If the specified operand is null then the created matcher will only match if * the examined object's equals method returns true when passed a * null (which would be a violation of the equals contract), unless the * examined object itself is null, in which case the matcher will return a positive * match.

* *

The created matcher provides a special behaviour when examining Arrays, whereby * it will match if both the operand and the examined object are arrays of the same length and * contain items that are equal to each other (according to the above rules) in the same * indexes.

* For example: *
     * assertThat("foo", equalTo("foo"));
     * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
     * 
* */ public static Matcher equalTo(T operand) { return new IsEqual<>(operand); } /** * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being * compared to be of the same static type. */ public static Matcher equalToObject(Object operand) { return new IsEqual<>(operand); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsInstanceOf.java000066400000000000000000000064621355170103300267120ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; import org.hamcrest.Matcher; /** * Tests whether the value is an instance of a class. * Classes of basic types will be converted to the relevant "Object" classes */ public class IsInstanceOf extends DiagnosingMatcher { private final Class expectedClass; private final Class matchableClass; /** * Creates a new instance of IsInstanceOf * * @param expectedClass The predicate evaluates to true for instances of this class * or one of its subclasses. */ public IsInstanceOf(Class expectedClass) { this.expectedClass = expectedClass; this.matchableClass = matchableClass(expectedClass); } private static Class matchableClass(Class expectedClass) { if (boolean.class.equals(expectedClass)) return Boolean.class; if (byte.class.equals(expectedClass)) return Byte.class; if (char.class.equals(expectedClass)) return Character.class; if (double.class.equals(expectedClass)) return Double.class; if (float.class.equals(expectedClass)) return Float.class; if (int.class.equals(expectedClass)) return Integer.class; if (long.class.equals(expectedClass)) return Long.class; if (short.class.equals(expectedClass)) return Short.class; return expectedClass; } @Override protected boolean matches(Object item, Description mismatch) { if (null == item) { mismatch.appendText("null"); return false; } if (!matchableClass.isInstance(item)) { mismatch.appendValue(item).appendText(" is a " + item.getClass().getName()); return false; } return true; } @Override public void describeTo(Description description) { description.appendText("an instance of ").appendText(expectedClass.getName()); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher assumes no relationship between specified type and the examined object.

* For example: *
assertThat(new Canoe(), instanceOf(Paddlable.class));
* */ @SuppressWarnings("unchecked") public static Matcher instanceOf(Class type) { return (Matcher) new IsInstanceOf(type); } /** * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. * *

The created matcher forces a relationship between specified type and the examined object, and should be * used when it is necessary to make generics conform, for example in the JMock clause * with(any(Thing.class))

* For example: *
assertThat(new Canoe(), instanceOf(Canoe.class));
* */ @SuppressWarnings("unchecked") public static Matcher any(Class type) { return (Matcher) new IsInstanceOf(type); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsIterableContaining.java000066400000000000000000000120571355170103300304170ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; import java.util.List; import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableContaining extends TypeSafeDiagnosingMatcher> { private final Matcher elementMatcher; public IsIterableContaining(Matcher elementMatcher) { this.elementMatcher = elementMatcher; } @Override protected boolean matchesSafely(Iterable collection, Description mismatchDescription) { if (isEmpty(collection)) { mismatchDescription.appendText("was empty"); return false; } for (Object item : collection) { if (elementMatcher.matches(item)) { return true; } } mismatchDescription.appendText("mismatches were: ["); boolean isPastFirst = false; for (Object item : collection) { if (isPastFirst) { mismatchDescription.appendText(", "); } elementMatcher.describeMismatch(item, mismatchDescription); isPastFirst = true; } mismatchDescription.appendText("]"); return false; } private boolean isEmpty(Iterable iterable) { return ! iterable.iterator().hasNext(); } @Override public void describeTo(Description description) { description .appendText("a collection containing ") .appendDescriptionOf(elementMatcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is matched by the specified * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
* * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ public static Matcher> hasItem(Matcher itemMatcher) { return new IsIterableContaining<>(itemMatcher); } /** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is equal to the specified * item. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
* * @param item * the item to compare against the items provided by the examined {@link Iterable} */ public static Matcher> hasItem(T item) { // Doesn't forward to hasItem() method so compiler can sort out generics. return new IsIterableContaining<>(equalTo(item)); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is matched by the corresponding * matcher from the specified itemMatchers. Whilst matching, each traversal of * the examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
* * @param itemMatchers * the matchers to apply to items provided by the examined {@link Iterable} */ @SafeVarargs public static Matcher> hasItems(Matcher... itemMatchers) { List>> all = new ArrayList<>(itemMatchers.length); for (Matcher elementMatcher : itemMatchers) { // Doesn't forward to hasItem() method so compiler can sort out generics. all.add(new IsIterableContaining<>(elementMatcher)); } return allOf(all); } /** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is equal to the corresponding * item from the specified items. Whilst matching, each traversal of the * examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
* * @param items * the items to compare against the items provided by the examined {@link Iterable} */ @SafeVarargs public static Matcher> hasItems(T... items) { List>> all = new ArrayList<>(items.length); for (T item : items) { all.add(hasItem(item)); } return allOf(all); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsNot.java000066400000000000000000000027041355170103300254140ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import static org.hamcrest.core.IsEqual.equalTo; /** * Calculates the logical negation of a matcher. */ public class IsNot extends BaseMatcher { private final Matcher matcher; public IsNot(Matcher matcher) { this.matcher = matcher; } @Override public boolean matches(Object arg) { return !matcher.matches(arg); } @Override public void describeTo(Description description) { description.appendText("not ").appendDescriptionOf(matcher); } /** * Creates a matcher that wraps an existing matcher, but inverts the logic by which * it will match. * For example: *
assertThat(cheese, is(not(equalTo(smelly))))
* * @param matcher * the matcher whose sense should be inverted */ public static Matcher not(Matcher matcher) { return new IsNot(matcher); } /** * A shortcut to the frequently used not(equalTo(x)). * For example: *
assertThat(cheese, is(not(smelly)))
* instead of: *
assertThat(cheese, is(not(equalTo(smelly))))
* * @param value * the value that any examined object should not equal */ public static Matcher not(T value) { return not(equalTo(value)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsNull.java000066400000000000000000000040331355170103300255630ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import static org.hamcrest.core.IsNot.not; /** * Is the value null? */ public class IsNull extends BaseMatcher { @Override public boolean matches(Object o) { return o == null; } @Override public void describeTo(Description description) { description.appendText("null"); } /** * Creates a matcher that matches if examined object is null. * For example: *
assertThat(cheese, is(nullValue())
* */ public static Matcher nullValue() { return new IsNull(); } /** * A shortcut to the frequently used not(nullValue()). * For example: *
assertThat(cheese, is(notNullValue()))
* instead of: *
assertThat(cheese, is(not(nullValue())))
* */ public static Matcher notNullValue() { return not(nullValue()); } /** * Creates a matcher that matches if examined object is null. Accepts a * single dummy argument to facilitate type inference. * For example: *
assertThat(cheese, is(nullValue(Cheese.class))
* * @param type * dummy parameter used to infer the generic type of the returned matcher */ public static Matcher nullValue(Class type) { return new IsNull(); } /** * A shortcut to the frequently used not(nullValue(X.class)). Accepts a * single dummy argument to facilitate type inference.. * For example: *
assertThat(cheese, is(notNullValue(X.class)))
* instead of: *
assertThat(cheese, is(not(nullValue(X.class))))
* * @param type * dummy parameter used to infer the generic type of the returned matcher * */ public static Matcher notNullValue(Class type) { return not(nullValue(type)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/IsSame.java000066400000000000000000000024451355170103300255430ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; /** * Is the value the same object as another value? */ public class IsSame extends BaseMatcher { private final T object; public IsSame(T object) { this.object = object; } @Override public boolean matches(Object arg) { return arg == object; } @Override public void describeTo(Description description) { description.appendText("sameInstance(") .appendValue(object) .appendText(")"); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ public static Matcher sameInstance(T target) { return new IsSame(target); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. * * @param target * the target instance against which others should be assessed */ public static Matcher theInstance(T target) { return new IsSame(target); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/ShortcutCombination.java000066400000000000000000000016311355170103300303540ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; abstract class ShortcutCombination extends BaseMatcher { private final Iterable> matchers; public ShortcutCombination(Iterable> matchers) { this.matchers = matchers; } @Override public abstract boolean matches(Object o); @Override public abstract void describeTo(Description description); protected boolean matches(Object o, boolean shortcut) { for (Matcher matcher : matchers) { if (matcher.matches(o) == shortcut) { return shortcut; } } return !shortcut; } public void describeTo(Description description, String operator) { description.appendList("(", " " + operator + " ", ")", matchers); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/StringContains.java000066400000000000000000000030311355170103300273170ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; /** * Tests if the argument is a string that contains a specific substring. */ public class StringContains extends SubstringMatcher { public StringContains(String substring) { this(false, substring); } public StringContains(boolean ignoringCase, String substring) { super("containing", ignoringCase, substring); } @Override protected boolean evalSubstringOf(String s) { return converted(s).contains(converted(substring)); } /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere. * For example: *
assertThat("myStringOfNote", containsString("ring"))
* * @param substring * the substring that the returned matcher will expect to find within any examined string * */ public static Matcher containsString(String substring) { return new StringContains(false, substring); } /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere, ignoring case. * For example: *
assertThat("myStringOfNote", containsStringIgnoringCase("Ring"))
* * @param substring * the substring that the returned matcher will expect to find within any examined string * */ public static Matcher containsStringIgnoringCase(String substring) { return new StringContains(true, substring); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/StringEndsWith.java000066400000000000000000000027061355170103300272760ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; /** * Tests if the argument is a string that ends with a specific substring. */ public class StringEndsWith extends SubstringMatcher { public StringEndsWith(String substring) { this(false, substring); } public StringEndsWith(boolean ignoringCase, String substring) { super("ending with", ignoringCase, substring); } @Override protected boolean evalSubstringOf(String s) { return converted(s).endsWith(converted(substring)); } /** * Creates a matcher that matches if the examined {@link String} ends with the specified * {@link String}. * For example: *
assertThat("myStringOfNote", endsWith("Note"))
* * @param suffix * the substring that the returned matcher will expect at the end of any examined string */ public static Matcher endsWith(String suffix) { return new StringEndsWith(false, suffix); } /** * Creates a matcher that matches if the examined {@link String} ends with the specified * {@link String}, ignoring case. * For example: *
assertThat("myStringOfNote", endsWithIgnoringCase("note"))
* * @param suffix * the substring that the returned matcher will expect at the end of any examined string */ public static Matcher endsWithIgnoringCase(String suffix) { return new StringEndsWith(true, suffix); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/StringRegularExpression.java000066400000000000000000000032671355170103300312350ustar00rootroot00000000000000/** * */ package org.hamcrest.core; import java.util.regex.Pattern; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; /** * @author borettim * @author sf105 * */ public class StringRegularExpression extends TypeSafeDiagnosingMatcher { protected StringRegularExpression(Pattern pattern) { this.pattern = pattern; } private Pattern pattern; @Override public void describeTo(Description description) { description.appendText("a string matching the pattern ").appendValue(pattern); } @Override protected boolean matchesSafely(String actual, Description mismatchDescription) { if (!pattern.matcher(actual).matches()) { mismatchDescription.appendText("the string was ").appendValue(actual); return false; } return true; } /** * Creates a matcher that checks if the examined string matches a specified {@link java.util.regex.Pattern}. * *
   * assertThat("abc", matchesRegex(Pattern.compile("ˆ[a-z]$"));
   * 
* * @param pattern * the pattern to be used. * @return The matcher. */ public static Matcher matchesRegex(Pattern pattern) { return new StringRegularExpression(pattern); } /** * Creates a matcher that checks if the examined string matches a specified regex. * *
   * assertThat("abc", matchesRegex("ˆ[a-z]+$"));
   * 
* * @param regex * The regex to be used for the validation. * @return The matcher. */ public static Matcher matchesRegex(String regex) { return matchesRegex(Pattern.compile(regex)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java000066400000000000000000000027531355170103300276670ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; /** * Tests if the argument is a string that starts with a specific substring. */ public class StringStartsWith extends SubstringMatcher { public StringStartsWith(String substring) { this(false, substring); } public StringStartsWith(boolean ignoringCase, String substring) { super("starting with", ignoringCase, substring); } @Override protected boolean evalSubstringOf(String s) { return converted(s).startsWith(converted(substring)); } /** *

* Creates a matcher that matches if the examined {@link String} starts with the specified * {@link String}. *

* For example: *
assertThat("myStringOfNote", startsWith("my"))
* * @param prefix * the substring that the returned matcher will expect at the start of any examined string */ public static Matcher startsWith(String prefix) { return new StringStartsWith(false, prefix); } /** *

* Creates a matcher that matches if the examined {@link String} starts with the specified * {@link String}, ignoring case *

* For example: *
assertThat("myStringOfNote", startsWithIgnoringCase("My"))
* * @param prefix * the substring that the returned matcher will expect at the start of any examined string */ public static Matcher startsWithIgnoringCase(String prefix) { return new StringStartsWith(true, prefix); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/SubstringMatcher.java000066400000000000000000000031111355170103300276350ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public abstract class SubstringMatcher extends TypeSafeMatcher { // TODO: Replace String with CharSequence to allow for easy interoperability between // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). private final String relationship; private final boolean ignoringCase; protected final String substring; protected SubstringMatcher(String relationship, boolean ignoringCase, String substring) { this.relationship = relationship; this.ignoringCase = ignoringCase; this.substring = substring; if (null == substring) { throw new IllegalArgumentException("missing substring"); } } @Override public boolean matchesSafely(String item) { return evalSubstringOf(ignoringCase ? item.toLowerCase() :item); } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was \"").appendText(item).appendText("\""); } @Override public void describeTo(Description description) { description.appendText("a string ") .appendText(relationship) .appendText(" ") .appendValue(substring); if (ignoringCase) { description.appendText(" ignoring case"); } } protected String converted(String arg) { return ignoringCase ? arg.toLowerCase() : arg; } protected abstract boolean evalSubstringOf(String string); } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/core/package.html000066400000000000000000000001721355170103300257730ustar00rootroot00000000000000

Fundamental matchers of objects and values, and composite matchers.

JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/internal/000077500000000000000000000000001355170103300243765ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/internal/ArrayIterator.java000066400000000000000000000013671355170103300300400ustar00rootroot00000000000000package org.hamcrest.internal; import java.lang.reflect.Array; import java.util.Iterator; public class ArrayIterator implements Iterator { private final Object array; private int currentIndex = 0; public ArrayIterator(Object array) { if (!array.getClass().isArray()) { throw new IllegalArgumentException("not an array"); } this.array = array; } @Override public boolean hasNext() { return currentIndex < Array.getLength(array); } @Override public Object next() { return Array.get(array, currentIndex++); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove items from an array"); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/internal/NullSafety.java000066400000000000000000000011571355170103300273330ustar00rootroot00000000000000package org.hamcrest.internal; import org.hamcrest.Matcher; import org.hamcrest.core.IsNull; import java.util.ArrayList; import java.util.List; public class NullSafety { @SuppressWarnings("unchecked") public static List> nullSafe(Matcher[] itemMatchers) { final List> matchers = new ArrayList>(itemMatchers.length); for (final Matcher itemMatcher : itemMatchers) { matchers.add((Matcher) (itemMatcher == null ? IsNull.nullValue() : itemMatcher)); } return matchers; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/internal/ReflectiveTypeFinder.java000066400000000000000000000060461355170103300313310ustar00rootroot00000000000000/** * The TypeSafe classes, and their descendants, need a mechanism to find out what type has been used as a parameter * for the concrete matcher. Unfortunately, this type is lost during type erasure so we need to use reflection * to get it back, by picking out the type of a known parameter to a known method. * The catch is that, with bridging methods, this type is only visible in the class that actually implements * the expected method, so the ReflectiveTypeFinder needs to be applied to that class or a subtype. * * For example, the abstract TypeSafeDiagnosingMatcher<T> defines an abstract method *
protected abstract boolean matchesSafely(T item, Description mismatchDescription);
* By default it uses new ReflectiveTypeFinder("matchesSafely", 2, 0); to find the * parameterised type. If we create a TypeSafeDiagnosingMatcher<String>, the type * finder will return String.class. * * A FeatureMatcher is an abstract subclass of TypeSafeDiagnosingMatcher. * Although it has a templated implementation of matchesSafely(<T>, Description);, the * actual run-time signature of this is matchesSafely(Object, Description);. Instead, * we must find the type by reflecting on the concrete implementation of *
protected abstract U featureValueOf(T actual);
* a method which is declared in FeatureMatcher. * * In short, use this to extract a type from a method in the leaf class of a templated class hierarchy. * * @author Steve Freeman * @author Nat Pryce */ package org.hamcrest.internal; import java.lang.reflect.Method; public class ReflectiveTypeFinder { private final String methodName; private final int expectedNumberOfParameters; private final int typedParameter; public ReflectiveTypeFinder(String methodName, int expectedNumberOfParameters, int typedParameter) { this.methodName = methodName; this.expectedNumberOfParameters = expectedNumberOfParameters; this.typedParameter = typedParameter; } public Class findExpectedType(Class fromClass) { for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) { for (Method method : c.getDeclaredMethods()) { if (canObtainExpectedTypeFrom(method)) { return expectedTypeFrom(method); } } } throw new Error("Cannot determine correct type for " + methodName + "() method."); } /** * @param method The method to examine. * @return true if this method references the relevant type */ private boolean canObtainExpectedTypeFrom(Method method) { return method.getName().equals(methodName) && method.getParameterTypes().length == expectedNumberOfParameters && !method.isSynthetic(); } /** * @param method The method from which to extract * @return The type we're looking for */ private Class expectedTypeFrom(Method method) { return method.getParameterTypes()[typedParameter]; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValue.java000066400000000000000000000006011355170103300311160ustar00rootroot00000000000000package org.hamcrest.internal; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; public class SelfDescribingValue implements SelfDescribing { private T value; public SelfDescribingValue(T value) { this.value = value; } @Override public void describeTo(Description description) { description.appendValue(value); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.java000066400000000000000000000011171355170103300326330ustar00rootroot00000000000000package org.hamcrest.internal; import org.hamcrest.SelfDescribing; import java.util.Iterator; public class SelfDescribingValueIterator implements Iterator { private Iterator values; public SelfDescribingValueIterator(Iterator values) { this.values = values; } @Override public boolean hasNext() { return values.hasNext(); } @Override public SelfDescribing next() { return new SelfDescribingValue(values.next()); } @Override public void remove() { values.remove(); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/io/000077500000000000000000000000001355170103300231715ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/io/FileMatchers.java000066400000000000000000000076441355170103300264150ustar00rootroot00000000000000package org.hamcrest.io; import org.hamcrest.Description; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.io.File; import java.io.IOException; import static org.hamcrest.core.IsEqual.equalTo; public final class FileMatchers { public static Matcher anExistingDirectory() { return fileChecker(IS_DIRECTORY, "an existing directory", "is not a directory"); } public static Matcher anExistingFileOrDirectory() { return fileChecker(EXISTS, "an existing file or directory", "does not exist"); } public static Matcher anExistingFile() { return fileChecker(IS_FILE, "an existing File", "is not a file"); } public static Matcher aReadableFile() { return fileChecker(CAN_READ, "a readable File", "cannot be read"); } public static Matcher aWritableFile() { return fileChecker(CAN_WRITE, "a writable File", "cannot be written to"); } public static Matcher aFileWithSize(long size) { return aFileWithSize(equalTo(size)); } public static Matcher aFileWithSize(final Matcher expected) { return new FeatureMatcher(expected, "A file with size", "size") { @Override protected Long featureValueOf(File actual) { return actual.length(); } }; } public static Matcher aFileNamed(final Matcher expected) { return new FeatureMatcher(expected, "A file with name", "name") { @Override protected String featureValueOf(File actual) { return actual.getName(); } }; } public static Matcher aFileWithCanonicalPath(final Matcher expected) { return new FeatureMatcher(expected, "A file with canonical path", "path") { @Override protected String featureValueOf(File actual) { try { return actual.getCanonicalPath(); } catch (IOException e) { return "Exception: " + e.getMessage(); } } }; } public static Matcher aFileWithAbsolutePath(final Matcher expected) { return new FeatureMatcher(expected, "A file with absolute path", "path") { @Override protected String featureValueOf(File actual) { return actual.getAbsolutePath(); } }; } public static interface FileStatus { boolean check(File actual); } public static final FileStatus CAN_WRITE = new FileStatus() { @Override public boolean check(File actual) { return actual.canWrite(); } }; public static final FileStatus CAN_READ = new FileStatus() { @Override public boolean check(File actual) { return actual.canRead(); } }; public static final FileStatus IS_FILE = new FileStatus() { @Override public boolean check(File actual) { return actual.isFile(); } }; public static final FileStatus IS_DIRECTORY = new FileStatus() { @Override public boolean check(File actual) { return actual.isDirectory(); } }; public static final FileStatus EXISTS = new FileStatus() { @Override public boolean check(File actual) { return actual.exists(); } }; private static Matcher fileChecker(final FileStatus fileStatus, final String successDescription, final String failureDescription) { return new TypeSafeDiagnosingMatcher() { public boolean matchesSafely(File actual, Description mismatchDescription) { final boolean result = fileStatus.check(actual); if (!result) { mismatchDescription.appendText(failureDescription); } return result; } public void describeTo(Description description) { description.appendText(successDescription); } }; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/number/000077500000000000000000000000001355170103300240525ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java000066400000000000000000000040321355170103300301650ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.math.BigDecimal; import java.math.MathContext; public class BigDecimalCloseTo extends TypeSafeMatcher { private final BigDecimal delta; private final BigDecimal value; public BigDecimalCloseTo(BigDecimal value, BigDecimal error) { this.delta = error; this.value = value; } @Override public boolean matchesSafely(BigDecimal item) { return actualDelta(item).compareTo(BigDecimal.ZERO) <= 0; } @Override public void describeMismatchSafely(BigDecimal item, Description mismatchDescription) { mismatchDescription.appendValue(item) .appendText(" differed by ") .appendValue(actualDelta(item)) .appendText(" more than delta ") .appendValue(delta); } @Override public void describeTo(Description description) { description.appendText("a numeric value within ") .appendValue(delta) .appendText(" of ") .appendValue(value); } private BigDecimal actualDelta(BigDecimal item) { return item.subtract(value, MathContext.DECIMAL128).abs().subtract(delta, MathContext.DECIMAL128).stripTrailingZeros(); } /** * Creates a matcher of {@link java.math.BigDecimal}s that matches when an examined BigDecimal is equal * to the specified operand, within a range of +/- error. The comparison for equality * is done by BigDecimals {@link java.math.BigDecimal#compareTo(java.math.BigDecimal)} method. * For example: *
assertThat(new BigDecimal("1.03"), is(closeTo(new BigDecimal("1.0"), new BigDecimal("0.03"))))
* * @param operand * the expected value of matching BigDecimals * @param error * the delta (+/-) within which matches will be allowed */ public static Matcher closeTo(BigDecimal operand, BigDecimal error) { return new BigDecimalCloseTo(operand, error); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/number/IsCloseTo.java000066400000000000000000000035171355170103300265670ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import static java.lang.Math.abs; /** * Is the value a number equal to a value within some range of * acceptable error? */ public class IsCloseTo extends TypeSafeMatcher { private final double delta; private final double value; public IsCloseTo(double value, double error) { this.delta = error; this.value = value; } @Override public boolean matchesSafely(Double item) { return actualDelta(item) <= 0.0; } @Override public void describeMismatchSafely(Double item, Description mismatchDescription) { mismatchDescription.appendValue(item) .appendText(" differed by ") .appendValue(actualDelta(item)) .appendText(" more than delta ") .appendValue(delta); } @Override public void describeTo(Description description) { description.appendText("a numeric value within ") .appendValue(delta) .appendText(" of ") .appendValue(value); } private double actualDelta(Double item) { return abs(item - value) - delta; } /** * Creates a matcher of {@link Double}s that matches when an examined double is equal * to the specified operand, within a range of +/- error. * For example: *
assertThat(1.03, is(closeTo(1.0, 0.03)))
* * @param operand * the expected value of matching doubles * @param error * the delta (+/-) within which matches will be allowed */ public static Matcher closeTo(double operand, double error) { return new IsCloseTo(operand, error); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/number/IsNaN.java000066400000000000000000000017061355170103300256710ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Is the value a number actually not a number (NaN)? */ public final class IsNaN extends TypeSafeMatcher { private IsNaN() { } @Override public boolean matchesSafely(Double item) { return Double.isNaN(item); } @Override public void describeMismatchSafely(Double item, Description mismatchDescription) { mismatchDescription.appendText("was ").appendValue(item); } @Override public void describeTo(Description description) { description.appendText("a double value of NaN"); } /** * Creates a matcher of {@link Double}s that matches when an examined double is not a number. * For example: *
assertThat(Double.NaN, is(notANumber()))
*/ public static Matcher notANumber() { return new IsNaN(); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/number/OrderingComparison.java000066400000000000000000000065241355170103300305300ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.Matcher; import org.hamcrest.comparator.ComparatorMatcherBuilder; public class OrderingComparison { private OrderingComparison() { } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * equal to the specified value, as reported by the compareTo method of the * examined object. * For example: *
assertThat(1, comparesEqualTo(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return zero */ public static > Matcher comparesEqualTo(T value) { return ComparatorMatcherBuilder.usingNaturalOrdering().comparesEqualTo(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * greater than the specified value, as reported by the compareTo method of the * examined object. * For example: *
assertThat(2, greaterThan(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return greater * than zero */ public static > Matcher greaterThan(T value) { return ComparatorMatcherBuilder.usingNaturalOrdering().greaterThan(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * greater than or equal to the specified value, as reported by the compareTo method * of the examined object. * For example: *
assertThat(1, greaterThanOrEqualTo(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return greater * than or equal to zero */ public static > Matcher greaterThanOrEqualTo(T value) { return ComparatorMatcherBuilder.usingNaturalOrdering().greaterThanOrEqualTo(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * less than the specified value, as reported by the compareTo method of the * examined object. * For example: *
assertThat(1, lessThan(2))
* * @param value the value which, when passed to the compareTo method of the examined object, should return less * than zero */ public static > Matcher lessThan(T value) { return ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(value); } /** * Creates a matcher of {@link Comparable} object that matches when the examined object is * less than or equal to the specified value, as reported by the compareTo method * of the examined object. * For example: *
assertThat(1, lessThanOrEqualTo(1))
* * @param value the value which, when passed to the compareTo method of the examined object, should return less * than or equal to zero */ public static > Matcher lessThanOrEqualTo(T value) { return ComparatorMatcherBuilder.usingNaturalOrdering().lessThanOrEqualTo(value); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/number/package.html000066400000000000000000000001411355170103300263270ustar00rootroot00000000000000

Matchers that perform numeric comparisons.

JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/object/000077500000000000000000000000001355170103300240305ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/object/HasEqualValues.java000066400000000000000000000054161355170103300275640ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.core.IsEqual; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import static java.lang.String.format; public class HasEqualValues extends TypeSafeDiagnosingMatcher { private final T expectedObject; private final List fieldMatchers; public HasEqualValues(T expectedObject) { super(expectedObject.getClass()); this.expectedObject = expectedObject; this.fieldMatchers = fieldMatchers(expectedObject); } @Override protected boolean matchesSafely(T item, Description mismatch) { for (FieldMatcher fieldMatcher : fieldMatchers) { if (!fieldMatcher.matches(item, mismatch)) { return false; } } return true; } @Override public void describeTo(Description description) { description.appendText(expectedObject.getClass().getSimpleName()) .appendText(" has values ") .appendList("[", ", ", "]", fieldMatchers); } private static class FieldMatcher extends DiagnosingMatcher { private final Field field; private final Matcher matcher; public FieldMatcher(Field field, Object expectedObject) { this.field = field; this.matcher = IsEqual.equalTo(uncheckedGet(field, expectedObject)); } @Override protected boolean matches(Object item, Description mismatch) { final Object actual = uncheckedGet(field, item); if (!matcher.matches(actual)) { mismatch.appendText("'").appendText(field.getName()).appendText("' "); matcher.describeMismatch(actual, mismatch); return false; } return true; } @Override public void describeTo(Description description) { description.appendText(field.getName()) .appendText(": ") .appendDescriptionOf(matcher); } } private static List fieldMatchers(Object expectedObject) { final List result = new ArrayList<>(); for (Field field : expectedObject.getClass().getFields()) { result.add(new FieldMatcher(field, expectedObject)); } return result; } private static Object uncheckedGet(Field field, Object object) { try { return field.get(object); } catch (Exception e) { throw new AssertionError(format("IllegalAccess, reading field '%s' from %s", field.getName(), object)); } } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/object/HasToString.java000066400000000000000000000026051355170103300271030ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import static org.hamcrest.core.IsEqual.equalTo; public class HasToString extends FeatureMatcher { public HasToString(Matcher toStringMatcher) { super(toStringMatcher, "with toString()", "toString()"); } @Override protected String featureValueOf(T actual) { return String.valueOf(actual); } /** * Creates a matcher that matches any examined object whose toString method * returns a value that satisfies the specified matcher. * For example: *
assertThat(true, hasToString(equalTo("TRUE")))
* * @param toStringMatcher * the matcher used to verify the toString result */ public static Matcher hasToString(Matcher toStringMatcher) { return new HasToString(toStringMatcher); } /** * Creates a matcher that matches any examined object whose toString method * returns a value equalTo the specified string. * For example: *
assertThat(true, hasToString("TRUE"))
* * @param expectedToString * the expected toString result */ public static Matcher hasToString(String expectedToString) { return new HasToString(equalTo(expectedToString)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/object/IsCompatibleType.java000066400000000000000000000023011355170103300301040ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class IsCompatibleType extends TypeSafeMatcher> { private final Class type; public IsCompatibleType(Class type) { this.type = type; } @Override public boolean matchesSafely(Class cls) { return type.isAssignableFrom(cls); } @Override public void describeMismatchSafely(Class cls, Description mismatchDescription) { mismatchDescription.appendValue(cls.getName()); } @Override public void describeTo(Description description) { description.appendText("type < ").appendText(type.getName()); } /** * Creates a matcher of {@link Class} that matches when the specified baseType is * assignable from the examined class. * For example: *
assertThat(Integer.class, typeCompatibleWith(Number.class))
* * @param baseType * the base class to examine classes against */ public static Matcher> typeCompatibleWith(Class baseType) { return new IsCompatibleType(baseType); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/object/IsEventFrom.java000066400000000000000000000044601355170103300271000ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.EventObject; /** * Tests if the value is an event announced by a specific object. */ public class IsEventFrom extends TypeSafeDiagnosingMatcher { private final Class eventClass; private final Object source; public IsEventFrom(Class eventClass, Object source) { this.eventClass = eventClass; this.source = source; } @Override public boolean matchesSafely(EventObject item, Description mismatchDescription) { if (!eventClass.isInstance(item)) { mismatchDescription.appendText("item type was " + item.getClass().getName()); return false; } if (!eventHasSameSource(item)) { mismatchDescription.appendText("source was ").appendValue(item.getSource()); return false; } return true; } private boolean eventHasSameSource(EventObject ev) { return ev.getSource() == source; } @Override public void describeTo(Description description) { description.appendText("an event of type ") .appendText(eventClass.getName()) .appendText(" from ") .appendValue(source); } /** * Creates a matcher of {@link java.util.EventObject} that matches any object * derived from eventClass announced by source. * For example: *
assertThat(myEvent, is(eventFrom(PropertyChangeEvent.class, myBean)))
* * @param eventClass * the class of the event to match on * @param source * the source of the event */ public static Matcher eventFrom(Class eventClass, Object source) { return new IsEventFrom(eventClass, source); } /** * Creates a matcher of {@link java.util.EventObject} that matches any EventObject * announced by source. * For example: *
assertThat(myEvent, is(eventFrom(myBean)))
* * @param source * the source of the event */ public static Matcher eventFrom(Object source) { return eventFrom(EventObject.class, source); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/object/package.html000066400000000000000000000001411355170103300263050ustar00rootroot00000000000000

Matchers that inspect objects and classes.

JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/000077500000000000000000000000001355170103300235465ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/CharSequenceLength.java000066400000000000000000000030551355170103300301240ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import static org.hamcrest.CoreMatchers.equalTo; /** * @author Marco Leichsenring * @author Steve Freeman */ public class CharSequenceLength extends FeatureMatcher { /** * @param lengthMatcher The matcher to apply to the feature */ @SuppressWarnings("WeakerAccess") public CharSequenceLength(Matcher lengthMatcher) { super(lengthMatcher, "a CharSequence with length", "length"); } @Override protected Integer featureValueOf(CharSequence actual) { return actual.length(); } /** * Creates a matcher of {@link CharSequence} that matches when a char sequence has the given length * For example: * *
     * assertThat("text", hasLength(4))
     * 
* * @param length the expected length of the string */ public static Matcher hasLength(int length) { return new CharSequenceLength(equalTo(length)); } /** * Creates a matcher of {@link CharSequence} that matches when a char sequence has the given length * For example: * *
      * assertThat("text", hasLength(lessThan(4)))
      * 
* * @param lengthMatcher the expected length of the string */ @SuppressWarnings("WeakerAccess") public static Matcher hasLength(Matcher lengthMatcher) { return new CharSequenceLength(lengthMatcher); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java000066400000000000000000000032031355170103300271210ustar00rootroot00000000000000 package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.regex.Pattern; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.IsNull.nullValue; /** * Matches blank Strings (and null). */ public final class IsBlankString extends TypeSafeMatcher { private static final IsBlankString BLANK_INSTANCE = new IsBlankString(); @SuppressWarnings("unchecked") private static final Matcher NULL_OR_BLANK_INSTANCE = anyOf(nullValue(), BLANK_INSTANCE); private static final Pattern REGEX_WHITESPACE = Pattern.compile("\\s*"); private IsBlankString() { } @Override public boolean matchesSafely(String item) { return REGEX_WHITESPACE.matcher(item).matches(); } @Override public void describeTo(Description description) { description.appendText("a blank string"); } /** * Creates a matcher of {@link String} that matches when the examined string contains * zero or more whitespace characters and nothing else. * For example: *
assertThat("  ", is(blankString()))
*/ public static Matcher blankString() { return BLANK_INSTANCE; } /** * Creates a matcher of {@link String} that matches when the examined string is null, or * contains zero or more whitespace characters and nothing else. * For example: *
assertThat(((String)null), is(blankOrNullString()))
* */ public static Matcher blankOrNullString() { return NULL_OR_BLANK_INSTANCE; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/IsEmptyString.java000066400000000000000000000042171355170103300271760ustar00rootroot00000000000000 package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.IsNull.nullValue; /** * Matches empty Strings (and null). */ public final class IsEmptyString extends TypeSafeMatcher { private static final IsEmptyString INSTANCE = new IsEmptyString(); @SuppressWarnings("unchecked") private static final Matcher NULL_OR_EMPTY_INSTANCE = anyOf(nullValue(), INSTANCE); private IsEmptyString() { } @Override public boolean matchesSafely(String item) { return item.equals(""); } @Override public void describeTo(Description description) { description.appendText("an empty string"); } /** * Creates a matcher of {@link String} that matches when the examined string has zero length. * For example: *
assertThat("", isEmptyString())
* * @deprecated use is(emptyString()) instead */ @Deprecated public static Matcher isEmptyString() { return emptyString(); } /** * Creates a matcher of {@link String} that matches when the examined string has zero length. * For example: *
assertThat("", is(emptyString()))
* */ public static Matcher emptyString() { return INSTANCE; } /** * Creates a matcher of {@link String} that matches when the examined string is null, or * has zero length. * For example: *
assertThat(((String)null), isEmptyOrNullString())
* * @deprecated use is(emptyOrNullString()) instead * */ @Deprecated public static Matcher isEmptyOrNullString() { return emptyOrNullString(); } /** * Creates a matcher of {@link String} that matches when the examined string is null, or * has zero length. * For example: *
assertThat(((String)null), is(emptyOrNullString()))
* */ public static Matcher emptyOrNullString() { return NULL_OR_EMPTY_INSTANCE; } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java000066400000000000000000000050671355170103300321530ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import static java.lang.Character.isWhitespace; /** * Tests if a string is equal to another string, compressing any changes in whitespace. */ public class IsEqualCompressingWhiteSpace extends TypeSafeMatcher { // TODO: Replace String with CharSequence to allow for easy interoperability between // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). private final String string; public IsEqualCompressingWhiteSpace(String string) { if (string == null) { throw new IllegalArgumentException("Non-null value required"); } this.string = string; } @Override public boolean matchesSafely(String item) { return stripSpaces(string).equals(stripSpaces(item)); } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was ").appendValue(item); } @Override public void describeTo(Description description) { description.appendText("a string equal to ") .appendValue(string) .appendText(" compressing white space"); } public String stripSpaces(String toBeStripped) { return toBeStripped.replaceAll("\\s+", " ").trim(); } /** * @deprecated {@link #equalToCompressingWhiteSpace(String)} * @param expectedString * the expected value of matched strings */ public static Matcher equalToIgnoringWhiteSpace(String expectedString) { return new IsEqualCompressingWhiteSpace(expectedString); } /** * Creates a matcher of {@link String} that matches when the examined string is equal to * the specified expectedString, when whitespace differences are (mostly) ignored. To be * exact, the following whitespace rules are applied: *
    *
  • all leading and trailing whitespace of both the expectedString and the examined string are ignored
  • *
  • any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
  • *
* For example: *
assertThat("   my\tfoo  bar ", equalToCompressingWhiteSpace(" my  foo bar"))
* * @param expectedString * the expected value of matched strings */ public static Matcher equalToCompressingWhiteSpace(String expectedString) { return new IsEqualCompressingWhiteSpace(expectedString); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java000066400000000000000000000031641355170103300302510ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Tests if a string is equal to another string, regardless of the case. */ public class IsEqualIgnoringCase extends TypeSafeMatcher { // TODO: Replace String with CharSequence to allow for easy interoperability between // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). private final String string; public IsEqualIgnoringCase(String string) { if (string == null) { throw new IllegalArgumentException("Non-null value required"); } this.string = string; } @Override public boolean matchesSafely(String item) { return string.equalsIgnoreCase(item); } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was ").appendValue(item); } @Override public void describeTo(Description description) { description.appendText("a string equal to ") .appendValue(string) .appendText(" ignoring case"); } /** * Creates a matcher of {@link String} that matches when the examined string is equal to * the specified expectedString, ignoring case. * For example: *
assertThat("Foo", equalToIgnoringCase("FOO"))
* * @param expectedString * the expected value of matched strings */ public static Matcher equalToIgnoringCase(String expectedString) { return new IsEqualIgnoringCase(expectedString); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/MatchesPattern.java000066400000000000000000000023431355170103300273350ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.regex.Pattern; public class MatchesPattern extends TypeSafeMatcher { private final Pattern pattern; public MatchesPattern(Pattern pattern) { this.pattern = pattern; } @Override protected boolean matchesSafely(String item) { return pattern.matcher(item).matches(); } @Override public void describeTo(Description description) { description.appendText("a string matching the pattern '" + pattern + "'"); } /** * Creates a matcher of {@link java.lang.String} that matches when the examined string * exactly matches the given {@link java.util.regex.Pattern}. */ public static Matcher matchesPattern(Pattern pattern) { return new MatchesPattern(pattern); } /** * Creates a matcher of {@link java.lang.String} that matches when the examined string * exactly matches the given regular expression, treated as a {@link java.util.regex.Pattern}. */ public static Matcher matchesPattern(String regex) { return new MatchesPattern(Pattern.compile(regex)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/StringContainsInOrder.java000066400000000000000000000045651355170103300306530ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Arrays; public class StringContainsInOrder extends TypeSafeMatcher { private final Iterable substrings; public StringContainsInOrder(Iterable substrings) { this.substrings = substrings; } @Override public boolean matchesSafely(String s) { int fromIndex = 0; for (String substring : substrings) { fromIndex = s.indexOf(substring, fromIndex); if (fromIndex == -1) { return false; } fromIndex++; } return true; } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("was \"").appendText(item).appendText("\""); } @Override public void describeTo(Description description) { description.appendText("a string containing ") .appendValueList("", ", ", "", substrings) .appendText(" in order"); } /** * Creates a matcher of {@link String} that matches when the examined string contains all of * the specified substrings, considering the order of their appearance. * For example: *
assertThat("myfoobarbaz", stringContainsInOrder(Arrays.asList("bar", "foo")))
* fails as "foo" occurs before "bar" in the string "myfoobarbaz" * * @param substrings * the substrings that must be contained within matching strings */ public static Matcher stringContainsInOrder(Iterable substrings) { return new StringContainsInOrder(substrings); } /** * Creates a matcher of {@link String} that matches when the examined string contains all of * the specified substrings, considering the order of their appearance. * For example: *
assertThat("myfoobarbaz", stringContainsInOrder("bar", "foo"))
* fails as "foo" occurs before "bar" in the string "myfoobarbaz" * * @param substrings * the substrings that must be contained within matching strings */ public static Matcher stringContainsInOrder(String... substrings) { return new StringContainsInOrder(Arrays.asList(substrings)); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/text/package.html000066400000000000000000000001361355170103300260270ustar00rootroot00000000000000

Matchers that perform text comparisons.

JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/xml/000077500000000000000000000000001355170103300233625ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/xml/HasXPath.java000066400000000000000000000150451355170103300257120ustar00rootroot00000000000000package org.hamcrest.xml; import org.hamcrest.Condition; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.core.IsAnything; import org.w3c.dom.Node; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.xpath.*; import static javax.xml.xpath.XPathConstants.STRING; import static org.hamcrest.Condition.matched; import static org.hamcrest.Condition.notMatched; /** * Applies a Matcher to a given XML Node in an existing XML Node tree, specified by an XPath expression. * * @author Joe Walnes * @author Steve Freeman */ public class HasXPath extends TypeSafeDiagnosingMatcher { public static final NamespaceContext NO_NAMESPACE_CONTEXT = null; private static final IsAnything WITH_ANY_CONTENT = new IsAnything(""); private static final Condition.Step NODE_EXISTS = nodeExists(); private final Matcher valueMatcher; private final XPathExpression compiledXPath; private final String xpathString; private final QName evaluationMode; /** * @param xPathExpression XPath expression. * @param valueMatcher Matcher to use at given XPath. * May be null to specify that the XPath must exist but the value is irrelevant. */ public HasXPath(String xPathExpression, Matcher valueMatcher) { this(xPathExpression, NO_NAMESPACE_CONTEXT, valueMatcher); } /** * @param xPathExpression XPath expression. * @param namespaceContext Resolves XML namespace prefixes in the XPath expression * @param valueMatcher Matcher to use at given XPath. * May be null to specify that the XPath must exist but the value is irrelevant. */ public HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher) { this(xPathExpression, namespaceContext, valueMatcher, STRING); } private HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher, QName mode) { this.compiledXPath = compiledXPath(xPathExpression, namespaceContext); this.xpathString = xPathExpression; this.valueMatcher = valueMatcher; this.evaluationMode = mode; } @Override public boolean matchesSafely(Node item, Description mismatch) { return evaluated(item, mismatch) .and(NODE_EXISTS) .matching(valueMatcher); } @Override public void describeTo(Description description) { description.appendText("an XML document with XPath ").appendText(xpathString); if (valueMatcher != null) { description.appendText(" ").appendDescriptionOf(valueMatcher); } } private Condition evaluated(Node item, Description mismatch) { try { return matched(compiledXPath.evaluate(item, evaluationMode), mismatch); } catch (XPathExpressionException e) { mismatch.appendText(e.getMessage()); } return notMatched(); } private static Condition.Step nodeExists() { return new Condition.Step() { @Override public Condition apply(Object value, Description mismatch) { if (value == null) { mismatch.appendText("xpath returned no results."); return notMatched(); } return matched(String.valueOf(value), mismatch); } }; } private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) { try { final XPath xPath = XPathFactory.newInstance().newXPath(); if (namespaceContext != null) { xPath.setNamespaceContext(namespaceContext); } return xPath.compile(xPathExpression); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e); } } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the * specified xPath that satisfies the specified valueMatcher. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", equalTo("Cheddar")))
* * @param xPath * the target xpath * @param valueMatcher * matcher for the value at the specified xpath */ public static Matcher hasXPath(String xPath, Matcher valueMatcher) { return hasXPath(xPath, NO_NAMESPACE_CONTEXT, valueMatcher); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the * specified xPath, within the specified namespaceContext, that satisfies * the specified valueMatcher. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs, equalTo("Cheddar")))
* * @param xPath * the target xpath * @param namespaceContext * the namespace for matching nodes * @param valueMatcher * matcher for the value at the specified xpath */ public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext, Matcher valueMatcher) { return new HasXPath(xPath, namespaceContext, valueMatcher, STRING); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node * at the specified xPath, with any content. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese"))
* * @param xPath * the target xpath */ public static Matcher hasXPath(String xPath) { return hasXPath(xPath, NO_NAMESPACE_CONTEXT); } /** * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node * at the specified xPath within the specified namespace context, with any content. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs))
* * @param xPath * the target xpath * @param namespaceContext * the namespace for matching nodes */ public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext) { return new HasXPath(xPath, namespaceContext, WITH_ANY_CONTENT, XPathConstants.NODE); } } JavaHamcrest-2.2/hamcrest/src/main/java/org/hamcrest/xml/package.html000066400000000000000000000001211355170103300256350ustar00rootroot00000000000000

Matchers of XML documents.

JavaHamcrest-2.2/hamcrest/src/test/000077500000000000000000000000001355170103300172775ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/000077500000000000000000000000001355170103300202205ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/000077500000000000000000000000001355170103300210075ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/000077500000000000000000000000001355170103300226155ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/AbstractMatcherTest.java000066400000000000000000000046501355170103300273740ustar00rootroot00000000000000package org.hamcrest; import junit.framework.TestCase; import org.junit.Assert; public abstract class AbstractMatcherTest extends TestCase { /** * Create an instance of the Matcher so some generic safety-net tests can be run on it. */ protected abstract Matcher createMatcher(); public static void assertMatches(Matcher matcher, T arg) { assertMatches("Expected match, but mismatched", matcher, arg); } public static void assertMatches(String message, Matcher matcher, Object arg) { if (!matcher.matches(arg)) { Assert.fail(message + " because: '" + mismatchDescription(matcher, arg) + "'"); } } public static void assertDoesNotMatch(Matcher c, T arg) { assertDoesNotMatch("Unexpected match", c, arg); } public static void assertDoesNotMatch(String message, Matcher c, T arg) { Assert.assertFalse(message, c.matches(arg)); } public static void assertDescription(String expected, Matcher matcher) { Description description = new StringDescription(); description.appendDescriptionOf(matcher); Assert.assertEquals("Expected description", expected, description.toString().trim()); } public static void assertMismatchDescription(String expected, Matcher matcher, Object arg) { Assert.assertFalse("Precondition: Matcher should not match item.", matcher.matches(arg)); Assert.assertEquals("Expected mismatch description", expected, mismatchDescription(matcher, arg)); } public static void assertNullSafe(Matcher matcher) { try { matcher.matches(null); } catch (Exception e) { Assert.fail("Matcher was not null safe"); } } public static void assertUnknownTypeSafe(Matcher matcher) { try { matcher.matches(new UnknownType()); } catch (Exception e) { Assert.fail("Matcher was not unknown type safe, because: " + e); } } public void testIsNullSafe() { assertNullSafe(createMatcher()); } public void testCopesWithUnknownTypes() { createMatcher().matches(new UnknownType()); } private static String mismatchDescription(Matcher matcher, Object arg) { Description description = new StringDescription(); matcher.describeMismatch(arg, description); return description.toString().trim(); } @SuppressWarnings("WeakerAccess") public static class UnknownType { } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java000066400000000000000000000062331355170103300274020ustar00rootroot00000000000000package org.hamcrest; import org.junit.Test; import static org.junit.Assert.assertEquals; public final class BaseDescriptionTest { private final StringBuilder result = new StringBuilder(); private final BaseDescription baseDescription = new BaseDescription() { @Override protected void append(char c) { result.append(c); } }; @Test public void describesAppendedNullValue() { baseDescription.appendValue(null); assertEquals("null", result.toString()); } @Test public void quotesAppendedStringValue() { baseDescription.appendValue("foo"); assertEquals("\"foo\"", result.toString()); } @Test public void quotesAppendedCharacterValue() { baseDescription.appendValue('f'); assertEquals("\"f\"", result.toString()); } @Test public void quotesAppendedTab() { baseDescription.appendValue('\t'); assertEquals("\"\\t\"", result.toString()); } @Test public void quotesAppendedNewLine() { baseDescription.appendValue('\n'); assertEquals("\"\\n\"", result.toString()); } @Test public void quotesAppendedLineReturn() { baseDescription.appendValue('\r'); assertEquals("\"\\r\"", result.toString()); } @Test public void quotesAppendedBackslash() { baseDescription.appendValue('\\'); assertEquals("\"\\\\\"", result.toString()); } @Test public void quotesAppendedDoubleQuotes() { baseDescription.appendValue('"'); assertEquals("\"\\\"\"", result.toString()); } @Test public void bracketsAppendedByteValue() { baseDescription.appendValue(Byte.valueOf("2")); assertEquals("<2b>", result.toString()); } @Test public void bracketsAppendedShortValue() { baseDescription.appendValue(Short.valueOf("2")); assertEquals("<2s>", result.toString()); } @Test public void bracketsAppendedLongValue() { baseDescription.appendValue(Long.valueOf("2")); assertEquals("<2L>", result.toString()); } @Test public void bracketsAppendedFloatValue() { baseDescription.appendValue(Float.valueOf("1.2")); assertEquals("<1.2F>", result.toString()); } @Test public void describesAppendedArrayValue() { baseDescription.appendValue(new String[] {"2", "3"}); assertEquals("[\"2\", \"3\"]", result.toString()); } @Test public void bracketsAppendedObjectValue() { final Object value = new Object(); baseDescription.appendValue(value); assertEquals("<" + value.toString() + ">", result.toString()); } @Test public void safelyDescribesAppendedValueOfObjectWhoseToStringThrowsAnException() { final Object value = new Object() { @Override public String toString() { throw new UnsupportedOperationException(); } }; final String expected = value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); baseDescription.appendValue(value); assertEquals("<" + expected + ">", result.toString()); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/BaseMatcherTest.java000066400000000000000000000012171355170103300264770ustar00rootroot00000000000000package org.hamcrest; import org.junit.Test; import static org.junit.Assert.assertEquals; public final class BaseMatcherTest { @Test public void describesItselfWithToStringMethod() { Matcher someMatcher = new BaseMatcher() { @Override public boolean matches(Object item) { throw new UnsupportedOperationException(); } @Override public void describeTo(Description description) { description.appendText("SOME DESCRIPTION"); } }; assertEquals("SOME DESCRIPTION", someMatcher.toString()); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/CustomMatcherTest.java000066400000000000000000000010021355170103300270670ustar00rootroot00000000000000package org.hamcrest; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.assertDescription; public final class CustomMatcherTest { @Test public void usesStaticDescription() throws Exception { Matcher matcher = new CustomMatcher("I match strings") { @Override public boolean matches(Object item) { return (item instanceof String); } }; assertDescription("I match strings", matcher); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/CustomTypeSafeMatcherTest.java000066400000000000000000000020731355170103300305410ustar00rootroot00000000000000package org.hamcrest; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; public final class CustomTypeSafeMatcherTest { private static final String STATIC_DESCRIPTION = "I match non empty strings"; private final Matcher customMatcher = new CustomTypeSafeMatcher(STATIC_DESCRIPTION) { @Override public boolean matchesSafely(String item) { return false; } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("an " + item); } }; @Test public void usesStaticDescription() throws Exception { assertDescription(STATIC_DESCRIPTION, customMatcher); } @Test public void reportsMismatch() { assertMismatchDescription("an item", customMatcher, "item"); } @Test public void isNullSafe() { assertNullSafe(customMatcher); } @Test public void copesWithUnknownTypes() { assertUnknownTypeSafe(customMatcher); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/FeatureMatcherTest.java000066400000000000000000000041241355170103300272200ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.core.IsEqual; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.junit.Assert.assertEquals; public final class FeatureMatcherTest { private final FeatureMatcher resultMatcher = resultMatcher(); @Test public void matchesPartOfAnObject() { assertMatches("feature", resultMatcher, new Thingy("bar")); assertDescription("Thingy with result \"bar\"", resultMatcher); } @Test public void mismatchesPartOfAnObject() { assertMismatchDescription("result mismatch-description", resultMatcher, new Thingy("foo")); } @Test public void doesNotThrowNullPointerException() { assertMismatchDescription("was null", resultMatcher, null); } @Test public void doesNotThrowClassCastException() { resultMatcher.matches(new ShouldNotMatch()); StringDescription mismatchDescription = new StringDescription(); resultMatcher.describeMismatch(new ShouldNotMatch(), mismatchDescription); assertEquals("was ShouldNotMatch ", mismatchDescription.toString()); } public static class Match extends IsEqual { public Match(String equalArg) { super(equalArg); } @Override public void describeMismatch(Object item, Description description) { description.appendText("mismatch-description"); } } public static class Thingy { private final String result; public Thingy(String result) { this.result = result; } public String getResult() { return result; } } public static class ShouldNotMatch { @Override public String toString() { return "ShouldNotMatch"; } } private static FeatureMatcher resultMatcher() { return new FeatureMatcher(new Match("bar"), "Thingy with result", "result") { @Override public String featureValueOf(Thingy actual) { return actual.getResult(); } }; } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/MatcherAssertTest.java000066400000000000000000000054211355170103300270670ustar00rootroot00000000000000package org.hamcrest; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.*; public final class MatcherAssertTest { @Test public void includesDescriptionOfTestedValueInErrorMessage() { String expected = "expected"; String actual = "actual"; String endLine = System.lineSeparator(); String expectedMessage = "identifier" + endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; try { assertThat("identifier", actual, equalTo(expected)); } catch (AssertionError e) { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } fail("should have failed"); } @Test public void descriptionCanBeElided() { String expected = "expected"; String actual = "actual"; String endLine = System.lineSeparator(); String expectedMessage = endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; try { assertThat(actual, equalTo(expected)); } catch (AssertionError e) { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } fail("should have failed"); } @Test public void canTestBooleanDirectly() { assertThat("success reason message", true); try { assertThat("failing reason message", false); } catch (AssertionError e) { assertEquals("failing reason message", e.getMessage()); return; } fail("should have failed"); } @Test public void includesMismatchDescription() { Matcher matcherWithCustomMismatchDescription = new BaseMatcher() { @Override public boolean matches(Object item) { return false; } @Override public void describeTo(Description description) { description.appendText("Something cool"); } @Override public void describeMismatch(Object item, Description mismatchDescription) { mismatchDescription.appendText("Not cool"); } }; String endLine = System.lineSeparator(); String expectedMessage = endLine + "Expected: Something cool" + endLine + " but: Not cool"; try { assertThat("Value", matcherWithCustomMismatchDescription); fail("should have failed"); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } } @Test public void canAssertSubtypes() { assertThat(1, equalTo((Number) 1)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/NullDescriptionTest.java000066400000000000000000000006651355170103300274450ustar00rootroot00000000000000package org.hamcrest; import org.hamcrest.Description.NullDescription; import org.junit.Test; import static org.junit.Assert.assertEquals; public final class NullDescriptionTest { private final NullDescription nullDescription = new Description.NullDescription(); @Test public void isUnchangedByAppendedText() { nullDescription.appendText("myText"); assertEquals("", nullDescription.toString()); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java000066400000000000000000000053641355170103300313570ustar00rootroot00000000000000package org.hamcrest; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; /** * @author Steve Freeman 2016 http://www.hamcrest.com */ @SuppressWarnings("WeakerAccess") public class TypeSafeDiagnosingMatcherTest { @Test public void describesMismatches() { assertMismatchDescription("was null", STRING_MATCHER, null); assertMismatchDescription("was Character \"c\"", STRING_MATCHER, 'c'); assertMismatchDescription("mismatching", STRING_MATCHER, "other"); } @Test public void detects_non_builtin_types() { final Matcher matcher = new TypeSafeDiagnosingMatcher() { @Override protected boolean matchesSafely(NotBuiltIn item, Description mismatchDescription) { return true; } @Override public void describeTo(Description description) { description.appendText("a not builtin"); } }; assertMatches("not built in", matcher, new NotBuiltIn()); assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } @Test public void filters_type_for_subclassed_matcher_when_expected_type_passed_in() { final Matcher matcher = new SubMatcher<>(new NotBuiltIn()); assertMatches("not built in", matcher, new NotBuiltIn()); assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } @Test public void but_cannot_detect_generic_type_in_subclassed_matcher_using_reflection() { final Matcher matcher = new SubMatcher<>(); assertMatches("not built in", matcher, new NotBuiltIn()); assertMatches("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); } private static final TypeSafeDiagnosingMatcher STRING_MATCHER = new TypeSafeDiagnosingMatcher() { @Override protected boolean matchesSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("mismatching"); return false; } @Override public void describeTo(Description description) { } }; public static class SubMatcher extends TypeSafeDiagnosingMatcher { public SubMatcher() { super(); } public SubMatcher(T expectedObject) { super(expectedObject.getClass()); } @Override protected boolean matchesSafely(T item, Description mismatchDescription) { return true; } @Override public void describeTo(Description description) { description.appendText("sub type"); } } public static class NotBuiltIn { public final String value = "not built in"; @Override public String toString() { return "NotBuiltIn"; } } public static class OtherNotBuiltIn { // empty } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/TypeSafeMatcherTest.java000066400000000000000000000024021355170103300273420ustar00rootroot00000000000000package org.hamcrest; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.assertMismatchDescription; import static org.junit.Assert.assertFalse; @SuppressWarnings("WeakerAccess") public final class TypeSafeMatcherTest { private final Matcher matcher = new TypeSafeMatcherSubclass(); public static class TypeSafeMatcherSubclass extends TypeSafeMatcher { @Override public boolean matchesSafely(String item) { return false; } @Override public void describeMismatchSafely(String item, Description mismatchDescription) { mismatchDescription.appendText("The mismatch"); } @Override public void describeTo(Description description) { } } @Test public void canDetermineMatcherTypeFromProtectedMatchesSafelyMethod() { assertFalse(matcher.matches(null)); assertFalse(matcher.matches(10)); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void describesMismatches() { assertMismatchDescription("was null", matcher, null); assertMismatchDescription("was a java.lang.Integer (<3>)", (Matcher)matcher, 3); assertMismatchDescription("The mismatch", matcher, "a string"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/beans/000077500000000000000000000000001355170103300237055ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java000066400000000000000000000024271355170103300276750ustar00rootroot00000000000000package org.hamcrest.beans; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.beans.HasProperty.hasProperty; /** * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman * @author Tom Denley * @since 1.1.0 */ public final class HasPropertyTest { private final HasPropertyWithValueTest.BeanWithoutInfo bean = new HasPropertyWithValueTest.BeanWithoutInfo("a bean", false); @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = hasProperty("irrelevant"); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesWhenThePropertyExists() { assertMatches(hasProperty("writeOnlyProperty"), bean); } @Test public void doesNotMatchIfPropertyDoesNotExist() { assertDoesNotMatch(hasProperty("aNonExistentProp"), bean); } @Test public void describesItself() { assertDescription("hasProperty(\"property\")", hasProperty("property")); } @Test public void describesAMismatch() { assertMismatchDescription("no \"aNonExistentProp\" in <[Person: a bean]>", hasProperty("aNonExistentProp"), bean); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyWithValueTest.java000066400000000000000000000147601355170103300315310ustar00rootroot00000000000000package org.hamcrest.beans; import org.hamcrest.*; import org.hamcrest.core.IsEqual; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; import static org.hamcrest.beans.HasPropertyWithValue.hasPropertyAtPath; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; /** * @author Iain McGinniss * @author Nat Pryce * @author Steve Freeman * @since 1.1.0 */ @SuppressWarnings("UnusedDeclaration") public class HasPropertyWithValueTest extends AbstractMatcherTest { private final BeanWithoutInfo shouldMatch = new BeanWithoutInfo("is expected", true); private final BeanWithoutInfo shouldNotMatch = new BeanWithoutInfo("not expected", false); private final BeanWithInfo beanWithInfo = new BeanWithInfo("with info"); @Override protected Matcher createMatcher() { return hasProperty("irrelevant", anything()); } public void testMatchesBeanWithoutInfoWithMatchedNamedProperty() { final Matcher propertyMatcher = hasProperty("property", equalTo("is expected")); assertMatches("with property", propertyMatcher, shouldMatch); assertMismatchDescription("property 'property' was \"not expected\"", propertyMatcher, shouldNotMatch); } public void testMatchesBeanWithoutInfoWithMatchedNamedBooleanProperty() { final Matcher booleanPropertyMatcher = hasProperty("booleanProperty", is(true)); assertMatches("with property", booleanPropertyMatcher, shouldMatch); assertMismatchDescription("property 'booleanProperty' was ", booleanPropertyMatcher, shouldNotMatch); } public void testMatchesBeanWithInfoWithMatchedNamedProperty() { assertMatches("with bean info", hasProperty("property", equalTo("with info")), beanWithInfo); assertMismatchDescription("property 'property' was \"with info\"", hasProperty("property", equalTo("without info")), beanWithInfo); } public void testDoesNotMatchBeanWithoutInfoOrMatchedNamedProperty() { assertMismatchDescription("No property \"nonExistentProperty\"", hasProperty("nonExistentProperty", anything()), shouldNotMatch); } public void testDoesNotMatchWriteOnlyProperty() { assertMismatchDescription("property \"writeOnlyProperty\" is not readable", hasProperty("writeOnlyProperty", anything()), shouldNotMatch); } public void testMatchesPath() { assertMatches("1-step path", hasPropertyAtPath("property", equalTo("is expected")), shouldMatch); assertMatches("2-step path", hasPropertyAtPath("inner.property", equalTo("is expected")), new BeanWithInner(shouldMatch)); assertMatches("3-step path", hasPropertyAtPath("inner.inner.property", equalTo("is expected")), new BeanWithInner(new BeanWithInner(shouldMatch))); assertMismatchDescription("inner.No property \"wrong\"", hasPropertyAtPath("inner.wrong.property", anything()), new BeanWithInner(new BeanWithInner(shouldMatch))); assertMismatchDescription("inner.inner.property.was \"not expected\"", hasPropertyAtPath("inner.inner.property", equalTo("something")), new BeanWithInner(new BeanWithInner(shouldNotMatch))); } public void testDescribeTo() { assertDescription("hasProperty(\"property\", )", hasProperty("property", equalTo(true))); } public void testMatchesPropertyAndValue() { assertMatches("property with value", hasProperty("property", anything()), beanWithInfo); } public void testDoesNotWriteMismatchIfPropertyMatches() { Description description = new StringDescription(); hasProperty( "property", anything()).describeMismatch(beanWithInfo, description); assertEquals("Expected mismatch description", "", description.toString()); } public void testDescribesMissingPropertyMismatch() { assertMismatchDescription("No property \"honk\"", hasProperty("honk", anything()), shouldNotMatch); } public void testExceptionsInBeanMethodsShouldBeReportedCorrectly() { assertMismatchDescription( "Calling 'public java.lang.String org.hamcrest.beans.HasPropertyWithValueTest$BeanWithBug.getBroken()': \"bean failed\"", hasProperty("broken", anything()), new BeanWithBug()); } public void testCanAccessAnAnonymousInnerClass() { class X implements IX { @Override public int getTest() { return 1; } } assertThat(new X(), HasPropertyWithValue.hasProperty("test", IsEqual.equalTo(1))); } interface IX { int getTest(); } @SuppressWarnings("WeakerAccess") public static class BeanWithoutInfo { private String property; private final boolean booleanProperty; public BeanWithoutInfo(String property, boolean booleanProperty) { this.property = property; this.booleanProperty = booleanProperty; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public boolean isBooleanProperty() { return booleanProperty; } public void setWriteOnlyProperty(@SuppressWarnings("unused") float property) { } @Override public String toString() { return "[Person: " + property + "]"; } } @SuppressWarnings("WeakerAccess") public static class BeanWithInner { private final Object inner; public BeanWithInner(Object inner) { this.inner = inner; } public Object getInner() { return inner; } } @SuppressWarnings("WeakerAccess") public static class BeanWithInfo { private final String propertyValue; public BeanWithInfo(String propertyValue) { this.propertyValue = propertyValue; } public String property() { return propertyValue; } } public static class BeanWithInfoBeanInfo extends SimpleBeanInfo { @Override public PropertyDescriptor[] getPropertyDescriptors() { try { return new PropertyDescriptor[] { new PropertyDescriptor("property", BeanWithInfo.class, "property", null) }; } catch (IntrospectionException e) { throw new AssertionError("Introspection exception", e); } } } @SuppressWarnings("WeakerAccess") public static class BeanWithBug { public String getBroken() { throw new BeanFailed(); } } @SuppressWarnings("WeakerAccess") public static class BeanFailed extends RuntimeException { public BeanFailed() { super("bean failed"); } } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/beans/SamePropertyValuesAsTest.java000066400000000000000000000116201355170103300315060ustar00rootroot00000000000000package org.hamcrest.beans; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs; @SuppressWarnings("WeakerAccess") public class SamePropertyValuesAsTest extends AbstractMatcherTest { private static final Value aValue = new Value("expected"); private static final ExampleBean expectedBean = new ExampleBean("same", 1, aValue); private static final ExampleBean actualBean = new ExampleBean("same", 1, aValue); @Override protected Matcher createMatcher() { return samePropertyValuesAs(expectedBean); } public void test_reports_match_when_all_properties_match() { assertMatches("matched properties", samePropertyValuesAs(expectedBean), actualBean); } public void test_reports_mismatch_when_actual_type_is_not_assignable_to_expected_type() { assertMismatchDescription("is incompatible type: ExampleBean", samePropertyValuesAs((Object)aValue), actualBean); } public void test_reports_mismatch_on_first_property_difference() { assertMismatchDescription("stringProperty was \"different\"", samePropertyValuesAs(expectedBean), new ExampleBean("different", 1, aValue)); assertMismatchDescription("intProperty was <2>", samePropertyValuesAs(expectedBean), new ExampleBean("same", 2, aValue)); assertMismatchDescription("valueProperty was ", samePropertyValuesAs(expectedBean), new ExampleBean("same", 1, new Value("other"))); } public void test_matches_beans_with_inheritance_but_no_extra_properties() { assertMatches("sub type with same properties", samePropertyValuesAs(expectedBean), new SubBeanWithNoExtraProperties("same", 1, aValue)); } public void test_rejects_subtype_that_has_extra_properties() { assertMismatchDescription("has extra properties called [extraProperty]", samePropertyValuesAs(expectedBean), new SubBeanWithExtraProperty("same", 1, aValue)); } public void test_ignores_extra_subtype_properties() { final SubBeanWithExtraProperty withExtraProperty = new SubBeanWithExtraProperty("same", 1, aValue); assertMatches("extra property", samePropertyValuesAs(expectedBean, "extraProperty"), withExtraProperty); } public void test_ignores_different_properties() { final ExampleBean differentBean = new ExampleBean("different", 1, aValue); assertMatches("different property", samePropertyValuesAs(expectedBean, "stringProperty"), differentBean); } public void test_accepts_missing_properties_to_ignore() { assertMatches("ignored property", samePropertyValuesAs(expectedBean, "notAProperty"), actualBean); } public void test_can_ignore_all_properties() { final ExampleBean differentBean = new ExampleBean("different", 2, new Value("not expected")); assertMatches( "different property", samePropertyValuesAs(expectedBean, "stringProperty", "intProperty", "valueProperty"), differentBean); } public void testDescribesItself() { assertDescription( "same property values as ExampleBean [intProperty: <1>, stringProperty: \"same\", valueProperty: ]", samePropertyValuesAs(expectedBean)); assertDescription( "same property values as ExampleBean [intProperty: <1>, stringProperty: \"same\", valueProperty: ] ignoring [\"ignored1\", \"ignored2\"]", samePropertyValuesAs(expectedBean, "ignored1", "ignored2")); } public static class Value { public Value(Object value) { this.value = value; } public final Object value; @Override public String toString() { return "Value " + value; } } @SuppressWarnings("unused") public static class ExampleBean { private String stringProperty; private int intProperty; private Value valueProperty; public ExampleBean(String stringProperty, int intProperty, Value valueProperty) { this.stringProperty = stringProperty; this.intProperty = intProperty; this.valueProperty = valueProperty; } public String getStringProperty() { return stringProperty; } public int getIntProperty() { return intProperty; } public Value getValueProperty() { return valueProperty; } @Override public String toString() { return "an ExampleBean"; } } public static class SubBeanWithNoExtraProperties extends ExampleBean { public SubBeanWithNoExtraProperties(String stringProperty, int intProperty, Value valueProperty) { super(stringProperty, intProperty, valueProperty); } } public static class SubBeanWithExtraProperty extends ExampleBean { public SubBeanWithExtraProperty(String stringProperty, int intProperty, Value valueProperty) { super(stringProperty, intProperty, valueProperty); } @SuppressWarnings("unused") public String getExtraProperty() { return "extra"; } } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/000077500000000000000000000000001355170103300247505ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInAnyOrderTest.java000066400000000000000000000041151355170103300331400ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.collection.ArrayMatching.arrayContainingInAnyOrder; import static org.hamcrest.core.IsEqual.equalTo; public class ArrayMatchingInAnyOrderTest extends AbstractMatcherTest { @SuppressWarnings("unchecked") @Override protected Matcher createMatcher() { return ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2)); } @SuppressWarnings("unchecked") public void testHasAReadableDescription() { assertDescription("[<1>, <2>] in any order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2))); assertDescription("[<1>, <2>] in any order", ArrayMatching.arrayContainingInAnyOrder(1, 2)); } public void testMatchesItemsInAnyOrder() { assertMatches("in order", ArrayMatching.arrayContainingInAnyOrder(1, 2, 3), new Integer[] {1, 2, 3}); assertMatches("out of order", ArrayMatching.arrayContainingInAnyOrder(1, 2, 3), new Integer[] {3, 2, 1}); assertMatches("single", ArrayMatching.arrayContainingInAnyOrder(1), new Integer[] {1}); } @SuppressWarnings("unchecked") public void testAppliesMatchersInAnyOrder() { assertMatches("in order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); assertMatches("out of order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {3, 2, 1}); assertMatches("single", ArrayMatching.arrayContainingInAnyOrder(equalTo(1)), new Integer[] {1}); } public void testMismatchesItemsInAnyOrder() { Matcher matcher = ArrayMatching.arrayContainingInAnyOrder(1, 2, 3); assertMismatchDescription("was null", matcher, null); assertMismatchDescription("no item matches: <1>, <2>, <3> in []", matcher, new Integer[] {}); assertMismatchDescription("no item matches: <2>, <3> in [<1>]", matcher, new Integer[] {1}); assertMismatchDescription("not matched: <4>", matcher, new Integer[] {4,3,2,1}); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInOrderTest.java000066400000000000000000000033501355170103300324700ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.collection.ArrayMatching.arrayContaining; import static org.hamcrest.core.IsEqual.equalTo; public class ArrayMatchingInOrderTest extends AbstractMatcherTest { @SuppressWarnings("unchecked") @Override protected Matcher createMatcher() { return arrayContaining(equalTo(1), equalTo(2)); } @SuppressWarnings("unchecked") public void testHasAReadableDescription() { assertDescription("[<1>, <2>]", arrayContaining(equalTo(1), equalTo(2))); } public void testMatchesItemsInOrder() { assertMatches("in order", arrayContaining(1, 2, 3), new Integer[] {1, 2, 3}); assertMatches("single", arrayContaining(1), new Integer[] {1}); } @SuppressWarnings("unchecked") public void testAppliesMatchersInOrder() { assertMatches("in order", arrayContaining(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); assertMatches("single", arrayContaining(equalTo(1)), new Integer[] {1}); } public void testMismatchesItemsInOrder() { Matcher matcher = arrayContaining(1, 2, 3); assertMismatchDescription("was null", matcher, null); assertMismatchDescription("no item was <1>", matcher, new Integer[] {}); assertMismatchDescription("no item was <2>", matcher, new Integer[] {1}); assertMismatchDescription("item 0: was <4>", matcher, new Integer[] {4,3,2,1}); assertMismatchDescription("item 2: was <4>", matcher, new Integer[] {1,2, 4}); } public void testCanHandleNullValuesInAnArray() { assertMatches("with nulls", arrayContaining(null, null), new Object[]{null, null}); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/HasItemInArrayTest.java000066400000000000000000000064241355170103300313010ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.collection.ArrayMatching.hasItemInArray; public class HasItemInArrayTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasItemInArray("irrelevant"); } public void testMatchesAnArrayThatContainsAnElementMatchingTheGivenMatcher() { assertMatches("should matches array that contains 'a'", hasItemInArray("a"), new String[]{"a", "b", "c"}); } public void testDoesNotMatchAnArrayThatDoesntContainAnElementMatchingTheGivenMatcher() { assertDoesNotMatch("should not matches array that doesn't contain 'a'", hasItemInArray("a"), new String[]{"b", "c"}); assertDoesNotMatch("should not matches empty array", hasItemInArray("a"), new String[0]); assertMismatchDescription( "mismatches were: [<3> was greater than <2>, <4> was greater than <2>, <5> was greater than <2>]", hasItemInArray(lessThan(2)), new Integer[] {3, 4, 5}); } public void testDoesNotMatchNull() { assertDoesNotMatch("should not matches null", hasItemInArray("a"), null); } public void testHasAReadableDescription() { assertDescription("an array containing a value less than <2>", hasItemInArray(lessThan(2))); } // Remaining code no longer compiles, thanks to generics. I think that's a good thing, but // I still need to investigate how this behaves with code that doesn't use generics. // I expect ClassCastExceptions will be thrown. // -Joe. // public void testDoesNotMatchObjectThatIsNotAnArray() { // assertDoesNotMatch("should not matches empty list", // arrayContaining("a"), "not a collection"); // } // public void testMatchesPrimitiveArrayElements() { // assertMatches("boolean", arrayContaining(true), new boolean[]{true, false}); // assertDoesNotMatch("boolean", arrayContaining(false), new boolean[]{false}); // // assertMatches("byte", arrayContaining((byte) 1), new byte[]{1, 2, 3}); // assertDoesNotMatch("byte", arrayContaining((byte) 0), new byte[]{1, 2, 3}); // // assertMatches("char", arrayContaining('a'), new char[]{'a', 'b', 'c'}); // assertDoesNotMatch("char", arrayContaining('z'), new char[]{'a', 'b', 'c'}); // // assertMatches("short", arrayContaining((short) 1), new short[]{1, 2, 3}); // assertDoesNotMatch("short", arrayContaining((short) 0), new short[]{1, 2, 3}); // // assertMatches("int", arrayContaining(1), new int[]{1, 2, 3}); // assertDoesNotMatch("int", arrayContaining(0), new int[]{1, 2, 3}); // // assertMatches("long", arrayContaining(1L), new long[]{1, 2, 3}); // assertDoesNotMatch("long", arrayContaining(0L), new long[]{1, 2, 3}); // // assertMatches("float", arrayContaining(1f), new float[]{1f, 2f, 3f}); // assertDoesNotMatch("float", arrayContaining(0f), new float[]{1f, 2f, 3f}); // // assertMatches("double", arrayContaining(1.0), new double[]{1.0, 2.0, 3.0}); // assertDoesNotMatch("double", arrayContaining(0.0), new double[]{1.0, 2.0, 3.0}); // } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java000066400000000000000000000037231355170103300337770ustar00rootroot00000000000000package org.hamcrest.collection; import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsArrayContainingInAnyOrderTest extends AbstractMatcherTest { @SuppressWarnings("unchecked") @Override protected Matcher createMatcher() { return arrayContainingInAnyOrder(equalTo(1), equalTo(2)); } @SuppressWarnings("unchecked") public void testHasAReadableDescription() { assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(equalTo(1), equalTo(2))); assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(1, 2)); } public void testMatchesItemsInAnyOrder() { assertMatches("in order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] {1, 2, 3}); assertMatches("out of order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] {3, 2, 1}); assertMatches("single", arrayContainingInAnyOrder(1), new Integer[] {1}); } @SuppressWarnings("unchecked") public void testAppliesMatchersInAnyOrder() { assertMatches("in order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); assertMatches("out of order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {3, 2, 1}); assertMatches("single", arrayContainingInAnyOrder(equalTo(1)), new Integer[] {1}); } public void testMismatchesItemsInAnyOrder() { Matcher matcher = arrayContainingInAnyOrder(1, 2, 3); assertMismatchDescription("was null", matcher, null); assertMismatchDescription("no item matches: <1>, <2>, <3> in []", matcher, new Integer[] {}); assertMismatchDescription("no item matches: <2>, <3> in [<1>]", matcher, new Integer[] {1}); assertMismatchDescription("not matched: <4>", matcher, new Integer[] {4,3,2,1}); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInOrderTest.java000066400000000000000000000031411355170103300333210ustar00rootroot00000000000000package org.hamcrest.collection; import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining; import static org.hamcrest.core.IsEqual.equalTo; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; public class IsArrayContainingInOrderTest extends AbstractMatcherTest { @SuppressWarnings("unchecked") @Override protected Matcher createMatcher() { return arrayContaining(equalTo(1), equalTo(2)); } @SuppressWarnings("unchecked") public void testHasAReadableDescription() { assertDescription("[<1>, <2>]", arrayContaining(equalTo(1), equalTo(2))); } public void testMatchesItemsInOrder() { assertMatches("in order", arrayContaining(1, 2, 3), new Integer[] {1, 2, 3}); assertMatches("single", arrayContaining(1), new Integer[] {1}); } @SuppressWarnings("unchecked") public void testAppliesMatchersInOrder() { assertMatches("in order", arrayContaining(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); assertMatches("single", arrayContaining(equalTo(1)), new Integer[] {1}); } public void testMismatchesItemsInOrder() { Matcher matcher = arrayContaining(1, 2, 3); assertMismatchDescription("was null", matcher, null); assertMismatchDescription("no item was <1>", matcher, new Integer[] {}); assertMismatchDescription("no item was <2>", matcher, new Integer[] {1}); assertMismatchDescription("item 0: was <4>", matcher, new Integer[] {4,3,2,1}); assertMismatchDescription("item 2: was <4>", matcher, new Integer[] {1,2, 4}); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsArrayTest.java000066400000000000000000000045361355170103300300350ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import static org.hamcrest.collection.IsArray.array; import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("unchecked") public class IsArrayTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return array(equalTo("irrelevant")); } public void testMatchesAnArrayThatMatchesAllTheElementMatchers() { assertMatches("should match array with matching elements", array(equalTo("a"), equalTo("b"), equalTo("c")), new String[]{"a", "b", "c"}); } public void testDoesNotMatchAnArrayWhenElementsDoNotMatch() { assertDoesNotMatch("should not match array with different elements", array(equalTo("a"), equalTo("b")), new String[]{"b", "c"}); } public void testDoesNotMatchAnArrayOfDifferentSize() { assertDoesNotMatch("should not match larger array", array(equalTo("a"), equalTo("b")), new String[]{"a", "b", "c"}); assertDoesNotMatch("should not match smaller array", array(equalTo("a"), equalTo("b")), new String[]{"a"}); } public void testDoesNotMatchNull() { assertDoesNotMatch("should not match null", array(equalTo("a")), null); } public void testHasAReadableDescription() { assertDescription("[\"a\", \"b\"]", array(equalTo("a"), equalTo("b"))); } public void testHasAReadableMismatchDescriptionUsing() { assertMismatchDescription("element <0> was \"c\"", array(equalTo("a"), equalTo("b")), new String[]{"c", "b"}); } public void testHasAReadableMismatchDescriptionUsingCustomMatchers() { final BaseMatcher m = new BaseMatcher() { @Override public boolean matches(Object item) { return false; } @Override public void describeTo(Description description) { description.appendText("c"); } @Override public void describeMismatch(Object item, Description description) { description.appendText("didn't match"); } }; assertMismatchDescription("element <0> didn't match", array(m, equalTo("b")), new String[]{"c", "b"}); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsArrayWithSizeTest.java000066400000000000000000000024721355170103300315210ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; import static org.hamcrest.collection.IsArrayWithSize.emptyArray; import static org.hamcrest.core.IsEqual.equalTo; public class IsArrayWithSizeTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return arrayWithSize(equalTo(2)); } public void testMatchesWhenSizeIsCorrect() { assertMatches("correct size", arrayWithSize(equalTo(3)), new Object[] {1, 2, 3}); assertDoesNotMatch("incorrect size", arrayWithSize(equalTo(2)), new Object[] {1, 2, 3}); } public void testProvidesConvenientShortcutForArrayWithSizeEqualTo() { assertMatches("correct size", arrayWithSize(3), new Object[] {1, 2, 3}); assertDoesNotMatch("incorrect size", arrayWithSize(2), new Object[] {1, 2, 3}); } public void testEmptyArray() { assertMatches("correct size", emptyArray(), new Object[] {}); assertDoesNotMatch("incorrect size", emptyArray(), new Object[] {1}); } public void testHasAReadableDescription() { assertDescription("an array with size <3>", arrayWithSize(equalTo(3))); assertDescription("an empty array", emptyArray()); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsCollectionWithSizeTest.java000066400000000000000000000060361355170103300325360ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.core.IsEqual.equalTo; public class IsCollectionWithSizeTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasSize(7); } public void testMatchesWhenSizeIsCorrect() { assertMatches("correct size", hasSize(equalTo(2)), asList(null, null)); assertMismatchDescription("collection size was <3>", hasSize(equalTo(2)), asList(null, null, null)); } public void testMatchesCollectionWhenSizeIsCorrectUsingObjectElementType() { Collection list = asList(null, null); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesCollectionWhenSizeIsCorrectUsingStringElementType() { Collection list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesCollectionWhenSizeIsCorrectUsingWildcardElementType() { Collection list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesListWhenSizeIsCorrectUsingObjectElementType() { List list = asList(null, null); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesListWhenSizeIsCorrectUsingStringElementType() { List list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testMatchesListWhenSizeIsCorrectUsingWildcardElementType() { List list = asList("a", "b"); assertMatches("correct size", hasSize(equalTo(2)), list); assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); } public void testProvidesConvenientShortcutForHasSizeEqualTo() { assertMatches("correct size", hasSize(2), asList(null, null)); assertMismatchDescription("collection size was <3>", hasSize(2), asList(null, null, null)); } public void testHasAReadableDescription() { assertDescription("a collection with size <3>", hasSize(equalTo(3))); } public void testCompilesWithATypedCollection() { // To prove Issue 43 ArrayList arrayList = new ArrayList(); MatcherAssert.assertThat(arrayList, hasSize(0)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyCollectionTest.java000066400000000000000000000024561355170103300320700ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.Collection; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.core.Is.is; public class IsEmptyCollectionTest extends AbstractMatcherTest { @Override protected Matcher> createMatcher() { return empty(); } public void testMatchesAnEmptyCollection() { assertMatches("empty collection", createMatcher(), emptyCollection()); } public void testDoesNotMatchACollectionWithAnItem() { assertMismatchDescription("<[one, three]>", is(createMatcher()), collectionOfValues()); } public void testHasAReadableDescription() { assertDescription("an empty collection", createMatcher()); } public void testCompiles() { needs(IsEmptyCollection.emptyCollectionOf(String.class)); } private void needs(@SuppressWarnings("unused") Matcher> bar) { } private static Collection collectionOfValues() { return new ArrayList(asList("one", "three")); } private static Collection emptyCollection() { return new ArrayList(); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyIterableTest.java000066400000000000000000000023731355170103300315220ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.Collection; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsEmptyIterable.emptyIterable; public class IsEmptyIterableTest extends AbstractMatcherTest { @Override protected Matcher> createMatcher() { return emptyIterable(); } public void testMatchesAnEmptyIterable() { assertMatches("empty iterable", createMatcher(), emptyCollection()); } public void testDoesNotMatchAnIterableWithItems() { assertDoesNotMatch("iterable with an item", createMatcher(), collectionOfValues()); } public void testHasAReadableDescription() { assertDescription("an empty iterable", createMatcher()); } public void testCompiles() { needs(IsEmptyIterable.emptyIterableOf(String.class)); } private void needs(@SuppressWarnings("unused") Matcher> bar) { } private static Collection collectionOfValues() { return new ArrayList(asList("one", "three")); } private static Collection emptyCollection() { return new ArrayList(); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsInTest.java000066400000000000000000000024421355170103300273170ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import java.util.Arrays; import java.util.Collection; public class IsInTest extends AbstractMatcherTest { String[] elements = {"a", "b", "c"}; @Override protected Matcher createMatcher() { return new IsIn(elements); } public void testReturnsTrueIfArgumentIsInCollection() { Collection collection = Arrays.asList(elements); Matcher isIn = new IsIn(collection); assertMatches("a", isIn, "a"); assertMatches("b", isIn, "b"); assertMatches("c", isIn, "c"); assertDoesNotMatch("d", isIn, "d"); } public void testReturnsTrueIfArgumentIsInArray() { Matcher isIn = new IsIn(elements); assertMatches("a", isIn, "a"); assertMatches("b", isIn, "b"); assertMatches("c", isIn, "c"); assertDoesNotMatch("d", isIn, "d"); } public void testHasReadableDescription() { Matcher isIn = new IsIn(elements); assertEquals("description", "one of {\"a\", \"b\", \"c\"}", StringDescription.toString(isIn)); } } IsIterableContainingInAnyOrderTest.java000066400000000000000000000041501355170103300343640ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collectionpackage org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.collection.IsIterableContainingInOrderTest.WithValue; import java.util.Collections; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrderTest.make; import static org.hamcrest.collection.IsIterableContainingInOrderTest.value; public class IsIterableContainingInAnyOrderTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return containsInAnyOrder(1, 2); } public void testMatchesSingleItemIterable() { assertMatches("single item", containsInAnyOrder(1), asList(1)); } public void testDoesNotMatchEmpty() { assertMismatchDescription("no item matches: <1>, <2> in []", containsInAnyOrder(1, 2), Collections.emptyList()); } public void testMatchesIterableOutOfOrder() { assertMatches("Out of order", containsInAnyOrder(1, 2), asList(2, 1)); } public void testMatchesIterableInOrder() { assertMatches("In order", containsInAnyOrder(1, 2), asList(1, 2)); } public void testDoesNotMatchIfOneOfMultipleElementsMismatches() { assertMismatchDescription("not matched: <4>", containsInAnyOrder(1, 2, 3), asList(1, 2, 4)); } @SuppressWarnings("unchecked") public void testDoesNotMatchIfThereAreMoreElementsThanMatchers() { final Matcher> helpTheCompilerOut = containsInAnyOrder(value(1), value(3)); assertMismatchDescription("not matched: ", helpTheCompilerOut, asList(make(1), make(2), make(3))); } public void testDoesNotMatchIfThereAreMoreMatchersThanElements() { assertMismatchDescription("no item matches: <4> in [<1>, <2>, <3>]", containsInAnyOrder(1, 2, 3, 4), asList(1, 2, 3)); } public void testHasAReadableDescription() { assertDescription("iterable with items [<1>, <2>] in any order", containsInAnyOrder(1, 2)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInOrderTest.java000066400000000000000000000055231355170103300340000ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("unchecked") public class IsIterableContainingInOrderTest extends AbstractMatcherTest { // temporary hack until the Java type system works private final Matcher> contains123 = contains(value(1), value(2), value(3)); @Override protected Matcher createMatcher() { return contains(1, 2); } public void testMatchingSingleItemIterable() throws Exception { assertMatches("Single item iterable", contains(1), singletonList(1)); } public void testMatchingMultipleItemIterable() throws Exception { assertMatches("Multiple item iterable", contains(1, 2, 3), asList(1, 2, 3)); } public void testDoesNotMatchWithMoreElementsThanExpected() throws Exception { assertMismatchDescription("not matched: <4>", contains(1, 2, 3), asList(1, 2, 3, 4)); } public void testDoesNotMatchWithFewerElementsThanExpected() throws Exception { assertMismatchDescription("no item was value with <3>", contains123, asList(make(1), make(2))); } public void testDoesNotMatchIfSingleItemMismatches() throws Exception { assertMismatchDescription("item 0: value was <3>", contains(value(4)), singletonList(make(3))); } public void testDoesNotMatchIfOneOfMultipleItemsMismatch() throws Exception { assertMismatchDescription("item 2: value was <4>", contains123, asList(make(1), make(2), make(4))); } public void testDoesNotMatchEmptyIterable() throws Exception { assertMismatchDescription("no item was value with <4>", contains(value(4)), new ArrayList()); } public void testHasAReadableDescription() { assertDescription("iterable containing [<1>, <2>]", contains(1, 2)); } public void testCanHandleNullMatchers() { assertMatches(contains(null, null), asList(null, null)); } public static class WithValue { private final int value; public WithValue(int value) { this.value = value; } public int getValue() { return value; } @Override public String toString() { return "WithValue " + value; } } public static WithValue make(int value) { return new WithValue(value); } public static Matcher value(int value) { return new FeatureMatcher(equalTo(value), "value with", "value") { @Override protected Integer featureValueOf(WithValue actual) { return actual.getValue(); } }; } } IsIterableContainingInRelativeOrderTest.java000066400000000000000000000075761355170103300354270ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collectionpackage org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder; import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("unchecked") public class IsIterableContainingInRelativeOrderTest extends AbstractMatcherTest { // temporary hack until the Java type system works private final Matcher> contains123 = containsInRelativeOrder(value(1), value(2), value(3)); @Override protected Matcher createMatcher() { return containsInRelativeOrder(1, 2); } public void testMatchingSingleItemIterable() throws Exception { assertMatches("Single item iterable", containsInRelativeOrder(1), asList(1)); } public void testMatchingMultipleItemIterable() throws Exception { assertMatches("Multiple item iterable", containsInRelativeOrder(1, 2, 3), asList(1, 2, 3)); } public void testMatchesWithMoreElementsThanExpectedAtBeginning() throws Exception { assertMatches("More elements at beginning", containsInRelativeOrder(2, 3, 4), asList(1, 2, 3, 4)); } public void testMatchesWithMoreElementsThanExpectedAtEnd() throws Exception { assertMatches("More elements at end", containsInRelativeOrder(1, 2, 3), asList(1, 2, 3, 4)); } public void testMatchesWithMoreElementsThanExpectedInBetween() throws Exception { assertMatches("More elements in between", containsInRelativeOrder(1, 3), asList(1, 2, 3)); } public void testMatchesSubSection() throws Exception { assertMatches("Sub section of iterable", containsInRelativeOrder(2, 3), asList(1, 2, 3, 4)); } public void testMatchesWithSingleGapAndNotFirstOrLast() throws Exception { assertMatches("Sub section with single gaps without a first or last match", containsInRelativeOrder(2, 4), asList(1, 2, 3, 4, 5)); } public void testMatchingSubSectionWithManyGaps() throws Exception { assertMatches("Sub section with many gaps iterable", containsInRelativeOrder(2, 4, 6), asList(1, 2, 3, 4, 5, 6, 7)); } public void testDoesNotMatchWithFewerElementsThanExpected() throws Exception { List valueList = asList(make(1), make(2)); assertMismatchDescription("value with <3> was not found after ", contains123, valueList); } public void testDoesNotMatchIfSingleItemNotFound() throws Exception { assertMismatchDescription("value with <4> was not found", containsInRelativeOrder(value(4)), asList(make(3))); } public void testDoesNotMatchIfOneOfMultipleItemsNotFound() throws Exception { assertMismatchDescription("value with <3> was not found after ", contains123, asList(make(1), make(2), make(4))); } public void testDoesNotMatchEmptyIterable() throws Exception { assertMismatchDescription("value with <4> was not found", containsInRelativeOrder(value(4)), new ArrayList()); } public void testHasAReadableDescription() { assertDescription("iterable containing [<1>, <2>] in relative order", containsInRelativeOrder(1, 2)); } public static class WithValue { private final int value; public WithValue(int value) { this.value = value; } public int getValue() { return value; } @Override public String toString() { return "WithValue " + value; } } public static WithValue make(int value) { return new WithValue(value); } public static Matcher value(int value) { return new FeatureMatcher(equalTo(value), "value with", "value") { @Override protected Integer featureValueOf(WithValue actual) { return actual.getValue(); } }; } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsIterableWithSizeTest.java000066400000000000000000000022701355170103300321660ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.Arrays; import java.util.Collections; import static org.hamcrest.collection.IsIterableWithSize.iterableWithSize; public class IsIterableWithSizeTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return iterableWithSize(7); } public void testMatchesEmptyIterable() throws Exception { assertMatches("Empty iterable", iterableWithSize(0), Collections.emptyList()); } public void testMatchingSingleItemIterable() throws Exception { assertMatches("Single item iterable", iterableWithSize(1), Arrays.asList(1)); } public void testMatchingMultipleItemIterable() throws Exception { assertMatches("Multiple item iterable", iterableWithSize(3), Arrays.asList(1, 2, 3)); } public void testDoesNotMatchIncorrectSize() throws Exception { assertDoesNotMatch("Incorrect size", iterableWithSize(3), Arrays.asList(1)); } public void testHasAReadableDescription() { assertDescription("an iterable with size <4>", iterableWithSize(4)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java000066400000000000000000000047331355170103300321560ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsMapContaining.hasKey; public class IsMapContainingKeyTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasKey("foo"); } public void testMatchesSingletonMapContainingKey() { Map map = new HashMap(); map.put("a", 1); assertMatches("Matches single key", hasKey("a"), map); } public void testMatchesMapContainingKey() { Map map = new HashMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); assertMatches("Matches a", hasKey("a"), map); assertMatches("Matches c", hasKey("c"), map); } // No longer compiles // public void testMatchesMapContainingKeyWithNoGenerics() { // Map map = new HashMap(); // map.put("a", 1); // map.put("b", 2); // map.put("c", 3); // // assertMatches("Matches a", hasKey("a"), map); // assertMatches("Matches c", hasKey("c"), map); // } public void testMatchesMapContainingKeyWithIntegerKeys() throws Exception { Map map = new HashMap(); map.put(1, "A"); map.put(2, "B"); assertThat(map, hasKey(1)); } public void testMatchesMapContainingKeyWithNumberKeys() throws Exception { Map map = new HashMap(); map.put(1, "A"); map.put(2, "B"); assertThat(map, hasKey((Number)1)); // TODO: work out the correct sprinkling of wildcards to get this to work! // assertThat(map, hasKey(1)); } public void testHasReadableDescription() { assertDescription("map containing [\"a\"->ANYTHING]", hasKey("a")); } public void testDoesNotMatchEmptyMap() { assertMismatchDescription("map was []", hasKey("Foo"), new HashMap()); } public void testDoesNotMatchMapMissingKey() { Map map = new TreeMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); assertMismatchDescription("map was [, , ]", hasKey("d"), map); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java000066400000000000000000000033031355170103300314750ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; public class IsMapContainingTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return IsMapContaining.hasEntry("irrelevant", "irrelevant"); } public void testMatchesMapContainingMatchingKeyAndValue() { Map map = new TreeMap<>(); map.put("a", 1); map.put("b", 2); assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); assertMismatchDescription("map was [, ]", hasEntry(equalTo("c"), equalTo(3)), map); } @SuppressWarnings("unchecked") public void testMatchesMapContainingMatchingKeyAndValueWithoutGenerics() { Map map = new HashMap(); map.put("a", 1); map.put("b", 2); assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); assertFalse("matcherC", hasEntry(equalTo("c"), equalTo(3)).matches(map)); // working around generics problem } public void testDoesNotMatchNull() { assertMismatchDescription("was null", hasEntry(anything(), anything()), null); } public void testHasReadableDescription() { assertDescription("map containing [\"a\"-><2>]", hasEntry(equalTo("a"), (equalTo(2)))); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingValueTest.java000066400000000000000000000025431355170103300324770ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import static org.hamcrest.collection.IsMapContaining.hasValue; public class IsMapContainingValueTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasValue("foo"); } public void testHasReadableDescription() { assertDescription("map containing [ANYTHING->\"a\"]", hasValue("a")); } public void testDoesNotMatchEmptyMap() { Map map = new HashMap(); assertMismatchDescription("map was []", hasValue(1), map); } public void testMatchesSingletonMapContainingValue() { Map map = new HashMap(); map.put("a", 1); assertMatches("Singleton map", hasValue(1), map); } public void testMatchesMapContainingValue() { Map map = new TreeMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); assertMatches("hasValue 1", hasValue(1), map); assertMatches("hasValue 3", hasValue(3), map); assertMismatchDescription("map was [, , ]", hasValue(4), map); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/collection/IsMapWithSizeTest.java000066400000000000000000000064371355170103300311650ustar00rootroot00000000000000package org.hamcrest.collection; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import java.util.HashMap; import java.util.Map; import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; import static org.hamcrest.core.IsEqual.equalTo; public final class IsMapWithSizeTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return aMapWithSize(7); } public void testMatchesWhenSizeIsCorrect() { assertMatches("correct size", aMapWithSize(equalTo(2)), mapWithKeys("a", "b")); assertMismatchDescription("map size was <3>", aMapWithSize(equalTo(2)), mapWithKeys("a", "b", "c")); } public void testMatchesMapWhenSizeIsCorrectUsingObjectElementType() { Map map = mapWithKeys(new Object(), new Object()); assertMatches("correct size", aMapWithSize(equalTo(2)), map); assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); } public void testMatchesMapWhenSizeIsCorrectUsingStringElementType() { Map map = mapWithKeys("a", "b"); assertMatches("correct size", aMapWithSize(equalTo(2)), map); assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); } public void testMatchesMapWhenSizeIsCorrectUsingWildcardElementType() { Map map = mapWithKeys("a", "b"); assertMatches("correct size", aMapWithSize(equalTo(2)), map); assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); } public void testMatchesListWhenSizeIsCorrectUsingObjectElementType() { Map map = mapWithKeys(new Object(), new Object()); assertMatches("correct size", aMapWithSize(equalTo(2)), map); assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); } public void testMatchesListWhenSizeIsCorrectUsingStringElementType() { Map list = mapWithKeys("a", "b"); assertMatches("correct size", aMapWithSize(equalTo(2)), list); assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), list); } public void testMatchesListWhenSizeIsCorrectUsingWildcardElementType() { Map list = mapWithKeys("a", "b"); assertMatches("correct size", aMapWithSize(equalTo(2)), list); assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), list); } public void testProvidesConvenientShortcutForHasSizeEqualTo() { assertMatches("correct size", aMapWithSize(2), mapWithKeys(new Object(), new Object())); assertMismatchDescription("map size was <3>", aMapWithSize(2), mapWithKeys(new Object(), new Object(), new Object())); } public void testHasAReadableDescription() { assertDescription("a map with size <3>", aMapWithSize(equalTo(3))); } public void testCompilesWithATypedMap() { Map arrayList = new HashMap(); MatcherAssert.assertThat(arrayList, aMapWithSize(0)); } private static Map mapWithKeys(K... keys) { final Map result = new HashMap(); for (K key : keys) { result.put(key, null); } return result; } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/comparator/000077500000000000000000000000001355170103300247645ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherBuilderTest.java000066400000000000000000000154321355170103300334160ustar00rootroot00000000000000package org.hamcrest.comparator; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.math.BigDecimal; import java.util.Comparator; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.comparator.ComparatorMatcherBuilder.comparedBy; import static org.hamcrest.core.IsNot.not; public class ComparatorMatcherBuilderTest extends AbstractMatcherTest { private final ComparatorMatcherBuilder integerComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); private final ComparatorMatcherBuilder doubleComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); private final ComparatorMatcherBuilder stringComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); private final ComparatorMatcherBuilder bigDecimalComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); private final Comparator backwardsIntegerComparator = new Comparator() { @Override public int compare(Integer o1, Integer o2) { return -o1.compareTo(o2); } @Override public String toString() { return "backwards integer comparator"; } }; @Override protected Matcher createMatcher() { return integerComparatorMatcherBuilder.greaterThan(1); } public void testDescription() { assertDescription("a value greater than <1>", integerComparatorMatcherBuilder.greaterThan(1)); assertDescription("a value equal to or greater than <1>", integerComparatorMatcherBuilder.greaterThanOrEqualTo(1)); assertDescription("a value equal to <1>", integerComparatorMatcherBuilder.comparesEqualTo(1)); assertDescription("a value less than or equal to <1>", integerComparatorMatcherBuilder.lessThanOrEqualTo(1)); assertDescription("a value less than <1>", integerComparatorMatcherBuilder.lessThan(1)); assertDescription("a value greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(1)); assertDescription("a value equal to or greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThanOrEqualTo(1)); assertDescription("a value equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).comparesEqualTo(1)); assertDescription("a value less than or equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThanOrEqualTo(1)); assertDescription("a value less than <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(1)); } public void testMismatchDescriptions() { assertMismatchDescription("<0> was less than <1>", integerComparatorMatcherBuilder.greaterThan(1), 0); assertMismatchDescription("<1> was equal to <1>", integerComparatorMatcherBuilder.greaterThan(1), 1); assertMismatchDescription("<1> was greater than <0>", integerComparatorMatcherBuilder.lessThan(0), 1); assertMismatchDescription("<2> was equal to <2>", integerComparatorMatcherBuilder.lessThan(2), 2); assertMismatchDescription("<1> was less than <0> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(0), 1); assertMismatchDescription("<1> was equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(1), 1); assertMismatchDescription("<0> was greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(1), 0); assertMismatchDescription("<2> was equal to <2> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(2), 2); } public void testComparesObjectsForGreaterThan() { assertThat(2, integerComparatorMatcherBuilder.greaterThan(1)); assertThat(0, not(integerComparatorMatcherBuilder.greaterThan(1))); } public void testComparesObjectsForLessThan() { assertThat(2, integerComparatorMatcherBuilder.lessThan(3)); assertThat(0, integerComparatorMatcherBuilder.lessThan(1)); } public void testComparesObjectsForEquality() { assertThat(3, integerComparatorMatcherBuilder.comparesEqualTo(3)); assertThat("aa", stringComparatorMatcherBuilder.comparesEqualTo("aa")); } public void testAllowsForInclusiveComparisons() { assertThat("less", 1, integerComparatorMatcherBuilder.lessThanOrEqualTo(1)); assertThat("greater", 1, integerComparatorMatcherBuilder.greaterThanOrEqualTo(1)); } public void testSupportsDifferentTypesOfComparableObjects() { assertThat(1.1, doubleComparatorMatcherBuilder.greaterThan(1.0)); assertThat("cc", stringComparatorMatcherBuilder.greaterThan("bb")); } public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() { assertThat(new BigDecimal("10.0"), bigDecimalComparatorMatcherBuilder.greaterThanOrEqualTo(new BigDecimal("10"))); assertThat(new BigDecimal(10), bigDecimalComparatorMatcherBuilder.greaterThanOrEqualTo(new BigDecimal("10.0"))); assertThat(new BigDecimal("2"), bigDecimalComparatorMatcherBuilder.comparesEqualTo(new BigDecimal("2.000"))); } public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() { assertThat(new CustomInt(5), ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(new CustomInt(10))); } public void testComparesByCustomComparator() { assertThat(5, comparedBy(backwardsIntegerComparator).lessThan(4)); } public void testJavadocExamples() { assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().comparesEqualTo(1)); assertThat(2, ComparatorMatcherBuilder.usingNaturalOrdering().greaterThan(1)); assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().greaterThanOrEqualTo(1)); assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(2)); assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().lessThanOrEqualTo(1)); assertThat(5, comparedBy(new Comparator() { @Override public int compare(Integer o1, Integer o2) { return -o1.compareTo(o2); } }).lessThan(4)); } private static final class CustomInt implements Comparable { private final int value; public CustomInt(int value) { this.value = value; } @Override public int compareTo(CustomInt other) { return value - other.value; } } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherTest.java000066400000000000000000000057451355170103300321150ustar00rootroot00000000000000package org.hamcrest.comparator; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.math.BigDecimal; import java.util.Comparator; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.number.OrderingComparison.*; public class ComparatorMatcherTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return ComparatorMatcherBuilder.comparedBy(new Comparator() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }).greaterThan(1); } public void testDescription() { assertDescription("a value greater than <1>", greaterThan(1)); assertDescription("a value equal to or greater than <1>", greaterThanOrEqualTo(1)); assertDescription("a value equal to <1>", comparesEqualTo(1)); assertDescription("a value less than or equal to <1>", lessThanOrEqualTo(1)); assertDescription("a value less than <1>", lessThan(1)); } public void testMismatchDescriptions() { assertMismatchDescription("<0> was less than <1>", greaterThan(1), 0); assertMismatchDescription("<1> was equal to <1>", greaterThan(1), 1); assertMismatchDescription("<1> was greater than <0>", lessThan(0), 1); assertMismatchDescription("<2> was equal to <2>", lessThan(2), 2); } public void testComparesObjectsForGreaterThan() { assertThat(2, greaterThan(1)); assertThat(0, not(greaterThan(1))); } public void testComparesObjectsForLessThan() { assertThat(2, lessThan(3)); assertThat(0, lessThan(1)); } public void testComparesObjectsForEquality() { assertThat(3, comparesEqualTo(3)); assertThat("aa", comparesEqualTo("aa")); } public void testAllowsForInclusiveComparisons() { assertThat("less", 1, lessThanOrEqualTo(1)); assertThat("greater", 1, greaterThanOrEqualTo(1)); } public void testSupportsDifferentTypesOfComparableObjects() { assertThat(1.1, greaterThan(1.0)); assertThat("cc", greaterThan("bb")); } public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() { assertThat(new BigDecimal("10.0"), greaterThanOrEqualTo(new BigDecimal("10"))); assertThat(new BigDecimal(10), greaterThanOrEqualTo(new BigDecimal("10.0"))); assertThat(new BigDecimal("2"), comparesEqualTo(new BigDecimal("2.000"))); } public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() { assertThat(new CustomInt(5), lessThan(new CustomInt(10))); } private static final class CustomInt implements Comparable { private final int value; public CustomInt(int value) { this.value = value; } public int compareTo(CustomInt other) { return value - other.value; } } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/000077500000000000000000000000001355170103300235455ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/AllOfTest.java000066400000000000000000000051351355170103300262510ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; public final class AllOfTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = allOf(equalTo("irrelevant"), startsWith("irr")); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void evaluatesToTheTheLogicalConjunctionOfTwoOtherMatchers() { Matcher matcher = allOf(startsWith("goo"), endsWith("ood")); assertMatches("didn't pass both sub-matchers", matcher, "good"); assertDoesNotMatch("didn't fail first sub-matcher", matcher, "mood"); assertDoesNotMatch("didn't fail second sub-matcher", matcher, "goon"); assertDoesNotMatch("didn't fail both sub-matchers", matcher, "fred"); } @Test public void evaluatesToTheTheLogicalConjunctionOfManyOtherMatchers() { Matcher matcher = allOf(startsWith("g"), startsWith("go"), endsWith("d"), startsWith("go"), startsWith("goo")); assertMatches("didn't pass all sub-matchers", matcher, "good"); assertDoesNotMatch("didn't fail middle sub-matcher", matcher, "goon"); } @Test public void supportsMixedTypes() { final Matcher matcher = allOf( equalTo(new SampleBaseClass("bad")), is(notNullValue()), equalTo(new SampleBaseClass("good")), equalTo(new SampleSubClass("ugly"))); assertDoesNotMatch("didn't fail last sub-matcher", matcher, new SampleSubClass("good")); } @Test public void hasAReadableDescription() { assertDescription("(\"good\" and \"bad\" and \"ugly\")", allOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); } @Test public void hasAMismatchDescriptionDescribingTheFirstFailingMatch() { assertMismatchDescription("\"good\" was \"bad\"", allOf(equalTo("bad"), equalTo("good")), "bad"); } @Test public void varargs(){ assertThat("the text!", new AllOf<>(startsWith("the"), containsString("text"), endsWith("!"))); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/AnyOfTest.java000066400000000000000000000043111355170103300262630ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; public final class AnyOfTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = anyOf(equalTo("irrelevant"), startsWith("irr")); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void evaluatesToTheTheLogicalDisjunctionOfTwoOtherMatchers() { Matcher matcher = anyOf(startsWith("goo"), endsWith("ood")); assertMatches("didn't pass both sub-matchers", matcher, "good"); assertMatches("didn't pass second sub-matcher", matcher, "mood"); assertMatches("didn't pass first sub-matcher", matcher, "goon"); assertDoesNotMatch("didn't fail both sub-matchers", matcher, "flan"); } @Test public void evaluatesToTheTheLogicalDisjunctionOfManyOtherMatchers() { Matcher matcher = anyOf(startsWith("g"), startsWith("go"), endsWith("d"), startsWith("go"), startsWith("goo")); assertMatches("didn't pass middle sub-matcher", matcher, "vlad"); assertDoesNotMatch("didn't fail all sub-matchers", matcher, "flan"); } @SuppressWarnings("unchecked") @Test public void supportsMixedTypes() { final Matcher matcher = anyOf( equalTo(new SampleBaseClass("bad")), equalTo(new SampleBaseClass("good")), equalTo(new SampleSubClass("ugly"))); assertMatches("didn't pass middle sub-matcher", matcher, new SampleSubClass("good")); } @Test public void hasAReadableDescription() { assertDescription("(\"good\" or \"bad\" or \"ugly\")", anyOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); } @Test public void varargs(){ assertThat("the text!", new AnyOf<>(startsWith("the"), endsWith("."))); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/CombinableTest.java000066400000000000000000000044751355170103300273150ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; public final class CombinableTest { private static final CombinableMatcher EITHER_3_OR_4 = CombinableMatcher.either(equalTo(3)).or(equalTo(4)); private static final CombinableMatcher NOT_3_AND_NOT_4 = CombinableMatcher.both(not(equalTo(3))).and(not(equalTo(4))); @Test public void copesWithNullsAndUnknownTypes() { assertNullSafe(EITHER_3_OR_4); assertNullSafe(NOT_3_AND_NOT_4); assertUnknownTypeSafe(EITHER_3_OR_4); assertUnknownTypeSafe(NOT_3_AND_NOT_4); } @Test public void bothAcceptsAndRejects() { assertMatches("both didn't pass", NOT_3_AND_NOT_4, 2); assertDoesNotMatch("both didn't fail", NOT_3_AND_NOT_4, 3); } @Test public void acceptsAndRejectsThreeAnds() { CombinableMatcher tripleAnd = NOT_3_AND_NOT_4.and(equalTo(2)); assertMatches("tripleAnd didn't pass", tripleAnd, 2); assertDoesNotMatch("tripleAnd didn't fail", tripleAnd, 3); } @Test public void bothDescribesItself() { assertDescription("(not <3> and not <4>)", NOT_3_AND_NOT_4); assertMismatchDescription("not <3> was <3>", NOT_3_AND_NOT_4, 3); } @Test public void eitherAcceptsAndRejects() { assertMatches("either didn't pass", EITHER_3_OR_4, 3); assertDoesNotMatch("either didn't fail", EITHER_3_OR_4, 6); } @Test public void acceptsAndRejectsThreeOrs() { final CombinableMatcher tripleOr = EITHER_3_OR_4.or(equalTo(11)); assertMatches("tripleOr didn't pass", tripleOr, 11); assertDoesNotMatch("tripleOr didn't fail", tripleOr, 9); } @Test public void eitherDescribesItself() { assertDescription("(<3> or <4>)", EITHER_3_OR_4); assertMismatchDescription("was <6>", EITHER_3_OR_4, 6); } @Test public void picksUpTypeFromLeftHandSideOfExpression() { @SuppressWarnings("unused") Matcher matcher = CombinableMatcher.both(equalTo("yellow")).and(notNullValue(String.class)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/DescribedAsTest.java000066400000000000000000000026541355170103300274270ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.DescribedAs.describedAs; import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; public final class DescribedAsTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = describedAs("irrelevant", anything()); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void overridesDescriptionOfOtherMatcherWithThatPassedToConstructor() { Matcher matcher = describedAs("my description", anything()); assertDescription("my description", matcher); } @Test public void appendsValuesToDescription() { Matcher matcher = describedAs("value 1 = %0, value 2 = %1", anything(), 33, 97); assertDescription("value 1 = <33>, value 2 = <97>", matcher); } @Test public void celegatesMatchingToAnotherMatcher() { Matcher matcher = describedAs("irrelevant", equalTo("hi")); assertMatches(matcher, "hi"); assertDoesNotMatch("matched", matcher, "oi"); } @Test public void delegatesMismatchDescriptionToAnotherMatcher() { Matcher matcher = describedAs("irrelevant", equalTo(2)); assertMismatchDescription("was <1>", matcher, 1); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/EveryTest.java000066400000000000000000000022631355170103300263450ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import java.util.ArrayList; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.StringContains.containsString; public final class EveryTest { private final Matcher> matcher = Every.everyItem(containsString("a")); @Test public void copesWithNullsAndUnknownTypes() { assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesOnlyWhenEveryItemMatches() { assertMatches(matcher, asList("AaA", "BaB", "CaC")); assertDoesNotMatch(matcher, asList("AaA", "BXB", "CaC")); } @Test public void matchesEmptyLists() { assertMatches("didn't match empty list", matcher, new ArrayList()); } @Test public void describesItself() { assertDescription("every item is a string containing \"a\"", matcher); } @Test public void describesAMismatch() { assertMismatchDescription("an item was \"BXB\"", matcher, singletonList("BXB")); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsAnythingTest.java000066400000000000000000000023161355170103300273270ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.assertDescription; import static org.hamcrest.AbstractMatcherTest.assertMatches; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsAnything.anything; public final class IsAnythingTest { private final Matcher matcher = anything(); private static class CustomThing { } @Test public void alwaysEvaluatesToTrue() { assertMatches("didn't match null", matcher, null); assertMatches("didn't match Object", matcher, new Object()); assertMatches("didn't match custom object", matcher, new CustomThing()); assertMatches("didn't match String", matcher, "hi"); } @Test public void compilesWithoutTypeWarnings() { assertThat(new CustomThing(), is(anything())); } @Test public void hasUsefulDefaultDescription() { assertDescription("ANYTHING", matcher); } @Test public void canOverrideDescription() { String description = "description"; assertDescription(description, anything(description)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsCollectionContainingTest.java000066400000000000000000000077261355170103300316650ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsCollectionContaining.hasItem; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsEqual.equalTo; public class IsCollectionContainingTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasItem(equalTo("irrelevant")); } public void testMatchesACollectionThatContainsAnElementMatchingTheGivenMatcher() { Matcher> itemMatcher = hasItem(equalTo("a")); assertMatches("should match list that contains 'a'", itemMatcher, asList("a", "b", "c")); } public void testDoesNotMatchCollectionThatDoesntContainAnElementMatchingTheGivenMatcher() { final Matcher> matcher1 = hasItem(mismatchable("a")); assertMismatchDescription("mismatches were: [mismatched: b, mismatched: c]", matcher1, asList("b", "c")); final Matcher> matcher2 = hasItem(equalTo("a")); assertMismatchDescription("was empty", matcher2, new ArrayList()); } public void testDoesNotMatchNull() { assertDoesNotMatch("should not matches null", hasItem(equalTo("a")), null); } public void testHasAReadableDescription() { assertDescription("a collection containing \"a\"", hasItem(equalTo("a"))); } public void testCanMatchItemWhenCollectionHoldsSuperclass() // Issue 24 { final Set s = new HashSet(); s.add(Integer.valueOf(2)); assertThat(s, new IsCollectionContaining(new IsEqual(Integer.valueOf(2)))); assertThat(s, IsCollectionContaining.hasItem(Integer.valueOf(2))); } @SuppressWarnings("unchecked") public void testMatchesAllItemsInCollection() { final Matcher> matcher1 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("should match list containing all items", matcher1, asList("a", "b", "c")); final Matcher> matcher2 = hasItems("a", "b", "c"); assertMatches("should match list containing all items (without matchers)", matcher2, asList("a", "b", "c")); final Matcher> matcher3 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("should match list containing all items in any order", matcher3, asList("c", "b", "a")); final Matcher> matcher4 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("should match list containing all items plus others", matcher4, asList("e", "c", "b", "a", "d")); final Matcher> matcher5 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertDoesNotMatch("should not match list unless it contains all items", matcher5, asList("e", "c", "b", "d")); // 'a' missing } private static Matcher mismatchable(final String string) { return new TypeSafeDiagnosingMatcher() { @Override protected boolean matchesSafely(String item, Description mismatchDescription) { if (string.equals(item)) return true; mismatchDescription.appendText("mismatched: " + item); return false; } @Override public void describeTo(Description description) { description.appendText("mismatchable: " + string); } }; } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java000066400000000000000000000114071355170103300266160ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsEqual.equalToObject; public final class IsEqualTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = equalTo("irrelevant"); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void comparesObjectsUsingEqualsMethod() { final Matcher matcher1 = equalTo("hi"); assertMatches(matcher1, "hi"); assertDoesNotMatch(matcher1, "bye"); assertDoesNotMatch(matcher1, null); final Matcher matcher2 = equalTo(1); assertMatches(matcher2, 1); assertDoesNotMatch(matcher2, 2); assertDoesNotMatch(matcher2, null); } @Test public void canCompareNullValues() { final Matcher matcher = equalTo(null); assertMatches(matcher, null); assertDoesNotMatch(matcher, 2); assertDoesNotMatch(matcher, "hi"); assertDoesNotMatch(matcher, new String[] {"a", "b"}); } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Test public void honoursIsEqualImplementationEvenWithNullValues() { Object alwaysEqual = new Object() { @Override public boolean equals(Object obj) { return true; } }; Object neverEqual = new Object() { @Override public boolean equals(Object obj) { return false; } }; Matcher matcher = equalTo(null); assertMatches(matcher, alwaysEqual); assertDoesNotMatch(matcher, neverEqual); } @Test public void comparesTheElementsOfAnObjectArray() { String[] s1 = {"a", "b"}; String[] s2 = {"a", "b"}; String[] s3 = {"c", "d"}; String[] s4 = {"a", "b", "c", "d"}; final Matcher matcher = equalTo(s1); assertMatches(matcher, s1); assertMatches(matcher, s2); assertDoesNotMatch(matcher, s3); assertDoesNotMatch(matcher, s4); assertDoesNotMatch(matcher, null); } @Test public void comparesTheElementsOfArraysWithNulls() { String[] s1 = {"a", null, "b"}; String[] s2 = {"a", null, "b"}; String[] s3 = {"c", "d"}; String[] s4 = {"a", "b", "c", "d"}; final Matcher matcher = equalTo(s1); assertMatches(matcher, s1); assertMatches(matcher, s2); assertDoesNotMatch(matcher, s3); assertDoesNotMatch(matcher, s4); } @Test public void comparesTheElementsOfAnArrayOfPrimitiveTypes() { int[] i1 = new int[]{1, 2}; int[] i2 = new int[]{1, 2}; int[] i3 = new int[]{3, 4}; int[] i4 = new int[]{1, 2, 3, 4}; final Matcher matcher = equalTo(i1); assertMatches(matcher, i1); assertMatches(matcher, i2); assertDoesNotMatch(matcher, i3); assertDoesNotMatch(matcher, i4); assertDoesNotMatch(matcher, null); } @Test public void recursivelyTestsElementsOfArrays() { int[][] i1 = new int[][]{{1, 2}, {3, 4}}; int[][] i2 = new int[][]{{1, 2}, {3, 4}}; int[][] i3 = new int[][]{{5, 6}, {7, 8}}; int[][] i4 = new int[][]{{1, 2, 3, 4}, {3, 4}}; final Matcher matcher = equalTo(i1); assertMatches(matcher, i1); assertMatches(matcher, i2); assertDoesNotMatch(matcher, i3); assertDoesNotMatch(matcher, i4); assertDoesNotMatch(matcher, null); } @Test public void hasUntypedVariant() { Object original = 10; assertMatches(equalToObject(10), original); assertDoesNotMatch(equalToObject(0), original); assertDoesNotMatch(equalToObject("10"), original); assertDoesNotMatch(equalToObject(10), "10"); } @Test public void includesTheResultOfCallingToStringOnItsArgumentInTheDescription() { final String argumentDescription = "ARGUMENT DESCRIPTION"; Object argument = new Object() { @Override public String toString() { return argumentDescription; } }; assertDescription("<" + argumentDescription + ">", equalTo(argument)); } @Test public void returnsAnObviousDescriptionIfCreatedWithANestedMatcherByMistake() { Matcher innerMatcher = equalTo("NestedMatcher"); assertDescription("<" + innerMatcher.toString() + ">", equalTo(innerMatcher)); } @Test public void returnsGoodDescriptionIfCreatedWithNullReference() { assertDescription("null", equalTo(null)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsInstanceOfTest.java000066400000000000000000000037771355170103300276130ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsInstanceOf.any; import static org.hamcrest.core.IsInstanceOf.instanceOf; public final class IsInstanceOfTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = instanceOf(Number.class); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void evaluatesToTrueIfArgumentIsInstanceOfASpecificClass() { final Matcher matcher = instanceOf(Number.class); assertMatches(matcher, 1); assertMatches(matcher, 1.1); assertDoesNotMatch(matcher, null); assertDoesNotMatch(matcher, new Object()); } @Test public void hasAReadableDescription() { assertDescription("an instance of java.lang.Number", instanceOf(Number.class)); } @Test public void describesActualClassInMismatchMessage() { assertMismatchDescription("\"some text\" is a java.lang.String", instanceOf(Number.class), "some text"); } @Test public void matchesPrimitiveTypes() { assertMatches(any(boolean.class), true); assertMatches(any(byte.class), (byte)1); assertMatches(any(char.class), 'x'); assertMatches(any(double.class), 5.0); assertMatches(any(float.class), 5.0f); assertMatches(any(int.class), 2); assertMatches(any(long.class), 4L); assertMatches(any(short.class), (short)1); } @Test public void instanceOfRequiresACastToReturnTheCorrectTypeForUseInJMock() { @SuppressWarnings("unused") Integer anInteger = (Integer)with(instanceOf(Integer.class)); } @Test public void anyWillReturnTheCorrectTypeForUseInJMock() { @SuppressWarnings("unused") Integer anInteger = with(any(Integer.class)); } private static T with(@SuppressWarnings("unused") Matcher matcher) { return null; } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsIterableContainingTest.java000066400000000000000000000100271355170103300313050ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import static java.util.Arrays.asList; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsIterableContaining.hasItem; import static org.hamcrest.core.IsIterableContaining.hasItems; import static org.hamcrest.core.IsEqual.equalTo; public final class IsIterableContainingTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = hasItem(equalTo("irrelevant")); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesACollectionThatContainsAnElementForTheGivenMatcher() { final Matcher> itemMatcher = hasItem(equalTo("a")); assertMatches("list containing 'a'", itemMatcher, asList("a", "b", "c")); } @Test public void doesNotMatchCollectionWithoutAnElementForGivenMatcher() { final Matcher> matcher = hasItem(mismatchable("a")); assertMismatchDescription("mismatches were: [mismatched: b, mismatched: c]", matcher, asList("b", "c")); assertMismatchDescription("was empty", matcher, new ArrayList()); } @Test public void doesNotMatchNull() { assertDoesNotMatch("doesn't match null", hasItem(equalTo("a")), null); } @Test public void hasAReadableDescription() { assertDescription("a collection containing mismatchable: a", hasItem(mismatchable("a"))); } @Test public void canMatchItemWhenCollectionHoldsSuperclass() { // Issue 24 final Set s = new HashSet<>(); s.add(2); assertMatches(new IsIterableContaining<>(new IsEqual(2)), s); assertMatches(IsIterableContaining.hasItem(2), s); } @SuppressWarnings("unchecked") @Test public void matchesMultipleItemsInCollection() { final Matcher> matcher1 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("list containing all items", matcher1, asList("a", "b", "c")); final Matcher> matcher2 = hasItems("a", "b", "c"); assertMatches("list containing all items (without matchers)", matcher2, asList("a", "b", "c")); final Matcher> matcher3 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("list containing all items in any order", matcher3, asList("c", "b", "a")); final Matcher> matcher4 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertMatches("list containing all items plus others", matcher4, asList("e", "c", "b", "a", "d")); final Matcher> matcher5 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); assertDoesNotMatch("not match list unless it contains all items", matcher5, asList("e", "c", "b", "d")); // 'a' missing } @Test public void reportsMismatchWithAReadableDescriptionForMultipleItems() { final Matcher> matcher = hasItems(3, 4); assertMismatchDescription("a collection containing <4> mismatches were: [was <1>, was <2>, was <3>]", matcher, asList(1, 2, 3)); } private static Matcher mismatchable(final String string) { return new TypeSafeDiagnosingMatcher() { @Override protected boolean matchesSafely(String item, Description mismatchDescription) { if (string.equals(item)) return true; mismatchDescription.appendText("mismatched: " + item); return false; } @Override public void describeTo(Description description) { description.appendText("mismatchable: " + string); } }; } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsNotTest.java000066400000000000000000000022151355170103300263040ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsNot.not; public final class IsNotTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = not("something"); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void evaluatesToTheTheLogicalNegationOfAnotherMatcher() { final Matcher matcher = not(equalTo("A")); assertMatches(matcher, "B"); assertDoesNotMatch(matcher, "A"); } @Test public void providesConvenientShortcutForNotEqualTo() { final Matcher matcher = not("A"); assertMatches(matcher, "B"); assertDoesNotMatch(matcher, "A"); } @Test public void usesDescriptionOfNegatedMatcherWithPrefix() { assertDescription("not an instance of java.lang.String", not(instanceOf(String.class))); assertDescription("not \"A\"", not("A")); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsNullTest.java000066400000000000000000000022741355170103300264630ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; public final class IsNullTest { private final Matcher nullMatcher = nullValue(); private final Matcher notNullMatcher = notNullValue(); @Test public void copesWithNullsAndUnknownTypes() { assertNullSafe(nullMatcher); assertUnknownTypeSafe(nullMatcher); assertNullSafe(notNullMatcher); assertUnknownTypeSafe(notNullMatcher); } @Test public void evaluatesToTrueIfArgumentIsNull() { assertMatches(nullMatcher, null); assertDoesNotMatch(nullMatcher, new Object()); assertMatches(notNullMatcher, new Object()); assertDoesNotMatch(notNullMatcher, null); } @Test public void supportsStaticTyping() { requiresStringMatcher(nullValue(String.class)); requiresStringMatcher(notNullValue(String.class)); } private void requiresStringMatcher(@SuppressWarnings("unused") Matcher arg) { // no-op } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsSameTest.java000066400000000000000000000025131355170103300264320ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsSame.sameInstance; import static org.hamcrest.core.IsSame.theInstance; public final class IsSameTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = sameInstance("irrelevant"); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void evaluatesToTrueIfArgumentIsReferenceToASpecifiedObject() { Object o1 = new Object(); Matcher matcher = sameInstance(o1); assertMatches(matcher, o1); assertDoesNotMatch(matcher, new Object()); } @Test public void alternativeFactoryMethodAlsoMatchesOnlyIfArgumentIsReferenceToASpecifiedObject() { Object o1 = new Object(); Matcher matcher = theInstance(o1); assertMatches(matcher, o1); assertDoesNotMatch(matcher, new Object()); } @Test public void returnsReadableDescriptionFromToString() { assertDescription("sameInstance(\"ARG\")", sameInstance("ARG")); } @Test public void returnsReadableDescriptionFromToStringWhenInitialisedWithNull() { assertDescription("sameInstance(null)", sameInstance(null)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/IsTest.java000066400000000000000000000026021355170103300256230ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.isA; import static org.hamcrest.core.IsEqual.equalTo; public final class IsTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = is("something"); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesTheSameWayTheUnderlyingMatcherDoes() { final Matcher matcher = is(equalTo(true)); assertMatches(matcher, true); assertDoesNotMatch(matcher, false); } @Test public void generatesIsPrefixInDescription() { assertDescription("is ", is(equalTo(true))); assertDescription("is \"A\"", is("A")); } @Test public void providesConvenientShortcutForIsEqualTo() { final Matcher matcher = is("A"); assertMatches(matcher, "A"); assertDoesNotMatch(is("A"), "B"); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void providesConvenientShortcutForIsInstanceOf() { final Matcher matcher = isA(Number.class); assertMatches(matcher, 1); assertDoesNotMatch(matcher, new Object()); assertDoesNotMatch(matcher, null); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/SampleBaseClass.java000066400000000000000000000007221355170103300274130ustar00rootroot00000000000000package org.hamcrest.core; public class SampleBaseClass { String value; public SampleBaseClass(String value) { this.value = value; } @Override public String toString() { return value; } @Override public boolean equals(Object obj) { return obj instanceof SampleBaseClass && value.equals(((SampleBaseClass) obj).value); } @Override public int hashCode() { return value.hashCode(); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/SampleSubClass.java000066400000000000000000000002401355170103300272650ustar00rootroot00000000000000package org.hamcrest.core; public class SampleSubClass extends SampleBaseClass { public SampleSubClass(String value) { super(value); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/StringContainsTest.java000066400000000000000000000033251355170103300302200ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.core.StringContains.containsStringIgnoringCase; public class StringContainsTest extends AbstractMatcherTest { static final String EXCERPT = "EXCERPT"; final Matcher stringContains = containsString(EXCERPT); @Override protected Matcher createMatcher() { return stringContains; } public void testMatchesSubstrings() { assertMatches(stringContains, EXCERPT + "END"); assertMatches(stringContains, "START" + EXCERPT); assertMatches(stringContains, "START" + EXCERPT + "END"); assertMatches(stringContains, EXCERPT); assertDoesNotMatch(stringContains, EXCERPT.toLowerCase()); assertMatches(stringContains, EXCERPT + EXCERPT); assertDoesNotMatch(stringContains, "XC"); assertMismatchDescription("was \"Something else\"", stringContains, "Something else"); assertDescription("a string containing \"EXCERPT\"", stringContains); } public void testMatchesSubstringsIgnoringCase() { final Matcher ignoringCase = containsStringIgnoringCase("ExCert"); assertMatches(ignoringCase, "eXcERT" + "END"); assertMatches(ignoringCase, "START" + "EXCert"); assertMatches(ignoringCase, "START" + "excERT" + "END"); assertMatches(ignoringCase, "eXCert" + "excErt"); assertDoesNotMatch(ignoringCase, "xc"); assertMismatchDescription("was \"Something else\"", ignoringCase, "Something else"); assertDescription("a string containing \"ExCert\" ignoring case", ignoringCase); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/StringEndsWithTest.java000066400000000000000000000034271355170103300301720ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringEndsWith.endsWithIgnoringCase; public class StringEndsWithTest extends AbstractMatcherTest { static final String EXCERPT = "EXCERPT"; final Matcher stringEndsWith = endsWith(EXCERPT); @Override protected Matcher createMatcher() { return stringEndsWith; } public void testMatchesSubstringAtEnd() { assertDoesNotMatch(stringEndsWith, EXCERPT + "END"); assertMatches(stringEndsWith, "START" + EXCERPT); assertMatches(stringEndsWith, EXCERPT); assertDoesNotMatch(stringEndsWith, EXCERPT.toLowerCase()); assertDoesNotMatch(stringEndsWith, "START" + EXCERPT + "END"); assertMatches(stringEndsWith, EXCERPT + EXCERPT); assertDoesNotMatch(stringEndsWith, "EXCER"); assertMismatchDescription("was \"Something else\"", stringEndsWith, "Something else"); assertDescription("a string ending with \"EXCERPT\"", stringEndsWith); } public void testMatchesSubstringAtEndIngoringCase() { final Matcher ignoringCase = endsWithIgnoringCase("EXCERpt"); assertDoesNotMatch(ignoringCase, "eXCErpt" + "END"); assertMatches(ignoringCase, "START" + "EXceRpt"); assertMatches(ignoringCase, "EXcerPT"); assertDoesNotMatch(ignoringCase, "START" + "ExcERpt" + "END"); assertMatches(ignoringCase, "exCERpt" + "EXCerPt"); assertDoesNotMatch(ignoringCase, "ExcER"); assertMismatchDescription("was \"Something else\"", ignoringCase, "Something else"); assertDescription("a string ending with \"EXCERpt\" ignoring case", ignoringCase); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/StringMatchingTest.java000066400000000000000000000015601355170103300301730ustar00rootroot00000000000000package org.hamcrest.core; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; /** * @author Steve Freeman 2016 http://www.hamcrest.com */ public class StringMatchingTest { @Rule public final ExpectedException thrown = ExpectedException.none(); @Test public void startsWithFailsWithNullSubstring() { thrown.expect(IllegalArgumentException.class); startsWith(null); } @Test public void endWithFailsWithNullSubstring() { thrown.expect(IllegalArgumentException.class); endsWith(null); } @Test public void containsFailsWithNullSubstring() { thrown.expect(IllegalArgumentException.class); containsString(null); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/StringRegularExpressionTest.java000066400000000000000000000013061355170103300321200ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.core.StringRegularExpression.matchesRegex; /** * @author Steve Freeman 2016 http://www.hamcrest.com */ public class StringRegularExpressionTest extends AbstractMatcherTest { public final Matcher matcher = matchesRegex("^[0-9]+$"); @Override protected Matcher createMatcher() { return matcher; } public void testMatchingRegex() { assertMatches(matcher, "12"); assertDoesNotMatch(matcher, "abc"); assertDescription("a string matching the pattern <^[0-9]+$>", matcher); assertMismatchDescription("the string was \"bcd\"", matcher, "bcd"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java000066400000000000000000000034541355170103300305610ustar00rootroot00000000000000package org.hamcrest.core; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.core.StringStartsWith.startsWithIgnoringCase; public class StringStartsWithTest extends AbstractMatcherTest { static final String EXCERPT = "EXCERPT"; final Matcher stringStartsWith = startsWith(EXCERPT); @Override protected Matcher createMatcher() { return stringStartsWith; } public void testMatchesStringAtStart() { assertMatches(stringStartsWith, EXCERPT + "END"); assertDoesNotMatch(stringStartsWith, "START" + EXCERPT); assertDoesNotMatch(stringStartsWith, "START" + EXCERPT + "END"); assertMatches(stringStartsWith, EXCERPT); assertDoesNotMatch(stringStartsWith, EXCERPT.toLowerCase()); assertMatches(stringStartsWith, EXCERPT + EXCERPT); assertDoesNotMatch(stringStartsWith, "EXCER"); assertDescription("a string starting with \"EXCERPT\"", stringStartsWith); assertMismatchDescription("was \"Something else\"", stringStartsWith, "Something else"); } public void testMatchesStringAtStartIgnoringCase() { final Matcher ignoreCase = startsWithIgnoringCase("EXCerPT"); assertMatches(ignoreCase, "exCerPT" + "END"); assertDoesNotMatch(ignoreCase, "START" + "EXCerpt"); assertDoesNotMatch(ignoreCase, "START" + "EXcerpT" + "END"); assertMatches(ignoreCase, "excERPT"); assertMatches(ignoreCase, "ExcerPT" + "EXCerpt"); assertDoesNotMatch(ignoreCase, "ExcER"); assertDescription("a string starting with \"EXCerPT\" ignoring case", ignoreCase); assertMismatchDescription("was \"Something else\"", ignoreCase, "Something else"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/io/000077500000000000000000000000001355170103300232245ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/io/FileMatchersTest.java000066400000000000000000000076021355170103300273020ustar00rootroot00000000000000package org.hamcrest.io; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.io.File; import java.io.IOException; import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("ResultOfMethodCallIgnored") public class FileMatchersTest extends AbstractMatcherTest { private File directory; private File file; @Override protected void setUp() throws IOException { directory = File.createTempFile("myDir", ""); assertTrue("deleting " + directory, directory.delete()); assertTrue("mkdir " + directory, directory.mkdirs()); file = new File(directory, "myFile"); file.createNewFile(); } public void testAnExistingDirectory() { assertMatches("matches existing directory", FileMatchers.anExistingDirectory(), directory); assertDoesNotMatch("doesn't match existing file", FileMatchers.anExistingDirectory(), file); assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingDirectory(), new File("foo")); } public void testAnExistingFileOrDirectory() { assertMatches("matches existing file", FileMatchers.anExistingFileOrDirectory(), file); assertMatches("matches existing directory", FileMatchers.anExistingFileOrDirectory(), directory); assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingFileOrDirectory(), new File("foo")); } public void testAnExistingFile() { assertMatches("matches existing file", FileMatchers.anExistingFile(), file); assertDoesNotMatch("doesn't match existing directory", FileMatchers.anExistingFile(), directory); assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingFile(), new File("foo")); } public void testAReadableFile() { // Not all OSes will allow setting readability so have to be forgiving here. file.setReadable(true); assertMatches("matches readable file", FileMatchers.aReadableFile(), file); if (file.setReadable(false)) { assertDoesNotMatch("doesn't match unreadable file", FileMatchers.aReadableFile(), file); } } public void testAWritableFile() { assertMatches("matches writable file", FileMatchers.aWritableFile(), file); assertTrue("set writable off " + file, file.setWritable(false)); assertDoesNotMatch("doesn't match unwritable file", FileMatchers.aWritableFile(), file); } public void testAFileWithSizeLong() { assertMatches("matches file size", FileMatchers.aFileWithSize(0L), file); assertDoesNotMatch("doesn't match incorrect file size", FileMatchers.aFileWithSize(34L), file); } public void testAFileWithSizeMatcherOfLong() { assertMatches("matches file size", FileMatchers.aFileWithSize(equalTo(0L)), file); assertDoesNotMatch("doesn't match incorrect file size", FileMatchers.aFileWithSize(equalTo(23L)), file); } public void testAFileNamed() { assertMatches("matches file name", FileMatchers.aFileNamed(equalTo(file.getName())), file); assertDoesNotMatch("doesn't match incorrect file name", FileMatchers.aFileNamed(equalTo("foo")), file); } public void testAFileWithCanonicalPath() throws Exception { assertMatches("matches file canonical path", FileMatchers.aFileWithCanonicalPath(equalTo(file.getCanonicalPath())), file); assertDoesNotMatch("doesn't match incorrect canonical path", FileMatchers.aFileWithCanonicalPath(equalTo("foo")), file); } public void testAFileWithAbsolutePath() { assertMatches("matches file absolute path", FileMatchers.aFileWithAbsolutePath(equalTo(file.getAbsolutePath())), file); assertDoesNotMatch("doesn't match incorrect absolute path", FileMatchers.aFileWithAbsolutePath(equalTo("foo")), file); } @Override protected Matcher createMatcher() { return FileMatchers.aFileWithSize(1L); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/number/000077500000000000000000000000001355170103300241055ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/number/BigDecimalCloseToTest.java000066400000000000000000000036001355170103300310600ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.math.BigDecimal; import static org.hamcrest.number.BigDecimalCloseTo.closeTo; public class BigDecimalCloseToTest extends AbstractMatcherTest { private final Matcher matcher = closeTo(new BigDecimal("1.0"), new BigDecimal("0.5")); @Override protected Matcher createMatcher() { BigDecimal irrelevant = new BigDecimal("0.01"); return closeTo(irrelevant, irrelevant); } public void testEvaluatesToTrueIfArgumentIsEqualToABigDecimalWithinSomeError() { assertTrue(matcher.matches(new BigDecimal("1.0"))); assertTrue(matcher.matches(new BigDecimal("0.5"))); assertTrue(matcher.matches(new BigDecimal("1.5"))); assertDoesNotMatch("too large", matcher, new BigDecimal("2.0")); assertMismatchDescription("<2.0> differed by <0.5> more than delta <0.5>", matcher, new BigDecimal("2.0")); assertDoesNotMatch("number too small", matcher, new BigDecimal("0.0")); assertMismatchDescription("<0.0> differed by <0.5> more than delta <0.5>", matcher, new BigDecimal("0.0")); } public void testEvaluatesToTrueIfArgumentHasDifferentScale() { assertTrue(matcher.matches(new BigDecimal("1.000000"))); assertTrue(matcher.matches(new BigDecimal("0.500000"))); assertTrue(matcher.matches(new BigDecimal("1.500000"))); assertDoesNotMatch("too large", matcher, new BigDecimal("2.000000")); assertMismatchDescription("<2.000000> differed by <0.5> more than delta <0.5>", matcher, new BigDecimal("2.000000")); assertDoesNotMatch("number too small", matcher, new BigDecimal("0.000000")); assertMismatchDescription("<0.000000> differed by <0.5> more than delta <0.5>", matcher, new BigDecimal("0.000000")); } public void test_is_self_describing() { assertDescription("a numeric value within <0.5> of <1.0>", matcher); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java000066400000000000000000000021041355170103300274510ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.number.IsCloseTo.closeTo; public class IsCloseToTest extends AbstractMatcherTest { private final Matcher matcher = closeTo(1.0d, 0.5d); @Override protected Matcher createMatcher() { final double irrelevant = 0.1; return closeTo(irrelevant, irrelevant); } public void test_matchesIfArgumentIsEqualToADoubleValueWithinSomeError() { assertMatches("1.0", matcher, 1.0); assertMatches("0.5d", matcher, 0.5d); assertMatches("1.5d", matcher, 1.5d); assertDoesNotMatch("too large", matcher, 2.0); assertMismatchDescription("<3.0> differed by <1.5> more than delta <0.5>", matcher, 3.0d); assertDoesNotMatch("number too small", matcher, 0.0); assertMismatchDescription("<0.1> differed by <0.4> more than delta <0.5>", matcher, 0.1); } public void test_is_self_describing() { assertDescription("a numeric value within <0.5> of <1.0>", matcher); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/number/IsNanTest.java000066400000000000000000000017401355170103300266220ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.number.IsNaN.notANumber; public final class IsNanTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = notANumber(); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesNaN() { assertMatches(notANumber(), Double.NaN); } @Test public void doesNotMatchDoubleValue() { assertDoesNotMatch(notANumber(), 1.25); } @Test public void doesNotMatchInfinity() { assertDoesNotMatch(notANumber(), Double.POSITIVE_INFINITY); } @Test public void describesItself() { assertDescription("a double value of NaN", notANumber()); } @Test public void describesAMismatch() { assertMismatchDescription("was <1.25>", notANumber(), 1.25); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/number/OrderingComparisonTest.java000066400000000000000000000053331355170103300314200ustar00rootroot00000000000000package org.hamcrest.number; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.math.BigDecimal; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.number.OrderingComparison.*; public class OrderingComparisonTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return greaterThan(1); } public void testDescription() { assertDescription("a value greater than <1>", greaterThan(1)); assertDescription("a value equal to or greater than <1>", greaterThanOrEqualTo(1)); assertDescription("a value equal to <1>", comparesEqualTo(1)); assertDescription("a value less than or equal to <1>", lessThanOrEqualTo(1)); assertDescription("a value less than <1>", lessThan(1)); } public void testMismatchDescriptions() { assertMismatchDescription("<0> was less than <1>", greaterThan(1), 0); assertMismatchDescription("<1> was equal to <1>", greaterThan(1), 1); assertMismatchDescription("<1> was greater than <0>", lessThan(0), 1); assertMismatchDescription("<2> was equal to <2>", lessThan(2), 2); } public void testComparesObjectsForGreaterThan() { assertThat(2, greaterThan(1)); assertThat(0, not(greaterThan(1))); } public void testComparesObjectsForLessThan() { assertThat(2, lessThan(3)); assertThat(0, lessThan(1)); } public void testComparesObjectsForEquality() { assertThat(3, comparesEqualTo(3)); assertThat("aa", comparesEqualTo("aa")); } public void testAllowsForInclusiveComparisons() { assertThat("less", 1, lessThanOrEqualTo(1)); assertThat("greater", 1, greaterThanOrEqualTo(1)); } public void testSupportsDifferentTypesOfComparableObjects() { assertThat(1.1, greaterThan(1.0)); assertThat("cc", greaterThan("bb")); } public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() { assertThat(new BigDecimal("10.0"), greaterThanOrEqualTo(new BigDecimal("10"))); assertThat(new BigDecimal(10), greaterThanOrEqualTo(new BigDecimal("10.0"))); assertThat(new BigDecimal("2"), comparesEqualTo(new BigDecimal("2.000"))); } public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() { assertThat(new CustomInt(5), lessThan(new CustomInt(10))); } private static final class CustomInt implements Comparable { private final int value; public CustomInt(int value) { this.value = value; } public int compareTo(CustomInt other) { return value - other.value; } } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/object/000077500000000000000000000000001355170103300240635ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java000066400000000000000000000033341355170103300306370ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; @SuppressWarnings("WeakerAccess") public class HasEqualsValuesTest extends AbstractMatcherTest { private static final WithPublicFields WITH_PUBLIC_FIELDS = new WithPublicFields('x', 666, "a string"); private static final HasEqualValues WITH_PUBLIC_FIELDS_MATCHER = new HasEqualValues<>(WITH_PUBLIC_FIELDS); @Override protected Matcher createMatcher() { return WITH_PUBLIC_FIELDS_MATCHER; } public void test_describes_itself() { assertDescription( "WithPublicFields has values [i: <666>, s: \"a string\", c: \"x\"]", WITH_PUBLIC_FIELDS_MATCHER); } public void test_matches_equivalent_object() { assertMatches(WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('x', 666, "a string")); } public void test_mismatches_on_first_field_inequality() { assertMismatchDescription( "'s' was \"different\"", WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('x', 666, "different")); } public void test_mismatches_on_inherited_field() { assertMismatchDescription( "'c' was \"y\"", WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('y', 666, "a string")); } public static class WithPublicFields extends Parent { public final int i; public final String s; public WithPublicFields(char c, int i, String s) { super(c); this.i = i; this.s = s; } } public static class Parent { public final char c; public Parent(char c) { this.c = c; } } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/object/HasToStringTest.java000066400000000000000000000033151355170103300277750ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.object.HasToString.hasToString; public final class HasToStringTest { private static final String TO_STRING_RESULT = "toString result"; private static final Object TEST_OBJECT = new Object() { @Override public String toString() { return TO_STRING_RESULT; } }; @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = hasToString(equalTo("irrelevant")); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesWhenUtilisingANestedMatcher() { final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); assertMatches(matcher, TEST_OBJECT); assertDoesNotMatch(matcher, new Object()); } @Test public void matchesWhenUsingShortcutForHasToStringEqualTo() { final Matcher matcher = hasToString(TO_STRING_RESULT); assertMatches(matcher, TEST_OBJECT); assertDoesNotMatch(matcher, new Object()); } @Test public void describesItself() { final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); assertDescription("with toString() \"toString result\"", matcher); } @Test public void describesAMismatch() { final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); String expectedMismatchString = "toString() was \"Cheese\""; assertMismatchDescription(expectedMismatchString, matcher, "Cheese"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/object/IsCompatibleTypeTest.java000066400000000000000000000030011355170103300307750ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith; public class IsCompatibleTypeTest extends AbstractMatcherTest { static class BaseClass { } private static class ExtendedClass extends BaseClass { } interface BaseInterface { } interface ExtendedInterface extends BaseInterface { } private static class ClassImplementingBaseInterface implements BaseInterface { } @Override protected Matcher createMatcher() { return typeCompatibleWith(BaseClass.class); } public void testMatchesSameClass() { assertThat(BaseClass.class, typeCompatibleWith(BaseClass.class)); } public void testMatchesSameInterface() { assertThat(BaseInterface.class, typeCompatibleWith(BaseInterface.class)); } public void testMatchesExtendedClass() { assertThat(ExtendedClass.class, typeCompatibleWith(BaseClass.class)); } public void testMatchesClassImplementingInterface() { assertThat(ClassImplementingBaseInterface.class, typeCompatibleWith(BaseInterface.class)); } public void testMatchesExtendedInterface() { assertThat(ExtendedInterface.class, typeCompatibleWith(BaseInterface.class)); } public void testHasReadableDescription() { assertDescription("type < java.lang.Runnable", typeCompatibleWith(Runnable.class)); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/object/IsEventFromTest.java000066400000000000000000000034101355170103300277650ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import java.util.EventObject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.object.IsEventFrom.eventFrom; public class IsEventFromTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return eventFrom(null); } public void testEvaluatesToTrueIfArgumentIsAnEventObjectFiredByASpecifiedSource() { Object o = "Source"; EventObject ev = new EventObject(o); EventObject ev2 = new EventObject("source 2"); Matcher isEventMatcher = eventFrom(o); assertThat(ev, isEventMatcher); assertMismatchDescription("source was \"source 2\"", isEventMatcher, ev2); } private static class DerivedEvent extends EventObject { private static final long serialVersionUID = 1L; public DerivedEvent(Object source) { super(source); } } public void testCanTestForSpecificEventClasses() { Object o = new Object(); DerivedEvent goodEv = new DerivedEvent(o); DerivedEvent wrongSource = new DerivedEvent("wrong source"); EventObject wrongType = new EventObject(o); EventObject wrongSourceAndType = new EventObject(new Object()); Matcher isEventMatcher = IsEventFrom.eventFrom(DerivedEvent.class, o); assertThat(goodEv, isEventMatcher); assertMismatchDescription("source was \"wrong source\"", isEventMatcher, wrongSource); assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongType); assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongSourceAndType); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/object/MatchesPatternTest.java000066400000000000000000000034711355170103300305150ustar00rootroot00000000000000package org.hamcrest.object; import org.hamcrest.Matcher; import org.hamcrest.text.MatchesPattern; import org.junit.Test; import java.util.regex.Pattern; import static org.hamcrest.AbstractMatcherTest.*; import static org.junit.Assert.assertThat; public class MatchesPatternTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = new MatchesPattern(Pattern.compile(".")); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesExactString() { assertThat("a", new MatchesPattern(Pattern.compile("a"))); } @Test public void doesNotMatchADifferentString() { assertDoesNotMatch("A different string does not match", new MatchesPattern(Pattern.compile("a")), "b"); } @Test public void doesNotMatchSubstring() { assertDoesNotMatch("A substring does not match", new MatchesPattern(Pattern.compile("a")), "ab"); } @Test public void hasAReadableDescription() { Matcher m = new MatchesPattern(Pattern.compile("a[bc](d|e)")); assertDescription("a string matching the pattern 'a[bc](d|e)'", m ); } @Test public void describesAMismatch() { final Matcher matcher = new MatchesPattern(Pattern.compile("a")); assertMismatchDescription("was \"Cheese\"", matcher, "Cheese"); } @Test public void factoryMethodAllowsCreationWithPattern() { Matcher m = MatchesPattern.matchesPattern(Pattern.compile("a[bc](d|e)")); assertDescription("a string matching the pattern 'a[bc](d|e)'", m ); } @Test public void factoryMethodAllowsCreationWithString() { Matcher m = MatchesPattern.matchesPattern("a[bc](d|e)"); assertDescription("a string matching the pattern 'a[bc](d|e)'", m ); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/text/000077500000000000000000000000001355170103300236015ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/text/CharSequenceLengthTest.java000066400000000000000000000021371355170103300310170ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.hamcrest.text.CharSequenceLength.hasLength; /** * @author Marco Leichsenring * @author Steve Freeman */ public class CharSequenceLengthTest extends AbstractMatcherTest { @Override protected Matcher createMatcher() { return hasLength(4); } public void test_matchesExactLengthOf_CharSequence() { final Matcher matcher = hasLength(4); assertMatches(matcher, "aaaa"); assertMatches(matcher, "a b "); assertMismatchDescription("length was <6>", matcher, "aaaaaa"); } public void test_matchesRelativeLengthOf_CharSequence() { final Matcher matcher = hasLength(lessThan(4)); assertMatches(matcher, "aaa"); assertMatches(matcher, "a b"); assertMismatchDescription("length <4> was equal to <4>", matcher, "aaaa"); assertMismatchDescription("length <5> was greater than <4>", matcher, "aaaaa"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java000066400000000000000000000027561355170103300300300ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.text.IsBlankString.blankOrNullString; import static org.hamcrest.text.IsBlankString.blankString; public final class IsBlankStringTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = blankString(); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesEmptyString() { assertMatches(blankOrNullString(), ""); assertMatches(blankString(), ""); } @Test public void matchesNullAppropriately() { assertMatches(blankOrNullString(), null); assertDoesNotMatch(blankString(), null); } @Test public void matchesBlankStringAppropriately() { assertMatches(blankString(), " \t"); assertMatches(blankOrNullString(), " \t"); } @Test public void doesNotMatchFilledString() { assertDoesNotMatch(blankString(), "a"); assertDoesNotMatch(blankOrNullString(), "a"); } @Test public void describesItself() { assertDescription("a blank string", blankString()); assertDescription("(null or a blank string)", blankOrNullString()); } @Test public void describesAMismatch() { assertMismatchDescription("was \"a\"", blankString(), "a"); assertMismatchDescription("was \"a\"", blankOrNullString(), "a"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/text/IsEmptyStringTest.java000066400000000000000000000027701355170103300300730ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.text.IsEmptyString.emptyOrNullString; import static org.hamcrest.text.IsEmptyString.emptyString; public final class IsEmptyStringTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = emptyString(); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void matchesEmptyString() { assertMatches(emptyOrNullString(), ""); assertMatches(emptyString(), ""); } @Test public void matchesNullAppropriately() { assertMatches(emptyOrNullString(), null); assertDoesNotMatch(emptyString(), null); } @Test public void matchesBlankStringAppropriately() { assertDoesNotMatch(emptyString(), " "); assertDoesNotMatch(emptyOrNullString(), " "); } @Test public void doesNotMatchFilledString() { assertDoesNotMatch(emptyString(), "a"); assertDoesNotMatch(emptyOrNullString(), "a"); } @Test public void describesItself() { assertDescription("an empty string", emptyString()); assertDescription("(null or an empty string)", emptyOrNullString()); } @Test public void describesAMismatch() { assertMismatchDescription("was \"a\"", emptyString(), "a"); assertMismatchDescription("was \"a\"", emptyOrNullString(), "a"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java000066400000000000000000000027631355170103300330460ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static org.hamcrest.text.IsEqualCompressingWhiteSpace.equalToCompressingWhiteSpace; public class IsEqualCompressingWhiteSpaceTest extends AbstractMatcherTest { private final Matcher matcher = equalToCompressingWhiteSpace(" Hello World how\n are we? "); @Override protected Matcher createMatcher() { return matcher; } public void testPassesIfWordsAreSameButWhitespaceDiffers() { assertMatches(matcher, "Hello World how are we?"); assertMatches(matcher, " Hello World how are \n\n\twe?"); } public void testFailsIfTextOtherThanWhitespaceDiffers() { assertDoesNotMatch(matcher, "Hello PLANET how are we?"); assertDoesNotMatch(matcher, "Hello World how are we"); } public void testFailsIfWhitespaceIsAddedOrRemovedInMidWord() { assertDoesNotMatch(matcher, "HelloWorld how are we?"); assertDoesNotMatch(matcher, "Hello Wo rld how are we?"); } public void test_has_a_readable_mismatch() { assertMismatchDescription("was \"Hello World how are we \"", matcher, "Hello World how are we "); } public void testFailsIfMatchingAgainstNull() { assertDoesNotMatch(matcher, null); } public void testHasAReadableDescription() { assertDescription("a string equal to \" Hello World how\\n are we? \" compressing white space", matcher); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java000066400000000000000000000034441355170103300311450ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.Matcher; import org.junit.Test; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; public final class IsEqualIgnoringCaseTest { @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = equalToIgnoringCase("irrelevant"); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void ignoresCaseOfCharsInString() { final Matcher matcher = equalToIgnoringCase("heLLo"); assertMatches(matcher, "HELLO"); assertMatches(matcher, "hello"); assertMatches(matcher, "HelLo"); assertDoesNotMatch(matcher, "bye"); } @Test public void mismatchesIfAdditionalWhitespaceIsPresent() { final Matcher matcher = equalToIgnoringCase("heLLo"); assertDoesNotMatch(matcher, "hello "); assertDoesNotMatch(matcher, " hello"); } @Test public void mismatchesNull() { final Matcher matcher = equalToIgnoringCase("heLLo"); assertDoesNotMatch(matcher, null); } @Test(expected=IllegalArgumentException.class) public void canOnlyBeConstructedAboutANonNullString() { equalToIgnoringCase(null); } @Test public void describesItself() { final Matcher matcher = equalToIgnoringCase("heLLo"); assertDescription("a string equal to \"heLLo\" ignoring case", matcher); } @Test public void describesAMismatch() { final Matcher matcher = equalToIgnoringCase("heLLo"); String expectedMismatchString = "was \"Cheese\""; assertMismatchDescription(expectedMismatchString, matcher, "Cheese"); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/text/StringContainsInOrderTest.java000066400000000000000000000024631355170103300315410ustar00rootroot00000000000000package org.hamcrest.text; import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; import static java.util.Arrays.asList; import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder; public class StringContainsInOrderTest extends AbstractMatcherTest { final StringContainsInOrder matcher = new StringContainsInOrder(asList("a", "b", "c", "c")); @Override protected Matcher createMatcher() { return matcher; } public void testMatchesOnlyIfStringContainsGivenSubstringsInTheSameOrder() { assertMatches("substrings in order", matcher, "abcc"); assertMatches("substrings separated", matcher, "1a2b3c4c5"); assertDoesNotMatch("can detect repeated strings for matching", stringContainsInOrder("abc", "abc"), "---abc---"); assertDoesNotMatch("substrings in order missing a repeated pattern", matcher, "abc"); assertDoesNotMatch("substrings out of order", matcher, "cab"); assertDoesNotMatch("no substrings in string", matcher, "xyz"); assertDoesNotMatch("substring missing", matcher, "ac"); assertDoesNotMatch("empty string", matcher, ""); } public void testHasAReadableDescription() { assertDescription("a string containing \"a\", \"b\", \"c\", \"c\" in order", matcher); } } JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/xml/000077500000000000000000000000001355170103300234155ustar00rootroot00000000000000JavaHamcrest-2.2/hamcrest/src/test/java/org/hamcrest/xml/HasXPathTest.java000066400000000000000000000122401355170103300265770ustar00rootroot00000000000000package org.hamcrest.xml; import org.hamcrest.Matcher; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.util.HashSet; import java.util.Iterator; import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.xml.HasXPath.hasXPath; import static org.junit.Assert.fail; /** * @author Joe Walnes * @author Tom Denley */ public final class HasXPathTest { private final Document xml = parse("" + "\n" + " Edam\n" + " Cheddar\n" + " Caravane\n" + " \n" + " " + "\n" ); private final NamespaceContext ns = new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { return ("cheese".equals(prefix) ? "http://cheese.com" : null); } @Override public String getPrefix(String namespaceURI) { return ("http://cheese.com".equals(namespaceURI) ? "cheese" : null); } @Override public Iterator getPrefixes(String namespaceURI) { HashSet prefixes = new HashSet(); String prefix = getPrefix(namespaceURI); if (prefix != null) { prefixes.add(prefix); } return prefixes.iterator(); } }; @Test public void copesWithNullsAndUnknownTypes() { Matcher matcher = hasXPath("//irrelevant"); assertNullSafe(matcher); assertUnknownTypeSafe(matcher); } @Test public void appliesMatcherToXPathInDocument() { assertMatches(hasXPath("/root/something[2]/cheese", equalTo("Cheddar")), xml); assertMatches(hasXPath("//something[1]/cheese", containsString("dam")), xml); assertMatches(hasXPath("//something[2]/cheese", not(containsString("dam"))), xml); assertMatches(hasXPath("/root/@type", equalTo("food")), xml); assertMatches(hasXPath("//something[@id='b']/cheese", equalTo("Cheddar")), xml); assertMatches(hasXPath("//something[@id='b']/cheese"), xml); } @Test public void matchesEmptyElement() { assertMatches(hasXPath("//emptySomething"), xml); } @Test public void matchesEmptyElementInNamespace() { assertMatches(hasXPath("//cheese:emptySomething", ns), xml); } @Test public void failsIfNodeIsMissing() { assertDoesNotMatch(hasXPath("/root/something[3]/cheese", ns, equalTo("Cheddar")), xml); assertDoesNotMatch(hasXPath("//something[@id='c']/cheese", ns), xml); } @Test public void failsIfNodeIsMissingInNamespace() { assertDoesNotMatch(hasXPath("//cheese:foreignSomething", equalTo("Badger")), xml); assertDoesNotMatch(hasXPath("//cheese:foreignSomething"), xml); } @Test public void matchesWithNamespace() { assertMatches(hasXPath("//cheese:foreignSomething", ns), xml); assertMatches(hasXPath("//cheese:foreignSomething/@milk", ns, equalTo("camel")), xml); assertMatches(hasXPath("//cheese:foreignSomething/text()", ns, equalTo("Caravane")), xml); } @Test public void throwsIllegalArgumentExceptionIfGivenIllegalExpression() { try { hasXPath("\\g:dfgd::DSgf/root/something[2]/cheese", equalTo("blah")); fail("Expected exception"); } catch (IllegalArgumentException expectedException) { // expected exception } } @Test public void describesItself() { assertDescription("an XML document with XPath /some/path \"Cheddar\"", hasXPath("/some/path", equalTo("Cheddar"))); assertDescription("an XML document with XPath /some/path", hasXPath("/some/path")); } @Test public void describesMissingNodeMismatch() { assertMismatchDescription("xpath returned no results.", hasXPath("//honky"), xml); } @Test public void describesIncorrectNodeValueMismatch() { assertMismatchDescription("was \"Edam\"", hasXPath("//something[1]/cheese", equalTo("parmesan")), xml); } private static Document parse(String xml) { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); return documentBuilder.parse(new ByteArrayInputStream(xml.getBytes())); } catch (Exception e) { throw new IllegalStateException(e); } } } JavaHamcrest-2.2/settings.gradle000066400000000000000000000007131355170103300167440ustar00rootroot00000000000000enableFeaturePreview('STABLE_PUBLISHING') include 'hamcrest', 'hamcrest-core', 'hamcrest-library', 'hamcrest-integration' rootProject.name = 'JavaHamcrest' // Change the file name of the child project build file to match the directory name // This avoids having multiple `build.gradle` files, making them easier to distinguish rootProject.children.each { childProject -> childProject.buildFileName = "${childProject.name}.gradle" }