├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── proptest-regressions └── runner.txt ├── release.toml └── src ├── lib.rs └── runner.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | .idea 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "monarch" 3 | version = "0.1.0" 4 | authors = ["Zach Mitchell "] 5 | edition = "2018" 6 | description = "A (currently) barebones metamorphic testing utility" 7 | repository = "https://github.com/zmitchell/monarch" 8 | readme = "README.md" 9 | keywords = ["testing", "metamorphic-testing"] 10 | categories = ["development-tools::testing"] 11 | license = "MIT OR Apache-2.0" 12 | 13 | [dependencies] 14 | 15 | [dev-dependencies] 16 | proptest = "^0.9.4" 17 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Zach Mitchell 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Monarch 2 | 3 | Monarch is a barebones utility for metamorphic testing in Rust. For an overview of metamorphic testing and some examples, there is an excellent blog post by Hillel Wayne: 4 | - [Metamorphic Testing - Hillel Wayne](https://hillelwayne.com/post/metamorphic-testing/) 5 | 6 | Monarch is currently still in the experimental stage, so the API is subject to my whims at this point. 7 | 8 | ## Metamorphic tests 9 | 10 | With a basic test you're checking that a specific input produces a specific, expected output. 11 | ```rust 12 | fn double(x: i32) -> i32 { 13 | 2 * x 14 | } 15 | 16 | #[test] 17 | fn test_double() { 18 | let doubled = double(5); 19 | assert_eq!(doubled, 10); // We already know what "doubled" should be! 20 | } 21 | ``` 22 | 23 | These tests can be quick and easy to write, but they don't always provide good test coverage because the responsibility falls on the developer to predict which inputs will uncover bugs. 24 | Futhermore, you can end up with lots of duplicated code between tests that perform the same operation with slightly different inputs. 25 | 26 | A metamorphic test works differently. When you write a metamorphic test you supply a few pieces of information: 27 | - An input to start out with 28 | - Ways to transform that input 29 | - An operation that turns an input into an output 30 | - A relationship that should be satisfied between the output of the original input and the transformed input 31 | 32 | First an output is computed from the original input. Next you compute a new, transformed input for every possible combination of transformations and produce an output for each of those. Finally, you check that your relation holds between the "original" output and each "transformed" output. 33 | 34 | That might sound complicated, but the transformations and relations can be extremely simple. On top of that, the more transformations you supply, the wider variety of inputs you'll generate, and the better coverage you'll get from this one test. 35 | 36 | Let's do a quick example. 37 | 38 | ## Example 39 | Let's say I'm working on a web app that returns some search results in response to a user's query. 40 | For my relation I'm going to require that I should get the same number of search results as the original input. 41 | 42 | ```rust 43 | #[test] 44 | fn test_search_results() { 45 | let mut runner: MetamorphicTestRunner> = MetamorphicTestRunner::new(); 46 | // ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ 47 | // input type output type 48 | let original_input = MyHTTPRequest::new(); 49 | runner.set_input(original_input.clone()); 50 | runner.set_relation(|&original_output, &transformed_output| { 51 | original_output.len() == transformed_output.len() 52 | }); 53 | } 54 | ``` 55 | 56 | The next order of business is coming up with ways to tweak the input that shouldn't affect how many total search results I get back. 57 | A few examples are changing the sort order of the results, changing the number of results per page, etc. 58 | ```rust 59 | runner.add_transformation(|&mut request| { 60 | request.sort_order = ... // Sort by some parameter 61 | }); 62 | runner.add_transformation(|&mut request| { 63 | request.page_results = ... // Some number of results per page 64 | }); 65 | ``` 66 | 67 | The last thing to do is to tell the test runner what operation to perform with each request in order to produce an output (e.g. send it to the server), and run the test. 68 | ```rust 69 | runner.set_operation(|&request| { 70 | // send the request 71 | }); 72 | runner.run().unwrap(); 73 | ``` 74 | 75 | The test runner will run the input through all combinations of the supplied transformations, and panic if the relation isn't satisfied. 76 | 77 | ## Error Reporting 78 | 79 | The final format of the error reporting is still up in the air. Currently the test runner will identify which test case failed (which transformed input caused the failure), but this is returned as a `MonarchError::TestFailure(Reason)`, where `Reason` has a method `message` which will return a `String` explaining the failure. 80 | 81 | ## License 82 | 83 | Licensed under either of 84 | 85 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 86 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 87 | 88 | at your option. 89 | 90 | ### Contribution 91 | 92 | Unless you explicitly state otherwise, any contribution intentionally 93 | submitted for inclusion in the work by you, as defined in the Apache-2.0 94 | license, shall be dual licensed as above, without any additional terms or 95 | conditions. 96 | 97 | ## FAQ 98 | - Why "monarch"? 99 | - Metamorphic testing -> metamorphosis -> butterflies -> monarch 100 | - Should I use this? 101 | - One day, but not today 102 | - Are you looking for contributors? 103 | - Contributions would be great once I get things up and running! 104 | -------------------------------------------------------------------------------- /proptest-regressions/runner.txt: -------------------------------------------------------------------------------- 1 | # Seeds for failure cases proptest has generated in the past. It is 2 | # automatically read and these particular cases re-run before any 3 | # novel cases are generated. 4 | # 5 | # It is recommended to check this file in to source control so that 6 | # everyone who runs the test benefits from these saved cases. 7 | cc 2c52b71a59f395cbec9ef8edec08aa46050ebfd341f919ab442558099fcd88e5 # shrinks to (indices, items) = ([0], [1]) 8 | cc 3dde89eaaab869bd37117234136777f6f54f5057be8f4e13f7ce80622282225c # shrinks to (indices, items) = ([0, 1], [1, 2]) 9 | cc d383c824f944c43eb21b07a7ab213ee1b4077870367ef478452a53f5b466bf8a # shrinks to (list, k) = ([8285442291085864714, 8891531040313862139, 10071136621965123754, 398708859798776713, 9017303705221743612, 12601458486210431958, 13736910551547584780, 12969992707571137395, 2444497746743817656, 4920956831727794990, 4100001297796134674, 12984961046930934836, 1804202113722278068, 14228039523968544480, 12576487822012863861, 12467930377831198019, 16327348708998656276, 432551666660531000, 8250345389414968247, 7084207375524337455, 1161497298798779992, 676440771193981671, 9136463081767262428, 4950326852059807116, 8301460787559630507, 12340138199708880138, 14446477845305286611, 4912477782261224624, 17184067284388580693, 13825310475955644664, 1907527182208652367, 9740061035174959773, 16991911974420902737, 280750401236181038, 6795550462531037138, 2634216566690415517, 1678961755075193852, 10556987751883103540, 4113726987759872456, 11619657027180310396, 606183832376979689, 14661239999861685929, 14061164458411833168, 8205276590362110937, 6150502343449092018, 11597372219325455543, 16158065000821370968, 13297075992772966978, 13620681686785736888, 2245109365027045614, 6644781455543878048, 3795127517494020101, 6618227697301014276, 1528729291134164696, 3436206961806369224, 5418627670397757414, 3827653326170508974, 8487801825963216868, 8102266651253259346, 2257683189196961752, 13957901498749665355, 9838254875337229833, 14120164789588786181, 10391779893581526210, 14286717452265771911, 13664463846795318072, 2355494864111493582, 14826544902168791308, 10318706631177617602, 6261094064529472185, 17713119611316584474, 13288011826531424256, 10617864980200532997, 11595076058559097942, 32290421521597610, 5485553914711254929, 13208724760726022274, 14173956420330944254, 2407078429394095390, 410006481576476857, 17032882041755961947, 4892036962721134278, 7830423549902492170, 16763244543367928358, 6462822879061933560, 14232136476507004203, 14930583409375138846, 11859417917974434068, 11687935272641831331], 89) 10 | cc 3710fb23a8123114082c95cd093d9140b258fc9b55820d81158e1a54c99fc287 # shrinks to (items, k) = ([0, 0], 2) 11 | -------------------------------------------------------------------------------- /release.toml: -------------------------------------------------------------------------------- 1 | no-dev-version = true 2 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod runner; 2 | 3 | pub use runner::{MetamorphicTestRunner, MonarchError}; 4 | -------------------------------------------------------------------------------- /src/runner.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | use proptest::collection; 3 | #[cfg(test)] 4 | use proptest::prelude::*; 5 | use std::fmt::Debug; 6 | use std::panic; 7 | 8 | #[derive(Debug, Clone, PartialEq)] 9 | pub struct Reason { 10 | msg: String, 11 | } 12 | 13 | impl Reason { 14 | fn message(&self) -> String { 15 | self.msg.clone() 16 | } 17 | } 18 | 19 | /// An error that may be encountered while running metamorphic tests. 20 | #[derive(Debug, PartialEq, Clone)] 21 | pub enum MonarchError { 22 | /// The test configuration is invalid 23 | Invalid(Reason), 24 | 25 | /// The test failed 26 | TestFailure(Reason), 27 | } 28 | 29 | /// The struct responsible for running the metamorphic test suite. 30 | pub struct MetamorphicTestRunner { 31 | input: Option, 32 | operation: Option OUT>>, 33 | transformations: Vec IN>>, 34 | relation: Option bool>>, 35 | } 36 | 37 | impl Default for MetamorphicTestRunner { 38 | fn default() -> Self { 39 | Self::new() 40 | } 41 | } 42 | 43 | impl MetamorphicTestRunner { 44 | /// Construct a new test runner. 45 | pub fn new() -> Self { 46 | MetamorphicTestRunner { 47 | input: None, 48 | operation: None, 49 | transformations: Vec::new(), 50 | relation: None, 51 | } 52 | } 53 | 54 | /// Supply an additional way of transforming an input. 55 | pub fn add_transformation(&mut self, f: impl Fn(&mut IN) -> IN + 'static) { 56 | self.transformations.push(Box::new(f)); 57 | } 58 | 59 | /// Set the initial input. 60 | /// 61 | /// This initial input along with the operation will be used to compute an output against which 62 | /// all other outputs will be compared using the supplied metamorphic relation. 63 | pub fn set_input(&mut self, input: IN) { 64 | self.input = Some(input); 65 | } 66 | 67 | /// Set the operation which will be used to compute an output for each input. 68 | pub fn set_operation(&mut self, f: impl Fn(&IN) -> OUT + 'static) { 69 | self.operation = Some(Box::new(f)); 70 | } 71 | 72 | /// Set the metamorphic relation which determines whether two outputs pass the test. 73 | pub fn set_relation(&mut self, f: impl Fn(&OUT, &OUT) -> bool + 'static) { 74 | self.relation = Some(Box::new(f)); 75 | } 76 | 77 | /// Run the metamorphic test. 78 | // TODO: At some point it would probably be a good idea to cache the combinations so they aren't 79 | // computed every time a new input is set. 80 | pub fn run(&mut self) -> Result<(), MonarchError> { 81 | if self.input.is_none() { 82 | return Err(MonarchError::Invalid(Reason { 83 | msg: String::from("No input was provided"), 84 | })); 85 | } 86 | if self.operation.is_none() { 87 | return Err(MonarchError::Invalid(Reason { 88 | msg: String::from("No operation was provided"), 89 | })); 90 | } 91 | if self.relation.is_none() { 92 | return Err(MonarchError::Invalid(Reason { 93 | msg: String::from("No relation was provided"), 94 | })); 95 | } 96 | if self.transformations.is_empty() { 97 | return Err(MonarchError::Invalid(Reason { 98 | msg: String::from("No transformations were provided"), 99 | })); 100 | } 101 | let op = self.operation.take().unwrap(); 102 | let input = self.input.take().unwrap(); 103 | let relation = self.relation.take().unwrap(); 104 | let src_output = op(&input); 105 | let mut trans_combinations = Vec::new(); 106 | for i in 1..self.transformations.len() { 107 | let combs = combinations(self.transformations.len(), i)?; 108 | trans_combinations.extend_from_slice(combs.as_slice()); 109 | } 110 | for comb in trans_combinations.iter() { 111 | let mut trans_input = input.clone(); 112 | for i in comb.iter() { 113 | trans_input = self.transformations[*i](&mut trans_input); 114 | } 115 | let trans_output = op(&trans_input); 116 | let test_result = panic::catch_unwind(panic::AssertUnwindSafe(|| { 117 | assert!(relation(&src_output, &trans_output)); 118 | })); 119 | if test_result.is_err() { 120 | return Err(MonarchError::TestFailure(Reason { 121 | msg: format!( 122 | "Test failed with original input {:?} and transformed input {:?}", 123 | input.clone(), 124 | trans_input 125 | ), 126 | })); 127 | } 128 | } 129 | Ok(()) 130 | } 131 | } 132 | 133 | /// Return all combinations (without replacement) of size `k` from a list of `n` items. 134 | /// 135 | /// This will return n! / k! (n - k)! combinations. 136 | fn combinations(n: usize, k: usize) -> Result>, MonarchError> { 137 | if n == 0 { 138 | return Err(MonarchError::Invalid(Reason { 139 | msg: String::from("Invalid number of combinations"), 140 | })); 141 | } 142 | if k > n { 143 | return Err(MonarchError::Invalid(Reason { 144 | msg: String::from("Invalid number of combinations"), 145 | })); 146 | } 147 | if k == 0 { 148 | return Err(MonarchError::Invalid(Reason { 149 | msg: String::from("Invalid number of combinations"), 150 | })); 151 | } 152 | if k == 1 { 153 | return Ok(each_index_separately(n)); 154 | } 155 | let last_index = k - 1; 156 | let start_of_last_k_elements = n - k; 157 | let mut current_indices: Vec = (0..k).collect(); 158 | let mut items: Vec> = Vec::new(); 159 | items.push(current_indices.clone()); 160 | loop { 161 | if indices_are_in_final_positions(current_indices.as_slice(), n, k) { 162 | return Ok(items); 163 | } 164 | while current_indices[last_index] < (start_of_last_k_elements + last_index) { 165 | current_indices[last_index] += 1; 166 | items.push(current_indices.clone()); 167 | } 168 | pack_indices_leftward(&mut current_indices, n, k); 169 | items.push(current_indices.clone()); 170 | } 171 | } 172 | 173 | /// Returns each element in its own vector. 174 | /// 175 | /// This is useful when the combination size is 1, as this avoids all the other machinery. 176 | fn each_index_separately(n: usize) -> Vec> { 177 | let mut items: Vec> = Vec::with_capacity(n); 178 | for i in 0..n { 179 | items.push(Vec::with_capacity(1)); 180 | items[i].push(i); 181 | } 182 | items 183 | } 184 | 185 | /// Returns true if the indices point to the last `k` elements of a collection with length `n` 186 | /// in order. 187 | /// 188 | /// For a list of length 5 and a list of indices of length 3, the final positions would 189 | /// be (2, 3, 4). 190 | fn indices_are_in_final_positions(indices: &[usize], n: usize, k: usize) -> bool { 191 | let start_of_last_k_elements = n - k; 192 | (0..k) 193 | .map(|i| indices[i] == (start_of_last_k_elements + i)) 194 | .all(|x| x) 195 | } 196 | 197 | /// Find the rightmost index that is not in its final position and pack all indices that follow 198 | /// immediately following this index. 199 | /// 200 | /// Given a list of items with length 10 and the indices (0, 2, 8, 9), the last two indices are in 201 | /// their final positions. The rightmost index not in its final position is the index with value 2. 202 | /// The last two indices will be packed to the left so that the result is (0, 2, 3, 4). 203 | fn pack_indices_leftward(indices: &mut Vec, n: usize, k: usize) { 204 | let start_of_last_k_elements = n - k; 205 | // Find the rightmost index that isn't in its final position and increment it. 206 | for i in (0..=(k - 2)).rev() { 207 | if indices[i] != (start_of_last_k_elements + i) { 208 | indices[i] += 1; 209 | // Pack the indices that follow `i` to the left so that `i`, `i+1`, ... are 210 | // all one after another. 211 | for (x, j) in (i + 1..k).enumerate() { 212 | indices[j] = indices[i] + x + 1; // enumerate starts at 0 213 | } 214 | break; 215 | } 216 | } 217 | } 218 | 219 | #[cfg(test)] 220 | mod tests { 221 | use super::*; 222 | 223 | /// Returns the number of combinations given the length of the list and the number of items in 224 | /// each combination. 225 | fn num_combinations(n: usize, k: usize) -> Result { 226 | let numerator = ((k + 1)..=n).rev().fold(Some(1usize), |acc, x| match acc { 227 | Some(acc) => acc.checked_mul(x), 228 | None => None, 229 | }); 230 | let bottom = factorial(n - k)?; 231 | match numerator { 232 | Some(top) => Ok(top / bottom), 233 | None => { 234 | return Err(MonarchError::Invalid(Reason { 235 | msg: String::from("Number of combinations too large"), 236 | })); 237 | } 238 | } 239 | } 240 | 241 | /// Returns the factorial of `n` 242 | fn factorial(n: usize) -> Result { 243 | if n > 20 { 244 | return Err(MonarchError::Invalid(Reason { 245 | msg: String::from("Invalid number of combinations"), 246 | })); 247 | } 248 | if n == 0 { 249 | return Ok(1); 250 | } 251 | Ok((1..=n).product()) 252 | } 253 | 254 | /// A strategy to produce a vector of indices into a vector of items. 255 | /// 256 | /// The return value is a tuple (indices_vec, items_vec). The `indices_vec` is guaranteed to be 257 | /// no longer than the `items_vec`. The contents of `indices_vec` have very few constraints. The 258 | /// maximum value of any index is the final index of `items_vec`, but the indices are in no 259 | /// particular order and may not even be unique. 260 | fn indices_and_items() -> impl Strategy, Vec)> { 261 | collection::vec(any::(), 1..100usize) 262 | .prop_flat_map(|v| (collection::vec(0..v.len(), 1..=v.len()), Just(v))) 263 | } 264 | 265 | /// A strategy to produce a vector of indices into an imaginary vector of items with length `n`. 266 | /// 267 | /// The return value is a tuple (indices_vec, n). The `indices_vec` is guaranteed to be 268 | /// no longer than the `n` indices. The indices are guaranteed to be unique and in the final 269 | /// state i.e. for an `items_vec` of length `n` and `indices_vec` of length `k`, the indices in 270 | /// the `indices_vec` will point to the last `k` items in `items_vec` with the indices in 271 | /// ascending order. 272 | /// 273 | /// This strategy is simpler and faster when you only care about the ordering of the indices and 274 | /// don't actually need the contents of the `items_vec`. 275 | fn indices_and_items_length_final() -> impl Strategy, usize)> { 276 | (1..100usize).prop_flat_map(|n| { 277 | ( 278 | (1..=n).prop_map(move |k| { 279 | let start_of_last_k_items = n - k; 280 | let mut ind_vec = Vec::with_capacity(k); 281 | for i in 0..k { 282 | ind_vec.push(start_of_last_k_items + i); 283 | } 284 | ind_vec 285 | }), 286 | Just(n), 287 | ) 288 | }) 289 | } 290 | 291 | /// A strategy producing two usizes where one is less than the other. 292 | fn valid_n_and_k(lim: usize) -> impl Strategy { 293 | (1usize..=lim).prop_flat_map(|n| (Just(n), 1..=n)) 294 | } 295 | 296 | /// A strategy producing two usizes where one is less than the other. 297 | fn valid_n_and_too_large_k(lim: usize) -> impl Strategy { 298 | (2usize..=lim).prop_flat_map(|k: usize| (1..k, Just(k))) 299 | } 300 | 301 | #[test] 302 | fn it_errors_when_operation_is_missing() { 303 | let mut runner: MetamorphicTestRunner = MetamorphicTestRunner::new(); 304 | runner.set_input(0); 305 | runner.set_relation(|&x, &y| x == y); 306 | runner.add_transformation(|&mut x| x); 307 | match runner.run() { 308 | Err(err) => { 309 | let dummy_error = MonarchError::Invalid(Reason { msg: String::new() }); 310 | assert_eq!( 311 | std::mem::discriminant(&err), 312 | std::mem::discriminant(&dummy_error) 313 | ); 314 | } 315 | _ => panic!(), 316 | } 317 | } 318 | 319 | #[test] 320 | fn it_errors_when_relation_is_missing() { 321 | let mut runner: MetamorphicTestRunner = MetamorphicTestRunner::new(); 322 | runner.set_input(0); 323 | runner.set_operation(|&x| x); 324 | runner.add_transformation(|&mut x| x); 325 | match runner.run() { 326 | Err(err) => { 327 | let dummy_error = MonarchError::Invalid(Reason { msg: String::new() }); 328 | assert_eq!( 329 | std::mem::discriminant(&err), 330 | std::mem::discriminant(&dummy_error) 331 | ); 332 | } 333 | _ => panic!(), 334 | } 335 | } 336 | 337 | #[test] 338 | fn it_errors_when_input_is_missing() { 339 | let mut runner: MetamorphicTestRunner = MetamorphicTestRunner::new(); 340 | runner.set_relation(|&x, &y| x == y); 341 | runner.set_operation(|&x| x); 342 | runner.add_transformation(|&mut x| x); 343 | match runner.run() { 344 | Err(err) => { 345 | let dummy_error = MonarchError::Invalid(Reason { msg: String::new() }); 346 | assert_eq!( 347 | std::mem::discriminant(&err), 348 | std::mem::discriminant(&dummy_error) 349 | ); 350 | } 351 | _ => panic!(), 352 | } 353 | } 354 | 355 | #[test] 356 | fn it_errors_when_transformations_are_missing() { 357 | let mut runner: MetamorphicTestRunner = MetamorphicTestRunner::new(); 358 | runner.set_relation(|&x, &y| x == y); 359 | runner.set_operation(|&x| x); 360 | runner.set_input(0); 361 | match runner.run() { 362 | Err(err) => { 363 | let dummy_error = MonarchError::Invalid(Reason { msg: String::new() }); 364 | assert_eq!( 365 | std::mem::discriminant(&err), 366 | std::mem::discriminant(&dummy_error) 367 | ); 368 | } 369 | _ => panic!(), 370 | } 371 | } 372 | 373 | #[test] 374 | fn it_completes_basic_test() { 375 | let mut runner: MetamorphicTestRunner<(i32, i32), i32> = MetamorphicTestRunner::new(); 376 | runner.set_input((2, 2)); 377 | runner.set_relation(|&z1, &z2| z1.signum() == z2.signum()); 378 | runner.set_operation(|&(x, y)| x + y); 379 | runner.add_transformation(|&mut (x, y)| (2 * x, 2 * y)); 380 | runner.add_transformation(|&mut (x, y)| (y, x)); 381 | runner.run().unwrap(); 382 | } 383 | 384 | #[test] 385 | fn error_when_k_is_zero() { 386 | let res = combinations(5usize, 0usize); 387 | match res { 388 | Err(e) => { 389 | let dummy_error = MonarchError::Invalid(Reason { msg: String::new() }); 390 | assert_eq!( 391 | std::mem::discriminant(&e), 392 | std::mem::discriminant(&dummy_error) 393 | ); 394 | } 395 | _ => assert!(false), 396 | } 397 | } 398 | 399 | #[test] 400 | #[should_panic] 401 | fn combinations_are_applied() { 402 | // This is a check to make sure that combinations of different sizes are being applied. 403 | // The two ends of the spectrum are one transformation at a time and combinations that 404 | // are the same size as the number of transformations. With three transformations the 405 | // middle case is two transformations. You can differentiate this case by incrementing a 406 | // starting value and looking for a value with the correct parity. 407 | let mut runner: MetamorphicTestRunner = MetamorphicTestRunner::new(); 408 | runner.set_input(0); 409 | runner.set_relation(|&orig, &trans| { 410 | if (trans == 1) || (trans == 3) { 411 | return true; 412 | } else if trans == 2 { 413 | return false; 414 | } else { 415 | return true; 416 | } 417 | }); 418 | runner.set_operation(|&x| x); 419 | runner.add_transformation(|&mut x| x + 1); 420 | runner.add_transformation(|&mut x| x + 1); 421 | runner.add_transformation(|&mut x| x + 1); 422 | runner.run().unwrap(); 423 | } 424 | 425 | #[test] 426 | #[should_panic] 427 | fn catches_test_failure() { 428 | let mut runner: MetamorphicTestRunner = MetamorphicTestRunner::new(); 429 | runner.set_input(0); 430 | runner.set_relation(|&orig, &trans| orig > trans); 431 | runner.set_operation(|&x| x); 432 | runner.add_transformation(|&mut x| x + 1); 433 | runner.add_transformation(|&mut x| x - 1); 434 | runner.run().unwrap(); 435 | } 436 | 437 | proptest! { 438 | #[test] 439 | fn correctly_identifies_final_index_positions( 440 | (indices, n) in indices_and_items_length_final() 441 | ) { 442 | prop_assert!(indices_are_in_final_positions(indices.as_ref(), n, indices.len())); 443 | } 444 | 445 | #[test] 446 | fn correctly_identifies_nonfinal_index_positions( 447 | (indices, items) in indices_and_items() 448 | ) { 449 | let n = items.len(); 450 | let k = indices.len(); 451 | let is_final = (0..k) 452 | .map(|i| { 453 | indices[k - 1 - i] == n - 1 - i 454 | }) 455 | .all(|x| x); 456 | prop_assume!(!is_final); 457 | prop_assert!(!indices_are_in_final_positions(indices.as_ref(), n, k)); 458 | } 459 | 460 | #[test] 461 | fn error_when_k_too_large( 462 | (n, k) in valid_n_and_too_large_k(100) 463 | ) { 464 | let res = combinations(n, k); 465 | match res { 466 | Err(e) => { 467 | let dummy_error = MonarchError::Invalid(Reason { msg: String::new() }); 468 | prop_assert_eq!(std::mem::discriminant(&e), std::mem::discriminant(&dummy_error)); 469 | }, 470 | Ok(_) => prop_assert!(false), 471 | } 472 | } 473 | 474 | #[test] 475 | fn error_when_list_is_empty(k: usize) { 476 | prop_assume!(k > 0); 477 | let res = combinations(0usize, k); 478 | match res { 479 | Err(e) => { 480 | let dummy_error = MonarchError::Invalid(Reason { msg: String::new() }); 481 | prop_assert_eq!(std::mem::discriminant(&e), std::mem::discriminant(&dummy_error)); 482 | }, 483 | _ => prop_assert!(false), 484 | } 485 | } 486 | 487 | #[test] 488 | fn correct_num_combinations_produced( 489 | (n, k) in valid_n_and_k(20) 490 | ) { 491 | let expected_num = num_combinations(n, k).unwrap(); 492 | let mut combs = combinations(n, k).unwrap(); 493 | let num_combs = combs.len(); 494 | combs.sort_unstable(); 495 | combs.dedup(); 496 | let unique_combs = combs.len(); 497 | prop_assert_eq!(num_combs, unique_combs); 498 | prop_assert_eq!(expected_num, unique_combs); 499 | } 500 | 501 | } 502 | } 503 | --------------------------------------------------------------------------------