├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── core.rs ├── lib.rs └── matchers │ ├── all_of.rs │ ├── any_of.rs │ ├── anything.rs │ ├── boolean.rs │ ├── close_to.rs │ ├── compared_to.rs │ ├── equal_to.rs │ ├── existing_path.rs │ ├── is.rs │ ├── mod.rs │ ├── none.rs │ ├── regex.rs │ ├── type_of.rs │ └── vecs.rs └── tests ├── all_of.rs ├── any_of.rs ├── anything.rs ├── boolean.rs ├── close_to.rs ├── compared_to.rs ├── equal_to.rs ├── existing_path.rs ├── none.rs ├── regex.rs ├── type_of.rs └── vecs.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | hamcrest-test 3 | /Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - beta 4 | - nightly 5 | - stable 6 | os: 7 | - linux 8 | - osx 9 | 10 | before_script: 11 | - (cargo install rustfmt || true) 12 | 13 | script: 14 | - | 15 | export PATH=$PATH:~/.cargo/bin && 16 | cargo fmt -- --write-mode=diff && 17 | cargo build && 18 | cargo test 19 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.1.5 [☰](https://github.com/ujh/hamcrest-rust/compare/0.1.4...0.1.5) 2 | 3 | * Implemented matcher trait for boolean values, #48 4 | 5 | ## 0.1.4 [☰](https://github.com/ujh/hamcrest-rust/compare/0.1.3...0.1.4) 6 | 7 | * Logical matchers `all_of`, `any_of`, comparison matchers `type_of`, `anything`, #47 8 | 9 | ## 0.1.3 [☰](https://github.com/ujh/hamcrest-rust/compare/0.1.2...0.1.3) 10 | 11 | * Comparison matchers `less_than`, `less_than_or_equal_to`, `greater_than`, `greater_than_or_equal_to`. #43 12 | * `in_order` option for `contains`. #44 13 | 14 | ## 0.1.2 [☰](https://github.com/ujh/hamcrest-rust/compare/0.1.1...0.1.2) 15 | 16 | * Added the `assert_that!` macro. It produces better error messages (with correct file and line 17 | number). 18 | * Deprecated the `assert_that` function. 19 | * Improvements to `Cargo.toml` (by @killercup) 20 | 21 | ## 0.1.1 [☰](https://github.com/ujh/hamcrest-rust/compare/a9f18681c64e3126ef6ccbd68ec2a5b39fe5b58b...0.1.1) 22 | 23 | * Licensing change. The crate is now dual licensed under the MIT and Apache 2 licenses. 24 | * Adds the `prelude` submodule to simplify inclusion of all matchers. 25 | * `matches_regex` matcher 26 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "hamcrest" 3 | description = "A port of the Hamcrest testing library" 4 | version = "0.1.5" 5 | keywords = ["unit", "matcher", "testing", "assertions", "tdd"] 6 | categories = ["development-tools", "development-tools::testing"] 7 | license = "MIT/Apache-2.0" 8 | repository = "https://github.com/ujh/hamcrest-rust" 9 | documentation = "https://docs.rs/hamcrest" 10 | readme = "README.md" 11 | authors = [ 12 | "Carl Lerche ", 13 | "Alex Crichton ", 14 | "Ben Longbons ", 15 | "Graham Dennis ", 16 | "Michael Gehring ", 17 | "Oliver Mader ", 18 | "Robin Gloster ", 19 | "Steve Klabnik ", 20 | "Tamir Duberstein ", 21 | "Thiago Pontes ", 22 | "Urban Hafner ", 23 | "Valerii Hiora ", 24 | "Yehuda Katz ", 25 | "Ian Létourneau ", 26 | "Matt LaChance ", 27 | "Flier Lu ", 28 | "Povilas Balciunas ", 29 | ] 30 | 31 | [dependencies] 32 | num = "0.1.40" 33 | regex = "0.2.2" 34 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 22 | 23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 24 | 25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 26 | 27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 28 | 29 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 30 | 31 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 34 | 35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 36 | 37 | a. You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | 39 | b. You must cause any modified files to carry prominent notices stating that You changed the files; and 40 | 41 | c. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 42 | 43 | d. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 44 | 45 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 46 | 47 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 48 | 49 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 50 | 51 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 52 | 53 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 54 | 55 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 56 | 57 | END OF TERMS AND CONDITIONS 58 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 2 | 3 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 4 | 5 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/ujh/hamcrest-rust.svg?branch=master)](https://travis-ci.org/ujh/hamcrest-rust) 2 | 3 | # Hamcrest 4 | 5 | A port of [Hamcrest](http://hamcrest.org/) to [Rust](http://rust-lang.org). 6 | 7 | ## Installing 8 | 9 | To use Hamcrest, add this to your `Cargo.toml`: 10 | 11 | ``` 12 | [dev-dependencies] 13 | hamcrest = "*" 14 | ``` 15 | 16 | And this to your crate root: 17 | 18 | ``` rust 19 | #[cfg(test)] #[macro_use] extern crate hamcrest; 20 | ``` 21 | 22 | After a quick `cargo build`, you should be good to go! 23 | 24 | ## Usage 25 | 26 | Hamcrest supports a number of matchers. The easiest way is to just `use` them all like this: 27 | 28 | ``` rust 29 | use hamcrest::prelude::*; 30 | ``` 31 | 32 | If you want to be more selective make sure that you also import the `HamcrestMatcher` trait. 33 | 34 | ### equal\_to 35 | 36 | ``` rust 37 | assert_that!(1, is(equal_to(1))); 38 | ``` 39 | 40 | ### close\_to 41 | 42 | ``` rust 43 | assert_that!(1e-40f32, is(close_to(0.0, 0.01))); 44 | assert_that!(1e-40f32, is_not(close_to(0.0, 0.000001))); 45 | ``` 46 | 47 | ### compared\_to 48 | 49 | ``` rust 50 | assert_that!(1, is(less_than(2))); 51 | assert_that!(1, is(less_than_or_equal_to(1))); 52 | assert_that!(2, is(greater_than(1))); 53 | assert_that!(2, is(greater_than_or_equal_to(2))); 54 | ``` 55 | 56 | ### existing\_{file,path,dir} 57 | 58 | ``` rust 59 | assert_that!(&path, is(existing_path())); 60 | assert_that!(&path, is(existing_file())); 61 | assert_that!(&path, is_not(existing_dir())); 62 | ``` 63 | 64 | ### none 65 | 66 | ``` rust 67 | assert_that!(None, is(none::())); 68 | assert_that!(Some(1), is_not(none::())); 69 | ``` 70 | 71 | ### anything 72 | 73 | ``` rust 74 | assert_that!(42, is(anything())); 75 | assert_that!("test", is(anything())); 76 | ``` 77 | 78 | ### contains, contains\_exactly, contains\_in order 79 | 80 | ``` rust 81 | assert_that!(&vec!(1i, 2, 3), contains(vec!(1i, 2))); 82 | assert_that!(&vec!(1i, 2, 3), not(contains(vec!(4i)))); 83 | 84 | assert_that!(&vec!(1i, 2, 3), contains(vec!(1i, 2, 3)).exactly()); 85 | assert_that!(&vec!(1i, 2, 3), not(contains(vec!(1i, 2)).exactly())); 86 | 87 | assert_that!(&vec!(1i, 2, 3), contains(vec!(1i, 2)).in_order()); 88 | assert_that!(&vec!(1i, 2, 3), not(contains(vec!(1i, 3)).in_order())); 89 | ``` 90 | 91 | ### matches_regex 92 | 93 | ``` rust 94 | assert_that!("1234", matches_regex(r"\d")); 95 | assert_that!("abc", does_not(match_regex(r"\d"))); 96 | ``` 97 | 98 | ### type_of 99 | 100 | ``` rust 101 | assert_that!(123usize, is(type_of::())); 102 | assert_that!("test", is(type_of::<&str>())); 103 | ``` 104 | 105 | ### all_of 106 | 107 | ``` rust 108 | assert_that!(4, all_of!(less_than(5), greater_than(3))); 109 | assert_that!( 110 | &vec![1, 2, 3], 111 | all_of!(contains(vec![1, 2]), not(contains(vec![4]))) 112 | ); 113 | ``` 114 | 115 | ### any_of 116 | 117 | ``` rust 118 | assert_that!(4, any_of!(less_than(2), greater_than(3))); 119 | assert_that!( 120 | &vec![1, 2, 3], 121 | any_of!(contains(vec![1, 2, 5]), not(contains(vec![4]))) 122 | ); 123 | ``` 124 | 125 | ### is(bool) 126 | 127 | ``` rust 128 | assert_that!(true, is(true)); 129 | assert_that!(false, is(false)); 130 | ``` 131 | 132 | ## License 133 | 134 | Licensed under either of 135 | 136 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or 137 | http://www.apache.org/licenses/LICENSE-2.0) 138 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 139 | 140 | at your option. 141 | 142 | ### Contribution 143 | 144 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the 145 | work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 146 | additional terms or conditions. 147 | -------------------------------------------------------------------------------- /src/core.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Steve Klabnik, Alex Crichton 2 | // Copyright 2015 Carl Lerche 3 | // Copyright 2016 Urban Hafner 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | use std::fmt; 12 | 13 | pub type MatchResult = Result<(), String>; 14 | 15 | pub fn success() -> MatchResult { 16 | Ok(()) 17 | } 18 | 19 | pub fn expect(predicate: bool, msg: String) -> MatchResult { 20 | if predicate { success() } else { Err(msg) } 21 | } 22 | 23 | #[deprecated(since = "0.1.2", note = "Use the assert_that! macro instead")] 24 | pub fn assert_that>(actual: T, matcher: U) { 25 | match matcher.matches(actual) { 26 | Ok(_) => return, 27 | Err(mismatch) => { 28 | panic!("\nExpected: {}\n but: {}", matcher, mismatch); 29 | } 30 | } 31 | } 32 | 33 | pub trait Matcher: fmt::Display { 34 | fn matches(&self, actual: T) -> MatchResult; 35 | } 36 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Oliver Mader, Alex Crichton, Thiago Pontes, 2 | // Yehuda Katz 3 | // Copyright 2015 Carl Lerche, Oliver Mader 4 | // Copyright 2016 Urban Hafner 5 | // 6 | // Licensed under the Apache License, Version 2.0 or the MIT license 8 | // , at your 9 | // option. This file may not be copied, modified, or distributed 10 | // except according to those terms. 11 | 12 | #![crate_name = "hamcrest"] 13 | #![crate_type = "lib"] 14 | 15 | extern crate num; 16 | extern crate regex; 17 | 18 | pub use prelude::*; 19 | 20 | #[macro_export] 21 | macro_rules! assert_that { 22 | ($actual:expr, $matcher:expr) => ({ 23 | // The separate statement is necessary to keep the compiler happy. 24 | let m = $matcher; 25 | match m.matches($actual) { 26 | Ok(_) => {}, 27 | Err(mismatch) => { 28 | // The panic macro produces the correct file and line number 29 | // when used in a macro like this, i.e. it's the line where 30 | // the macro was originally written. 31 | panic!("\nExpected: {}\n but: {}", m, mismatch); 32 | } 33 | } 34 | } 35 | ); 36 | } 37 | 38 | pub mod core; 39 | pub mod matchers; 40 | pub mod prelude { 41 | #[allow(deprecated)] 42 | pub use core::assert_that; 43 | pub use core::Matcher as HamcrestMatcher; 44 | pub use matchers::close_to::close_to; 45 | pub use matchers::compared_to::less_than; 46 | pub use matchers::compared_to::less_than_or_equal_to; 47 | pub use matchers::compared_to::greater_than; 48 | pub use matchers::compared_to::greater_than_or_equal_to; 49 | pub use matchers::equal_to::equal_to; 50 | pub use matchers::existing_path::existing_dir; 51 | pub use matchers::existing_path::existing_file; 52 | pub use matchers::existing_path::existing_path; 53 | pub use matchers::is::is_not as does_not; 54 | pub use matchers::is::is_not as not; 55 | pub use matchers::is::is_not; 56 | pub use matchers::is::is; 57 | pub use matchers::none::none; 58 | pub use matchers::regex::matches_regex as match_regex; 59 | pub use matchers::regex::matches_regex; 60 | pub use matchers::vecs::contains; 61 | pub use matchers::vecs::of_len; 62 | pub use matchers::anything::anything; 63 | pub use matchers::type_of::type_of; 64 | pub use matchers::all_of::all_of; 65 | pub use matchers::all_of::all_of as and; 66 | pub use matchers::any_of::any_of; 67 | pub use matchers::any_of::any_of as or; 68 | } 69 | -------------------------------------------------------------------------------- /src/matchers/all_of.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Flier Lu 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use std::fmt::{self, Display}; 10 | use std::marker::PhantomData; 11 | 12 | use core::*; 13 | 14 | pub struct AllOf(M, PhantomData); 15 | 16 | pub fn all_of(matchers: M) -> AllOf { 17 | AllOf(matchers, PhantomData) 18 | } 19 | 20 | #[macro_export] 21 | macro_rules! all_of { 22 | ($( $arg:expr ),*) => ($crate::matchers::all_of::all_of(($( $arg ),*))) 23 | } 24 | 25 | impl Display for AllOf 26 | where 27 | M0: Display, 28 | M1: Display, 29 | { 30 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 31 | let (ref m0, ref m1) = self.0; 32 | 33 | write!(f, "all of ({}, {})", m0, m1) 34 | } 35 | } 36 | 37 | impl Matcher for AllOf 38 | where 39 | T: Clone, 40 | M0: Matcher, 41 | M1: Matcher, 42 | { 43 | fn matches(&self, actual: T) -> MatchResult { 44 | let (ref m0, ref m1) = self.0; 45 | 46 | m0.matches(actual.clone())?; 47 | m1.matches(actual.clone())?; 48 | 49 | success() 50 | } 51 | } 52 | 53 | impl Display for AllOf 54 | where 55 | M0: Display, 56 | M1: Display, 57 | M2: Display, 58 | { 59 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 60 | let (ref m0, ref m1, ref m2) = self.0; 61 | 62 | write!(f, "all of ({}, {}, {})", m0, m1, m2) 63 | } 64 | } 65 | 66 | impl Matcher for AllOf 67 | where 68 | T: Clone, 69 | M0: Matcher, 70 | M1: Matcher, 71 | M2: Matcher, 72 | { 73 | fn matches(&self, actual: T) -> MatchResult { 74 | let (ref m0, ref m1, ref m2) = self.0; 75 | 76 | m0.matches(actual.clone())?; 77 | m1.matches(actual.clone())?; 78 | m2.matches(actual.clone())?; 79 | 80 | success() 81 | } 82 | } 83 | 84 | impl Display for AllOf 85 | where 86 | M0: Display, 87 | M1: Display, 88 | M2: Display, 89 | M3: Display, 90 | { 91 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 92 | let (ref m0, ref m1, ref m2, ref m3) = self.0; 93 | 94 | write!(f, "all of ({}, {}, {}, {})", m0, m1, m2, m3) 95 | } 96 | } 97 | 98 | impl Matcher for AllOf 99 | where 100 | T: Clone, 101 | M0: Matcher, 102 | M1: Matcher, 103 | M2: Matcher, 104 | M3: Matcher, 105 | { 106 | fn matches(&self, actual: T) -> MatchResult { 107 | let (ref m0, ref m1, ref m2, ref m3) = self.0; 108 | 109 | m0.matches(actual.clone())?; 110 | m1.matches(actual.clone())?; 111 | m2.matches(actual.clone())?; 112 | m3.matches(actual.clone())?; 113 | 114 | success() 115 | } 116 | } 117 | 118 | impl Display for AllOf 119 | where 120 | M0: Display, 121 | M1: Display, 122 | M2: Display, 123 | M3: Display, 124 | M4: Display, 125 | { 126 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 127 | let (ref m0, ref m1, ref m2, ref m3, ref m4) = self.0; 128 | 129 | write!(f, "all of ({}, {}, {}, {}, {})", m0, m1, m2, m3, m4) 130 | } 131 | } 132 | 133 | impl Matcher for AllOf 134 | where 135 | T: Clone, 136 | M0: Matcher, 137 | M1: Matcher, 138 | M2: Matcher, 139 | M3: Matcher, 140 | M4: Matcher, 141 | { 142 | fn matches(&self, actual: T) -> MatchResult { 143 | let (ref m0, ref m1, ref m2, ref m3, ref m4) = self.0; 144 | 145 | m0.matches(actual.clone())?; 146 | m1.matches(actual.clone())?; 147 | m2.matches(actual.clone())?; 148 | m3.matches(actual.clone())?; 149 | m4.matches(actual.clone())?; 150 | 151 | success() 152 | } 153 | } 154 | 155 | impl Display for AllOf 156 | where 157 | M0: Display, 158 | M1: Display, 159 | M2: Display, 160 | M3: Display, 161 | M4: Display, 162 | M5: Display, 163 | { 164 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 165 | let (ref m0, ref m1, ref m2, ref m3, ref m4, ref m5) = self.0; 166 | 167 | write!(f, "all of ({}, {}, {}, {}, {}, {})", m0, m1, m2, m3, m4, m5) 168 | } 169 | } 170 | 171 | impl Matcher for AllOf 172 | where 173 | T: Clone, 174 | M0: Matcher, 175 | M1: Matcher, 176 | M2: Matcher, 177 | M3: Matcher, 178 | M4: Matcher, 179 | M5: Matcher, 180 | { 181 | fn matches(&self, actual: T) -> MatchResult { 182 | let (ref m0, ref m1, ref m2, ref m3, ref m4, ref m5) = self.0; 183 | 184 | m0.matches(actual.clone())?; 185 | m1.matches(actual.clone())?; 186 | m2.matches(actual.clone())?; 187 | m3.matches(actual.clone())?; 188 | m4.matches(actual.clone())?; 189 | m5.matches(actual.clone())?; 190 | 191 | success() 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/matchers/any_of.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Flier Lu 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use std::fmt::{self, Display}; 10 | use std::marker::PhantomData; 11 | 12 | use core::*; 13 | 14 | pub struct AnyOf(M, PhantomData); 15 | 16 | pub fn any_of(matchers: M) -> AnyOf { 17 | AnyOf(matchers, PhantomData) 18 | } 19 | 20 | #[macro_export] 21 | macro_rules! any_of { 22 | ($( $arg:expr ),*) => ($crate::matchers::any_of::any_of(($( $arg ),*))) 23 | } 24 | 25 | impl Display for AnyOf 26 | where 27 | M0: Display, 28 | M1: Display, 29 | { 30 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 31 | let (ref m0, ref m1) = self.0; 32 | 33 | write!(f, "any of ({}, {})", m0, m1) 34 | } 35 | } 36 | 37 | impl Matcher for AnyOf 38 | where 39 | T: Clone, 40 | M0: Matcher, 41 | M1: Matcher, 42 | { 43 | fn matches(&self, actual: T) -> MatchResult { 44 | let (ref m0, ref m1) = self.0; 45 | 46 | m0.matches(actual.clone()).or_else( 47 | |_| m1.matches(actual.clone()), 48 | ) 49 | } 50 | } 51 | 52 | impl Display for AnyOf 53 | where 54 | M0: Display, 55 | M1: Display, 56 | M2: Display, 57 | { 58 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 59 | let (ref m0, ref m1, ref m2) = self.0; 60 | 61 | write!(f, "any of ({}, {}, {})", m0, m1, m2) 62 | } 63 | } 64 | 65 | impl Matcher for AnyOf 66 | where 67 | T: Clone, 68 | M0: Matcher, 69 | M1: Matcher, 70 | M2: Matcher, 71 | { 72 | fn matches(&self, actual: T) -> MatchResult { 73 | let (ref m0, ref m1, ref m2) = self.0; 74 | 75 | m0.matches(actual.clone()) 76 | .or_else(|_| m1.matches(actual.clone())) 77 | .or_else(|_| m2.matches(actual.clone())) 78 | } 79 | } 80 | 81 | impl Display for AnyOf 82 | where 83 | M0: Display, 84 | M1: Display, 85 | M2: Display, 86 | M3: Display, 87 | { 88 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 89 | let (ref m0, ref m1, ref m2, ref m3) = self.0; 90 | 91 | write!(f, "any of ({}, {}, {}, {})", m0, m1, m2, m3) 92 | } 93 | } 94 | 95 | impl Matcher for AnyOf 96 | where 97 | T: Clone, 98 | M0: Matcher, 99 | M1: Matcher, 100 | M2: Matcher, 101 | M3: Matcher, 102 | { 103 | fn matches(&self, actual: T) -> MatchResult { 104 | let (ref m0, ref m1, ref m2, ref m3) = self.0; 105 | 106 | m0.matches(actual.clone()) 107 | .or_else(|_| m1.matches(actual.clone())) 108 | .or_else(|_| m2.matches(actual.clone())) 109 | .or_else(|_| m3.matches(actual.clone())) 110 | } 111 | } 112 | 113 | impl Display for AnyOf 114 | where 115 | M0: Display, 116 | M1: Display, 117 | M2: Display, 118 | M3: Display, 119 | M4: Display, 120 | { 121 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 122 | let (ref m0, ref m1, ref m2, ref m3, ref m4) = self.0; 123 | 124 | write!(f, "any of ({}, {}, {}, {}, {})", m0, m1, m2, m3, m4) 125 | } 126 | } 127 | 128 | impl Matcher for AnyOf 129 | where 130 | T: Clone, 131 | M0: Matcher, 132 | M1: Matcher, 133 | M2: Matcher, 134 | M3: Matcher, 135 | M4: Matcher, 136 | { 137 | fn matches(&self, actual: T) -> MatchResult { 138 | let (ref m0, ref m1, ref m2, ref m3, ref m4) = self.0; 139 | 140 | m0.matches(actual.clone()) 141 | .or_else(|_| m1.matches(actual.clone())) 142 | .or_else(|_| m2.matches(actual.clone())) 143 | .or_else(|_| m3.matches(actual.clone())) 144 | .or_else(|_| m4.matches(actual.clone())) 145 | } 146 | } 147 | 148 | impl Display for AnyOf 149 | where 150 | M0: Display, 151 | M1: Display, 152 | M2: Display, 153 | M3: Display, 154 | M4: Display, 155 | M5: Display, 156 | { 157 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 158 | let (ref m0, ref m1, ref m2, ref m3, ref m4, ref m5) = self.0; 159 | 160 | write!(f, "any of ({}, {}, {}, {}, {}, {})", m0, m1, m2, m3, m4, m5) 161 | } 162 | } 163 | 164 | impl Matcher for AnyOf 165 | where 166 | T: Clone, 167 | M0: Matcher, 168 | M1: Matcher, 169 | M2: Matcher, 170 | M3: Matcher, 171 | M4: Matcher, 172 | M5: Matcher, 173 | { 174 | fn matches(&self, actual: T) -> MatchResult { 175 | let (ref m0, ref m1, ref m2, ref m3, ref m4, ref m5) = self.0; 176 | 177 | m0.matches(actual.clone()) 178 | .or_else(|_| m1.matches(actual.clone())) 179 | .or_else(|_| m2.matches(actual.clone())) 180 | .or_else(|_| m3.matches(actual.clone())) 181 | .or_else(|_| m4.matches(actual.clone())) 182 | .or_else(|_| m5.matches(actual.clone())) 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/matchers/anything.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Flier Lu 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | use std::fmt::{self, Display, Formatter}; 9 | 10 | use core::*; 11 | 12 | pub struct Anything; 13 | 14 | impl Display for Anything { 15 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 16 | write!(f, "anything") 17 | } 18 | } 19 | 20 | impl Matcher for Anything { 21 | fn matches(&self, _: T) -> MatchResult { 22 | success() 23 | } 24 | } 25 | 26 | /// always matches, useful if you don't care what the object under test is 27 | pub fn anything() -> Anything { 28 | Anything 29 | } 30 | -------------------------------------------------------------------------------- /src/matchers/boolean.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Povilas Balciunas 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use core::*; 10 | 11 | impl Matcher for bool { 12 | fn matches(&self, actual: bool) -> MatchResult { 13 | if actual == *self { 14 | success() 15 | } else { 16 | Err(format!("was {:?}", actual)) 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/matchers/close_to.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Steve Klabnik, Valerii Hiora, Oliver Mader 2 | // Copyright 2015 Carl Lerche, Oliver Mader, Alex Crichton, Graham Dennis, 3 | // Tamir Duberstein, Robin Gloster 4 | // Copyright 2016 Urban Hafner 5 | // 6 | // Licensed under the Apache License, Version 2.0 or the MIT license 8 | // , at your 9 | // option. This file may not be copied, modified, or distributed 10 | // except according to those terms. 11 | 12 | use num::{Float, Zero}; 13 | use std::fmt::{self, Display, Debug, Formatter}; 14 | 15 | use core::*; 16 | 17 | /// Compares two floating point values for equality. 18 | /// 19 | /// The comparison is based on a relative error metric and uses special 20 | /// fallbacks for certain edge cases like very small numbers. The exact 21 | /// algorithm is described [here](http://floating-point-gui.de/errors/comparison/). 22 | pub struct CloseTo { 23 | expected: T, 24 | epsilon: T, 25 | } 26 | 27 | impl Display for CloseTo { 28 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 29 | self.expected.fmt(f) 30 | } 31 | } 32 | 33 | impl Matcher for CloseTo { 34 | fn matches(&self, actual: T) -> MatchResult { 35 | let a = self.expected.abs(); 36 | let b = actual.abs(); 37 | 38 | let d = (a - b).abs(); 39 | 40 | let close = 41 | // shortcut, handles infinities 42 | a == b 43 | // a or b is zero or both are extremely close to it 44 | // relative error is less meaningful here 45 | || ((a == Zero::zero() || b == Zero::zero() || d < Float::min_positive_value()) && 46 | d < (self.epsilon * Float::min_positive_value())) 47 | // use relative error 48 | || d / (a + b).min(Float::max_value()) < self.epsilon; 49 | 50 | if close { 51 | success() 52 | } else { 53 | Err(format!("was {:?}", actual)) 54 | } 55 | } 56 | } 57 | 58 | pub fn close_to(expected: T, epsilon: T) -> CloseTo { 59 | CloseTo { 60 | expected: expected, 61 | epsilon: epsilon, 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/matchers/compared_to.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Steve Klabnik, Alex Crichton, Yehuda Katz, 2 | // Ben Longbons 3 | // Copyright 2015 Carl Lerche, Alex Crichton, Robin Gloster 4 | // Copyright 2016 Urban Hafner 5 | // Copyright 2017 Matt LaChance 6 | // 7 | // Licensed under the Apache License, Version 2.0 or the MIT license 9 | // , at your 10 | // option. This file may not be copied, modified, or distributed 11 | // except according to those terms. 12 | 13 | use std::fmt; 14 | 15 | use core::*; 16 | 17 | enum CompareOperation { 18 | LessOrEqual, 19 | LessThan, 20 | GreaterOrEqual, 21 | GreaterThan, 22 | } 23 | 24 | pub struct ComparedTo { 25 | operation: CompareOperation, 26 | right_hand_side: T, 27 | } 28 | 29 | impl fmt::Display for ComparedTo { 30 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 31 | let operation = match self.operation { 32 | CompareOperation::LessOrEqual => "<=", 33 | CompareOperation::LessThan => "<", 34 | CompareOperation::GreaterOrEqual => ">=", 35 | CompareOperation::GreaterThan => ">", 36 | }; 37 | 38 | write!(f, "{} {:?}", operation, &self.right_hand_side) 39 | } 40 | } 41 | 42 | impl Matcher for ComparedTo { 43 | fn matches(&self, actual: T) -> MatchResult { 44 | let it_succeeded = match self.operation { 45 | CompareOperation::LessOrEqual => actual <= self.right_hand_side, 46 | CompareOperation::LessThan => actual < self.right_hand_side, 47 | CompareOperation::GreaterOrEqual => actual >= self.right_hand_side, 48 | CompareOperation::GreaterThan => actual > self.right_hand_side, 49 | }; 50 | 51 | if it_succeeded { 52 | success() 53 | } else { 54 | Err(format!("was {:?}", actual)) 55 | } 56 | } 57 | } 58 | 59 | pub fn less_than(right_hand_side: T) -> ComparedTo { 60 | ComparedTo { 61 | operation: CompareOperation::LessThan, 62 | right_hand_side: right_hand_side, 63 | } 64 | } 65 | 66 | pub fn less_than_or_equal_to(right_hand_side: T) -> ComparedTo { 67 | ComparedTo { 68 | operation: CompareOperation::LessOrEqual, 69 | right_hand_side: right_hand_side, 70 | } 71 | } 72 | 73 | pub fn greater_than(right_hand_side: T) -> ComparedTo { 74 | ComparedTo { 75 | operation: CompareOperation::GreaterThan, 76 | right_hand_side: right_hand_side, 77 | } 78 | } 79 | 80 | pub fn greater_than_or_equal_to(right_hand_side: T) -> ComparedTo { 81 | ComparedTo { 82 | operation: CompareOperation::GreaterOrEqual, 83 | right_hand_side: right_hand_side, 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/matchers/equal_to.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Steve Klabnik, Alex Crichton, Yehuda Katz, 2 | // Ben Longbons 3 | // Copyright 2015 Carl Lerche, Alex Crichton, Robin Gloster 4 | // Copyright 2016 Urban Hafner 5 | // 6 | // Licensed under the Apache License, Version 2.0 or the MIT license 8 | // , at your 9 | // option. This file may not be copied, modified, or distributed 10 | // except according to those terms. 11 | 12 | use std::fmt; 13 | 14 | use core::*; 15 | 16 | pub struct EqualTo { 17 | expected: T, 18 | } 19 | 20 | impl fmt::Display for EqualTo { 21 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 22 | self.expected.fmt(f) 23 | } 24 | } 25 | 26 | impl Matcher for EqualTo { 27 | fn matches(&self, actual: T) -> MatchResult { 28 | if self.expected.eq(&actual) { 29 | success() 30 | } else { 31 | Err(format!("was {:?}", actual)) 32 | } 33 | } 34 | } 35 | 36 | pub fn equal_to(expected: T) -> EqualTo { 37 | EqualTo { expected: expected } 38 | } 39 | -------------------------------------------------------------------------------- /src/matchers/existing_path.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Steve Klabnik, Alex Crichton, Ben Longbons, 2 | // Michael Gehring, Yehuda Katz 3 | // Copyright 2015 Carl Lerche, Alex Crichton, Graham Dennis, Robin Gloster 4 | // Copyright 2016 Urban Hafner 5 | // 6 | // Licensed under the Apache License, Version 2.0 or the MIT license 8 | // , at your 9 | // option. This file may not be copied, modified, or distributed 10 | // except according to those terms. 11 | 12 | use std::fmt; 13 | use std::path::{Path, PathBuf}; 14 | use std::fs; 15 | 16 | use core::*; 17 | 18 | #[derive(Clone, Copy)] 19 | pub enum PathType { 20 | AnyType, 21 | File, 22 | Dir, 23 | } 24 | 25 | #[derive(Clone, Copy)] 26 | pub struct ExistingPath { 27 | path_type: PathType, 28 | } 29 | 30 | impl ExistingPath { 31 | fn match_path_type(&self, actual: &Path) -> MatchResult { 32 | let metadata = fs::metadata(actual); 33 | match self.path_type { 34 | PathType::File => { 35 | expect( 36 | metadata.map(|m| m.is_file()).unwrap_or(false), 37 | format!("`{}` was not a file", actual.display()), 38 | ) 39 | } 40 | PathType::Dir => { 41 | expect( 42 | metadata.map(|m| m.is_dir()).unwrap_or(false), 43 | format!("`{}` was not a dir", actual.display()), 44 | ) 45 | } 46 | _ => success(), 47 | } 48 | } 49 | } 50 | 51 | impl fmt::Display for ExistingPath { 52 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 53 | write!(f, "an existing file") 54 | } 55 | } 56 | 57 | impl<'a> Matcher<&'a PathBuf> for ExistingPath { 58 | fn matches(&self, actual: &'a PathBuf) -> MatchResult { 59 | self.matches(&**actual) 60 | } 61 | } 62 | 63 | impl<'a> Matcher<&'a Path> for ExistingPath { 64 | fn matches(&self, actual: &Path) -> MatchResult { 65 | expect( 66 | fs::metadata(actual).is_ok(), 67 | format!("{} was missing", actual.display()), 68 | ).and(self.match_path_type(actual)) 69 | } 70 | } 71 | 72 | pub fn existing_path() -> ExistingPath { 73 | ExistingPath { path_type: PathType::AnyType } 74 | } 75 | 76 | pub fn existing_file() -> ExistingPath { 77 | ExistingPath { path_type: PathType::File } 78 | } 79 | 80 | pub fn existing_dir() -> ExistingPath { 81 | ExistingPath { path_type: PathType::Dir } 82 | } 83 | -------------------------------------------------------------------------------- /src/matchers/is.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Alex Crichton, Michael Gehring, Yehuda Katz 2 | // Copyright 2015 Carl Lerche, Alex Crichton, Robin Gloster 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | use std::fmt; 11 | use std::marker::PhantomData; 12 | 13 | use core::*; 14 | 15 | pub struct Is { 16 | matcher: M, 17 | marker: PhantomData, 18 | } 19 | 20 | impl> fmt::Display for Is { 21 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 22 | self.matcher.fmt(f) 23 | } 24 | } 25 | 26 | impl> Matcher for Is { 27 | fn matches(&self, actual: T) -> MatchResult { 28 | self.matcher.matches(actual) 29 | } 30 | } 31 | 32 | pub fn is>(matcher: M) -> Is { 33 | Is { 34 | matcher: matcher, 35 | marker: PhantomData, 36 | } 37 | } 38 | 39 | pub struct IsNot { 40 | matcher: M, 41 | marker: PhantomData, 42 | } 43 | 44 | impl> fmt::Display for IsNot { 45 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 46 | write!(f, "not {}", self.matcher) 47 | } 48 | } 49 | 50 | impl> Matcher for IsNot { 51 | fn matches(&self, actual: T) -> MatchResult { 52 | match self.matcher.matches(actual) { 53 | Ok(_) => Err("matched".to_string()), 54 | Err(_) => Ok(()), 55 | } 56 | } 57 | } 58 | 59 | pub fn is_not>(matcher: M) -> IsNot { 60 | IsNot { 61 | matcher: matcher, 62 | marker: PhantomData, 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/matchers/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | pub mod close_to; 10 | pub mod compared_to; 11 | pub mod equal_to; 12 | pub mod existing_path; 13 | pub mod is; 14 | pub mod none; 15 | pub mod regex; 16 | pub mod vecs; 17 | pub mod anything; 18 | pub mod type_of; 19 | pub mod all_of; 20 | pub mod any_of; 21 | pub mod boolean; 22 | -------------------------------------------------------------------------------- /src/matchers/none.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Alex Crichton, Michael Gehring, Yehuda Katz 2 | // Copyright 2015 Carl Lerche, Alex Crichton, Graham Dennis, Tamir Duberstein, 3 | // Robin Gloster 4 | // Copyright 2016 Urban Hafner 5 | // 6 | // Licensed under the Apache License, Version 2.0 or the MIT license 8 | // , at your 9 | // option. This file may not be copied, modified, or distributed 10 | // except according to those terms. 11 | 12 | use std::fmt; 13 | use std::marker::PhantomData; 14 | 15 | use core::*; 16 | 17 | pub struct IsNone { 18 | marker: PhantomData, 19 | } 20 | 21 | impl fmt::Display for IsNone { 22 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 23 | write!(f, "none") 24 | } 25 | } 26 | 27 | impl Matcher> for IsNone { 28 | fn matches(&self, actual: Option) -> MatchResult { 29 | match actual { 30 | Some(s) => Err(format!("was Some({:?})", s)), 31 | None => success(), 32 | } 33 | } 34 | } 35 | 36 | pub fn none() -> IsNone { 37 | IsNone { marker: PhantomData } 38 | } 39 | -------------------------------------------------------------------------------- /src/matchers/regex.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use regex::Regex; 10 | use std::fmt; 11 | 12 | use core::*; 13 | 14 | pub struct MatchesRegex { 15 | regex: Regex, 16 | } 17 | 18 | impl fmt::Display for MatchesRegex { 19 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 20 | self.regex.fmt(f) 21 | } 22 | } 23 | 24 | impl<'a> Matcher<&'a str> for MatchesRegex { 25 | fn matches(&self, actual: &'a str) -> MatchResult { 26 | if self.regex.is_match(actual) { 27 | success() 28 | } else { 29 | Err(format!("was {:?}", actual)) 30 | } 31 | } 32 | } 33 | 34 | pub fn matches_regex(regex: &str) -> MatchesRegex { 35 | MatchesRegex { regex: Regex::new(regex).unwrap() } 36 | } 37 | -------------------------------------------------------------------------------- /src/matchers/type_of.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Flier Lu 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | use std::any::TypeId; 9 | use std::fmt::{self, Display, Formatter}; 10 | 11 | use core::*; 12 | 13 | pub struct TypeOf(TypeId); 14 | 15 | impl Display for TypeOf { 16 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 17 | write!(f, "type of {:?}", self.0) 18 | } 19 | } 20 | 21 | impl Matcher for TypeOf { 22 | fn matches(&self, _: T) -> MatchResult { 23 | let type_id = TypeId::of::(); 24 | 25 | if self.0 == type_id { 26 | success() 27 | } else { 28 | Err(format!("type of {:?}", type_id)) 29 | } 30 | } 31 | } 32 | 33 | pub fn type_of() -> TypeOf { 34 | TypeOf(TypeId::of::()) 35 | } 36 | -------------------------------------------------------------------------------- /src/matchers/vecs.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Carl Lerche, Yehuda Katz, Steve Klabnik, Alex Crichton, 2 | // Ben Longbons 3 | // Copyright 2015 Carl Lerche, Graham Dennis, Alex Crichton, Tamir Duberstein, 4 | // Robin Gloster 5 | // Copyright 2016 Urban Hafner 6 | // 7 | // Licensed under the Apache License, Version 2.0 or the MIT license 9 | // , at your 10 | // option. This file may not be copied, modified, or distributed 11 | // except according to those terms. 12 | 13 | use std::fmt; 14 | use std::vec::Vec; 15 | 16 | use core::*; 17 | 18 | #[derive(Clone, Copy)] 19 | pub struct OfLen { 20 | len: usize, 21 | } 22 | 23 | impl fmt::Display for OfLen { 24 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 25 | write!(f, "of len {}", self.len) 26 | } 27 | } 28 | 29 | impl<'a, T> Matcher<&'a Vec> for OfLen { 30 | fn matches(&self, actual: &Vec) -> MatchResult { 31 | if self.len == actual.len() { 32 | success() 33 | } else { 34 | Err(format!("was len {}", actual.len())) 35 | } 36 | } 37 | } 38 | 39 | pub fn of_len(len: usize) -> OfLen { 40 | OfLen { len: len } 41 | } 42 | 43 | #[derive(Clone)] 44 | pub struct Contains { 45 | items: Vec, 46 | exactly: bool, 47 | in_order: bool, 48 | } 49 | 50 | impl Contains { 51 | pub fn exactly(mut self) -> Contains { 52 | self.exactly = true; 53 | self 54 | } 55 | 56 | pub fn in_order(mut self) -> Contains { 57 | self.in_order = true; 58 | self 59 | } 60 | } 61 | 62 | impl fmt::Display for Contains { 63 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 64 | if self.exactly { 65 | write!(f, "containing exactly {}", Pretty(&self.items)) 66 | } else { 67 | write!(f, "containing {}", Pretty(&self.items)) 68 | } 69 | } 70 | } 71 | 72 | impl<'a, T: fmt::Debug + PartialEq + Clone> Matcher<&'a Vec> for Contains { 73 | fn matches(&self, actual: &Vec) -> MatchResult { 74 | let mut rem = actual.clone(); 75 | 76 | for item in self.items.iter() { 77 | match rem.iter().position(|a| *item == *a) { 78 | Some(idx) => { 79 | rem.remove(idx); 80 | } 81 | None => return Err(format!("was {}", Pretty(&actual))), 82 | } 83 | } 84 | 85 | if self.exactly && !rem.is_empty() { 86 | return Err(format!("also had {}", Pretty(&rem))); 87 | } 88 | 89 | if self.in_order && !contains_in_order(actual, &self.items) { 90 | return Err(format!( 91 | "{} does not contain {} in order", 92 | Pretty(&actual), 93 | Pretty(&self.items) 94 | )); 95 | } 96 | 97 | success() 98 | } 99 | } 100 | 101 | fn contains_in_order(actual: &Vec, items: &Vec) -> bool { 102 | let mut previous = None; 103 | 104 | for item in items.iter() { 105 | match actual.iter().position(|a| *item == *a) { 106 | Some(current) => { 107 | if !is_next_index(¤t, &previous) { 108 | return false; 109 | } 110 | previous = Some(current); 111 | } 112 | None => return false, 113 | } 114 | } 115 | 116 | return true; 117 | } 118 | 119 | fn is_next_index(current_index: &usize, previous_index: &Option) -> bool { 120 | if let Some(index) = *previous_index { 121 | return *current_index == index + 1; 122 | } 123 | return true; 124 | } 125 | 126 | pub fn contains(items: Vec) -> Contains { 127 | Contains { 128 | items: items, 129 | exactly: false, 130 | in_order: false, 131 | } 132 | } 133 | 134 | struct Pretty<'a, T: 'a>(&'a [T]); 135 | 136 | impl<'a, T: fmt::Debug> fmt::Display for Pretty<'a, T> { 137 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 138 | try!(write!(f, "[")); 139 | for (i, t) in self.0.iter().enumerate() { 140 | if i != 0 { 141 | try!(write!(f, ", ")); 142 | } 143 | try!(write!(f, "{:?}", t)); 144 | } 145 | write!(f, "]") 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /tests/all_of.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod all_of { 13 | 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn ints_less_than_and_greater_than() { 18 | assert_that!(4, all_of!(less_than(5), greater_than(3))); 19 | } 20 | 21 | #[test] 22 | fn vec_contains() { 23 | assert_that!( 24 | &vec![1, 2, 3], 25 | all_of!(contains(vec![1, 2]), not(contains(vec![4]))) 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /tests/any_of.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod any_of { 13 | 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn ints_less_than_and_greater_than() { 18 | assert_that!(4, any_of!(less_than(2), greater_than(3))); 19 | } 20 | 21 | #[test] 22 | fn vec_contains() { 23 | assert_that!( 24 | &vec![1, 2, 3], 25 | any_of!(contains(vec![1, 2, 5]), not(contains(vec![4]))) 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /tests/anything.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod anything { 13 | 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn usize_is_anything() { 18 | assert_that!(123, is(anything())); 19 | } 20 | 21 | #[test] 22 | fn str_is_anything() { 23 | assert_that!("test", is(anything())); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /tests/boolean.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Povilas Balciunas 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod boolean { 13 | mod is_true { 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn matches_when_true() { 18 | assert_that!(true, is(true)); 19 | } 20 | 21 | #[test] 22 | #[should_panic] 23 | fn fails_when_false() { 24 | assert_that!(false, is(true)); 25 | } 26 | } 27 | 28 | mod is_false { 29 | use hamcrest::prelude::*; 30 | 31 | #[test] 32 | fn matches_when_false() { 33 | assert_that!(false, is(false)); 34 | } 35 | 36 | #[test] 37 | #[should_panic] 38 | fn fails_when_true() { 39 | assert_that!(true, is(false)); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tests/close_to.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod close_to { 13 | 14 | use hamcrest::prelude::*; 15 | use std::f64; 16 | 17 | #[test] 18 | fn equality_of_floats() { 19 | assert_that!(1.0f64, is(close_to(1.0, 0.00001))); 20 | assert_that!(1e-40f32, is(close_to(0.0, 0.01))); 21 | assert_that!(1e-40f32, is(not(close_to(0.0, 0.000001)))); 22 | assert_that!(2.0, is(not(close_to(1.0f64, 0.00001)))); 23 | } 24 | 25 | #[test] 26 | fn it_can_handle_infinity() { 27 | assert_that!(f64::INFINITY, is(close_to(f64::INFINITY, 0.00001))); 28 | } 29 | 30 | #[test] 31 | fn it_can_handle_nan() { 32 | assert_that!(f64::NAN, is(not(close_to(f64::NAN, 0.00001)))); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /tests/compared_to.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // Copyright 2017 Matt LaChance 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | #[macro_use] 11 | extern crate hamcrest; 12 | 13 | mod compared_to { 14 | 15 | use hamcrest::prelude::*; 16 | 17 | #[test] 18 | fn ints_less_than() { 19 | assert_that!(4, is(less_than(5))); 20 | } 21 | 22 | #[test] 23 | #[should_panic] 24 | fn unsuccessful_less_than() { 25 | assert_that!(4, is(less_than(3))); 26 | } 27 | 28 | #[test] 29 | #[should_panic] 30 | fn less_than_is_not_equal() { 31 | assert_that!(2, is(less_than(2))); 32 | } 33 | 34 | #[test] 35 | fn ints_greater_than() { 36 | assert_that!(8, is(greater_than(5))); 37 | } 38 | 39 | #[test] 40 | #[should_panic] 41 | fn unsuccessful_greater_than() { 42 | assert_that!(1, is(greater_than(3))); 43 | } 44 | 45 | #[test] 46 | #[should_panic] 47 | fn greater_than_is_not_equal() { 48 | assert_that!(2, is(greater_than(2))); 49 | } 50 | 51 | #[test] 52 | fn ints_less_than_or_equal() { 53 | assert_that!(3, is(less_than_or_equal_to(7))); 54 | assert_that!(3, is(less_than_or_equal_to(3))); 55 | } 56 | 57 | #[test] 58 | #[should_panic] 59 | fn unsuccessful_less_than_or_equal() { 60 | assert_that!(4, is(less_than_or_equal_to(3))); 61 | } 62 | 63 | #[test] 64 | fn ints_greater_than_or_equal() { 65 | assert_that!(6, is(greater_than_or_equal_to(5))); 66 | assert_that!(8, is(greater_than_or_equal_to(8))); 67 | } 68 | 69 | #[test] 70 | #[should_panic] 71 | fn unsuccessful_greater_than_or_equal() { 72 | assert_that!(4, is(greater_than_or_equal_to(5))); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /tests/equal_to.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod equal_to { 13 | 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn equality_of_ints() { 18 | assert_that!(1, is(equal_to(1))); 19 | } 20 | 21 | #[test] 22 | #[should_panic] 23 | fn unsuccessful_match() { 24 | assert_that!(2, is(equal_to(1))); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /tests/existing_path.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod existing_path { 13 | 14 | pub use hamcrest::prelude::*; 15 | pub use std::env; 16 | pub use std::path::Path; 17 | pub use std::path::PathBuf; 18 | 19 | #[test] 20 | fn an_existing_file() { 21 | let path = path(env::var("TEST_EXISTS_FILE"), "./README.md"); 22 | assert_that!(&path, is(existing_path())); 23 | assert_that!(&path, is(existing_file())); 24 | assert_that!(&path, is_not(existing_dir())); 25 | } 26 | 27 | #[test] 28 | fn an_existing_dir() { 29 | let path = path(env::var("TEST_EXISTS_DIR"), "./target"); 30 | assert_that!(&path, is(existing_path())); 31 | assert_that!(&path, is(existing_dir())); 32 | assert_that!(&path, is_not(existing_file())); 33 | } 34 | 35 | #[test] 36 | fn a_nonexisting_path() { 37 | let path = path(env::var("TEST_EXISTS_NONE"), "./zomg.txt"); 38 | assert_that!(&path, is_not(existing_path())); 39 | assert_that!(&path, is_not(existing_file())); 40 | assert_that!(&path, is_not(existing_dir())); 41 | } 42 | 43 | pub fn path(path: Result, default: &str) -> PathBuf { 44 | Path::new(&path.unwrap_or(default.to_string())).to_owned() 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /tests/none.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod none { 13 | 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn none_is_none() { 18 | assert_that!(None, is(none::())); 19 | } 20 | 21 | #[test] 22 | fn some_is_not_none() { 23 | assert_that!(Some(1), is_not(none())); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /tests/regex.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod regex { 13 | 14 | use hamcrest::prelude::*; 15 | #[test] 16 | fn successful_match() { 17 | assert_that!("123", matches_regex(r"^\d+$")); 18 | } 19 | 20 | #[test] 21 | fn successful_negative_match() { 22 | assert_that!("abc", does_not(matches_regex(r"\d"))); 23 | } 24 | 25 | #[test] 26 | #[should_panic] 27 | fn unsuccessful_match() { 28 | assert_that!("abc", matches_regex(r"\d")); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /tests/type_of.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod type_of { 13 | 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn usize_is_type_of_usize() { 18 | assert_that!(123usize, is(type_of::())); 19 | } 20 | 21 | #[test] 22 | fn str_is_type_of_str() { 23 | assert_that!("test", is(type_of::<&str>())); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /tests/vecs.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Urban Hafner 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate hamcrest; 11 | 12 | mod vecs { 13 | 14 | use hamcrest::prelude::*; 15 | 16 | #[test] 17 | fn vec_contains() { 18 | assert_that!(&vec![1, 2, 3], contains(vec![1, 2])); 19 | assert_that!(&vec![1, 2, 3], not(contains(vec![4]))); 20 | } 21 | 22 | #[test] 23 | fn vec_contains_exactly() { 24 | assert_that!(&vec![1, 2, 3], contains(vec![1, 2, 3]).exactly()); 25 | assert_that!(&vec![1, 2, 3], not(contains(vec![1, 2]).exactly())); 26 | } 27 | 28 | #[test] 29 | fn it_contains_elements_in_order() { 30 | assert_that!(&vec![1, 2, 3], contains(vec![1, 2]).in_order()); 31 | } 32 | 33 | #[test] 34 | fn it_does_not_contain_elements_in_order() { 35 | assert_that!(&vec![1, 2, 3], not(contains(vec![1, 3]).in_order())); 36 | } 37 | 38 | #[test] 39 | #[should_panic] 40 | fn it_unsuccessfully_contains_elements_in_order() { 41 | assert_that!(&vec![1, 2, 3], contains(vec![1, 3]).in_order()); 42 | } 43 | 44 | #[test] 45 | #[should_panic] 46 | fn it_unsuccessfully_does_not_contain_elements_in_order() { 47 | assert_that!(&vec![1, 2, 3], not(contains(vec![2, 3]).in_order())); 48 | } 49 | 50 | #[test] 51 | fn vec_of_len() { 52 | assert_that!(&vec![1, 2, 3], of_len(3)); 53 | assert_that!(&vec![1, 2, 3], is(of_len(3))); 54 | } 55 | 56 | } 57 | --------------------------------------------------------------------------------