├── .gitignore ├── LICENSE ├── README.md ├── comparators.go ├── comparators_test.go ├── pluck.go ├── pluck_test.go ├── rule.go └── rule_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | grules 2 | 3 | # Introduction 4 | 5 | This package was created with inspiration from Thomas' [go-ruler](https://github.com/hopkinsth/go-ruler) to run a simple set of rules against an entity. 6 | 7 | This version includes a couple more features including, AND and OR composites and the ability to add custom comparators. 8 | 9 | **Note**: This package only compares two types: `string` and `float64`, this plays nicely with `encoding/json`. 10 | 11 | # Example 12 | 13 | ```go 14 | // Create a new instance of an engine with some default comparators 15 | e, err := NewJSONEngine(json.RawMessage(`{"composites":[{"operator":"or","rules":[{"comparator":"always-false","path":"user.name","value":"Trevor"},{"comparator":"eq","path":"user.name","value":"Trevor"}]}]}`)) 16 | if err != nil { 17 | panic(err) 18 | } 19 | 20 | // Add a new, custom comparator 21 | e = e.AddComparator("always-false", func(a, b interface{}) bool { 22 | return false 23 | }) 24 | 25 | // Give some properties, this map can be deeper and supports interfaces 26 | props := map[string]interface{}{ 27 | "user": map[string]interface{}{ 28 | "name": "Trevor", 29 | } 30 | } 31 | 32 | // Run the engine on the props 33 | res := e.Evaluate(props) 34 | // res == true 35 | ``` 36 | 37 | # Comparators 38 | 39 | - `eq` will return true if `a == b` 40 | - `neq` will return true if `a != b` 41 | - `lt` will return true if `a < b` 42 | - `lte` will return true if `a <= b` 43 | - `gt` will return true if `a > b` 44 | - `gte` will return true if `a >= b` 45 | - `contains` will return true if `a` contains `b` 46 | - `ncontains` will return true if `a` does not contain `b` 47 | - `oneof` will return true if `a` is one of `b` 48 | - `noneof` will return true if `a` is not one of `b` 49 | - `regex` will return true if `a` matches `b` 50 | 51 | `contains` and `ncontains` work for substring comparisons as well as item-in-collection comparisons. 52 | 53 | When used for item-in-collection comparisons, `contains` expects the first argument to be a slice. `contains` is different than `oneof` in that `oneof` expects the second argument to be a slice. 54 | 55 | # Benchmarks 56 | 57 | | Benchmark | N | Speed | Used | Allocs | 58 | | -------------------------------- | ---------- | ------------ | --------- | ------------ | 59 | | BenchmarkEqual-12 | 650602549 | 5.52 ns/op | 0 B/op | 0 allocs/op | 60 | | BenchmarkNotEqual-12 | 876894124 | 4.09 ns/op | 0 B/op | 0 allocs/op | 61 | | BenchmarkLessThan-12 | 1000000000 | 2.84 ns/op | 0 B/op | 0 allocs/op | 62 | | BenchmarkLessThanEqual-12 | 1000000000 | 2.57 ns/op | 0 B/op | 0 allocs/op | 63 | | BenchmarkGreaterThan-12 | 1000000000 | 2.07 ns/op | 0 B/op | 0 allocs/op | 64 | | BenchmarkGreaterThanEqual-12 | 1000000000 | 2.86 ns/op | 0 B/op | 0 allocs/op | 65 | | BenchmarkRegex-12 | 4524237 | 793 ns/op | 753 B/op | 11 allocs/op | 66 | | BenchmarkRegexPhone-12 | 1000000 | 3338 ns/op | 3199 B/op | 30 allocs/op | 67 | | BenchmarkContains-12 | 499627219 | 7.16 ns/op | 0 B/op | 0 allocs/op | 68 | | BenchmarkStringContains-12 | 405497102 | 8.87 ns/op | 0 B/op | 0 allocs/op | 69 | | BenchmarkContainsLong50000-12 | 18992 | 184016 ns/op | 0 B/op | 0 allocs/op | 70 | | BenchmarkNotContains-12 | 292932907 | 12.3 ns/op | 0 B/op | 0 allocs/op | 71 | | BenchmarkStringNotContains-12 | 392618857 | 9.14 ns/op | 0 B/op | 0 allocs/op | 72 | | BenchmarkNotContainsLong50000-12 | 19243 | 191787 ns/op | 0 B/op | 0 allocs/op | 73 | | BenchmarkOneOf-12 | 1000000000 | 1.80 ns/op | 0 B/op | 0 allocs/op | 74 | | BenchmarkNoneOf-12 | 1000000000 | 1.79 ns/op | 0 B/op | 0 allocs/op | 75 | | BenchmarkPluckShallow-12 | 85997188 | 41.6 ns/op | 16 B/op | 1 allocs/op | 76 | | BenchmarkPluckDeep-12 | 18789103 | 194 ns/op | 112 B/op | 1 allocs/op | 77 | | BenchmarkRule_evaluate-12 | 69558996 | 51.1 ns/op | 16 B/op | 1 allocs/op | 78 | | BenchmarkComposite_evaluate-12 | 59484760 | 55.7 ns/op | 16 B/op | 1 allocs/op | 79 | | BenchmarkEngine_Evaluate-12 | 47892318 | 75.0 ns/op | 16 B/op | 1 allocs/op | 80 | 81 | To run benchmarks: 82 | 83 | ``` 84 | go test -run none -bench . -benchtime 3s -benchmem 85 | ``` 86 | 87 | All benchmarks were run on: 88 | 89 | MacOS High Sierra 2.6Ghz Intel Core i7 16 GB 2400 MHz DDR4 90 | 91 | # License 92 | 93 | Copyright © 2019 Trevor Hutto 94 | 95 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at: 96 | 97 | http://www.apache.org/licenses/LICENSE-2.0 98 | 99 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 100 | -------------------------------------------------------------------------------- /comparators.go: -------------------------------------------------------------------------------- 1 | package grules 2 | 3 | import ( 4 | "regexp" 5 | "strings" 6 | ) 7 | 8 | // Comparator is a function that should evaluate two values and return 9 | // the true if the comparison is true, or false if the comparison is 10 | // false 11 | type Comparator func(a, b interface{}) bool 12 | 13 | // equal will return true if a == b 14 | func equal(a, b interface{}) bool { 15 | return a == b 16 | } 17 | 18 | // notEqual will return true if a != b 19 | func notEqual(a, b interface{}) bool { 20 | return !equal(a, b) 21 | } 22 | 23 | // lessThan will return true if a < b 24 | func lessThan(a, b interface{}) bool { 25 | switch a.(type) { 26 | case string: 27 | at, ok := a.(string) 28 | if !ok { 29 | return false 30 | } 31 | bt, ok := b.(string) 32 | if !ok { 33 | return false 34 | } 35 | return at < bt 36 | case float64: 37 | at, ok := a.(float64) 38 | if !ok { 39 | return false 40 | } 41 | bt, ok := b.(float64) 42 | if !ok { 43 | return false 44 | } 45 | return at < bt 46 | default: 47 | return false 48 | } 49 | } 50 | 51 | func lessThanEqual(a, b interface{}) bool { 52 | switch a.(type) { 53 | case string: 54 | at, ok := a.(string) 55 | if !ok { 56 | return false 57 | } 58 | bt, ok := b.(string) 59 | if !ok { 60 | return false 61 | } 62 | return at <= bt 63 | case float64: 64 | at, ok := a.(float64) 65 | if !ok { 66 | return false 67 | } 68 | bt, ok := b.(float64) 69 | if !ok { 70 | return false 71 | } 72 | return at <= bt 73 | default: 74 | return false 75 | } 76 | } 77 | 78 | // greaterThan will return true if a > b 79 | func greaterThan(a, b interface{}) bool { 80 | switch a.(type) { 81 | case string: 82 | at, ok := a.(string) 83 | if !ok { 84 | return false 85 | } 86 | bt, ok := b.(string) 87 | if !ok { 88 | return false 89 | } 90 | return at > bt 91 | case float64: 92 | at, ok := a.(float64) 93 | if !ok { 94 | return false 95 | } 96 | bt, ok := b.(float64) 97 | if !ok { 98 | return false 99 | } 100 | return at > bt 101 | default: 102 | return false 103 | } 104 | } 105 | 106 | // greaterThanEqual will return true if a >= b 107 | func greaterThanEqual(a, b interface{}) bool { 108 | switch a.(type) { 109 | case string: 110 | at, ok := a.(string) 111 | if !ok { 112 | return false 113 | } 114 | bt, ok := b.(string) 115 | if !ok { 116 | return false 117 | } 118 | return at >= bt 119 | case float64: 120 | at, ok := a.(float64) 121 | if !ok { 122 | return false 123 | } 124 | bt, ok := b.(float64) 125 | if !ok { 126 | return false 127 | } 128 | return at >= bt 129 | default: 130 | return false 131 | } 132 | } 133 | 134 | func regex(a, b interface{}) bool { 135 | switch a.(type) { 136 | case string: 137 | at, ok := a.(string) 138 | if !ok { 139 | return false 140 | } 141 | bt, ok := b.(string) 142 | if !ok { 143 | return false 144 | } 145 | 146 | r, err := regexp.Compile(bt) 147 | if err != nil { 148 | return false 149 | } 150 | 151 | return r.MatchString(at) 152 | default: 153 | return false 154 | } 155 | } 156 | 157 | // contains will return true if a contains b. a can be a slice 158 | // or a string. If you need b to be a slice consider using oneOf 159 | func contains(a, b interface{}) bool { 160 | switch bt := b.(type) { 161 | case string: 162 | switch at := a.(type) { 163 | case []interface{}: 164 | for _, v := range at { 165 | if elem, ok := v.(string); ok && elem == bt { 166 | return true 167 | } 168 | } 169 | return false 170 | case []string: 171 | for _, v := range at { 172 | if v == bt { 173 | return true 174 | } 175 | } 176 | return false 177 | case string: 178 | return strings.Contains(a.(string), b.(string)) 179 | default: 180 | return false 181 | } 182 | case float64: 183 | switch at := a.(type) { 184 | case []interface{}: 185 | for _, v := range at { 186 | if elem, ok := v.(float64); ok && elem == bt { 187 | return true 188 | } 189 | } 190 | return false 191 | case []float64: 192 | for _, v := range at { 193 | if v == bt { 194 | return true 195 | } 196 | } 197 | default: 198 | return false 199 | } 200 | default: 201 | return false 202 | } 203 | 204 | return false 205 | } 206 | 207 | // notContains will return true if the b is not contained a. This will also return 208 | // true if a is a slice of different types than b. It will return false if a 209 | // is not a slice or a string. 210 | func notContains(a, b interface{}) bool { 211 | switch bt := b.(type) { 212 | case string: 213 | switch at := a.(type) { 214 | case []interface{}: 215 | for _, v := range at { 216 | if elem, ok := v.(string); ok && elem == bt { 217 | return false 218 | } 219 | } 220 | return true 221 | case []string: 222 | for _, v := range at { 223 | if v == bt { 224 | return false 225 | } 226 | } 227 | return true 228 | case string: 229 | return !strings.Contains(a.(string), b.(string)) 230 | default: 231 | return false 232 | } 233 | case float64: 234 | switch at := a.(type) { 235 | case []interface{}: 236 | for _, v := range at { 237 | if elem, ok := v.(float64); ok && elem == bt { 238 | return false 239 | } 240 | } 241 | return true 242 | case []float64: 243 | for _, v := range at { 244 | if v == bt { 245 | return false 246 | } 247 | } 248 | return true 249 | default: 250 | return false 251 | } 252 | default: 253 | return false 254 | } 255 | } 256 | 257 | // oneOf will return true if b (slice) contains a 258 | func oneOf(a, b interface{}) bool { 259 | m, ok := b.(map[interface{}]struct{}) 260 | if !ok { 261 | return false 262 | } 263 | 264 | _, found := m[a] 265 | if found { 266 | return true 267 | } 268 | 269 | return false 270 | } 271 | 272 | // noneOf will return true if b (slice) does not contain a 273 | func noneOf(a, b interface{}) bool { 274 | m, ok := b.(map[interface{}]struct{}) 275 | if !ok { 276 | return false 277 | } 278 | 279 | _, found := m[a] 280 | if !found { 281 | return true 282 | } 283 | 284 | return false 285 | } 286 | -------------------------------------------------------------------------------- /comparators_test.go: -------------------------------------------------------------------------------- 1 | package grules 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | type testCase struct { 9 | args []interface{} 10 | expected bool 11 | } 12 | 13 | func TestEqual(t *testing.T) { 14 | cases := []testCase{ 15 | testCase{args: []interface{}{"a", "a"}, expected: true}, 16 | testCase{args: []interface{}{"a", "b"}, expected: false}, 17 | testCase{args: []interface{}{float64(1), float64(1)}, expected: true}, 18 | testCase{args: []interface{}{float64(1), float64(0)}, expected: false}, 19 | testCase{args: []interface{}{float64(1.1), float64(1.1)}, expected: true}, 20 | testCase{args: []interface{}{float64(1.1), float64(0.1)}, expected: false}, 21 | } 22 | 23 | for i, c := range cases { 24 | res := equal(c.args[0], c.args[1]) 25 | if res != c.expected { 26 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 27 | } 28 | } 29 | } 30 | 31 | func BenchmarkEqual(b *testing.B) { 32 | for i := 0; i < b.N; i++ { 33 | equal("benchmark", "benchmark") 34 | } 35 | } 36 | 37 | func TestNotEqual(t *testing.T) { 38 | cases := []testCase{ 39 | testCase{args: []interface{}{"a", "a"}, expected: false}, 40 | testCase{args: []interface{}{"a", "b"}, expected: true}, 41 | testCase{args: []interface{}{float64(1), float64(1)}, expected: false}, 42 | testCase{args: []interface{}{float64(1), float64(0)}, expected: true}, 43 | testCase{args: []interface{}{float64(1.1), float64(1.1)}, expected: false}, 44 | testCase{args: []interface{}{float64(1.1), float64(0.1)}, expected: true}, 45 | } 46 | 47 | for i, c := range cases { 48 | res := notEqual(c.args[0], c.args[1]) 49 | if res != c.expected { 50 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 51 | } 52 | } 53 | } 54 | 55 | func BenchmarkNotEqual(b *testing.B) { 56 | for i := 0; i < b.N; i++ { 57 | notEqual("benchmark", "not-benchmark") 58 | } 59 | } 60 | 61 | func TestLessThan(t *testing.T) { 62 | cases := []testCase{ 63 | testCase{args: []interface{}{"a", "a"}, expected: false}, 64 | testCase{args: []interface{}{"a", "b"}, expected: true}, 65 | testCase{args: []interface{}{float64(1), float64(1)}, expected: false}, 66 | testCase{args: []interface{}{float64(0), float64(1)}, expected: true}, 67 | testCase{args: []interface{}{float64(1.1), float64(1.1)}, expected: false}, 68 | testCase{args: []interface{}{float64(1.1), float64(1.2)}, expected: true}, 69 | } 70 | 71 | for i, c := range cases { 72 | res := lessThan(c.args[0], c.args[1]) 73 | if res != c.expected { 74 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 75 | } 76 | } 77 | } 78 | 79 | func BenchmarkLessThan(b *testing.B) { 80 | for i := 0; i < b.N; i++ { 81 | lessThan(0, 1) 82 | } 83 | } 84 | 85 | func TestLessThanEqual(t *testing.T) { 86 | cases := []testCase{ 87 | testCase{args: []interface{}{"a", "a"}, expected: true}, 88 | testCase{args: []interface{}{"a", "b"}, expected: true}, 89 | testCase{args: []interface{}{"c", "b"}, expected: false}, 90 | testCase{args: []interface{}{float64(1), float64(1)}, expected: true}, 91 | testCase{args: []interface{}{float64(0), float64(1)}, expected: true}, 92 | testCase{args: []interface{}{float64(1), float64(0)}, expected: false}, 93 | testCase{args: []interface{}{float64(1.1), float64(1.1)}, expected: true}, 94 | testCase{args: []interface{}{float64(1.1), float64(1.2)}, expected: true}, 95 | testCase{args: []interface{}{float64(1.2), float64(1.1)}, expected: false}, 96 | } 97 | 98 | for i, c := range cases { 99 | res := lessThanEqual(c.args[0], c.args[1]) 100 | if res != c.expected { 101 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 102 | } 103 | } 104 | } 105 | 106 | func BenchmarkLessThanEqual(b *testing.B) { 107 | for i := 0; i < b.N; i++ { 108 | lessThanEqual(0, 0) 109 | } 110 | } 111 | 112 | func TestGreaterThan(t *testing.T) { 113 | cases := []testCase{ 114 | testCase{args: []interface{}{"a", "a"}, expected: false}, 115 | testCase{args: []interface{}{"b", "a"}, expected: true}, 116 | testCase{args: []interface{}{float64(1), float64(1)}, expected: false}, 117 | testCase{args: []interface{}{float64(1), float64(0)}, expected: true}, 118 | testCase{args: []interface{}{float64(1.1), float64(1.1)}, expected: false}, 119 | testCase{args: []interface{}{float64(1.2), float64(1.1)}, expected: true}, 120 | } 121 | 122 | for i, c := range cases { 123 | res := greaterThan(c.args[0], c.args[1]) 124 | if res != c.expected { 125 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 126 | } 127 | } 128 | } 129 | 130 | func BenchmarkGreaterThan(b *testing.B) { 131 | for i := 0; i < b.N; i++ { 132 | greaterThan(1, 0) 133 | } 134 | } 135 | 136 | func TestGreaterThanEqual(t *testing.T) { 137 | cases := []testCase{ 138 | testCase{args: []interface{}{"a", "a"}, expected: true}, 139 | testCase{args: []interface{}{"a", "b"}, expected: false}, 140 | testCase{args: []interface{}{"c", "b"}, expected: true}, 141 | testCase{args: []interface{}{float64(1), float64(1)}, expected: true}, 142 | testCase{args: []interface{}{float64(0), float64(1)}, expected: false}, 143 | testCase{args: []interface{}{float64(1), float64(0)}, expected: true}, 144 | testCase{args: []interface{}{float64(1.1), float64(1.1)}, expected: true}, 145 | testCase{args: []interface{}{float64(1.1), float64(1.2)}, expected: false}, 146 | testCase{args: []interface{}{float64(1.2), float64(1.1)}, expected: true}, 147 | } 148 | 149 | for i, c := range cases { 150 | res := greaterThanEqual(c.args[0], c.args[1]) 151 | if res != c.expected { 152 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 153 | } 154 | } 155 | } 156 | 157 | func BenchmarkGreaterThanEqual(b *testing.B) { 158 | for i := 0; i < b.N; i++ { 159 | greaterThanEqual(0, 0) 160 | } 161 | } 162 | 163 | func TestRegex(t *testing.T) { 164 | cases := []testCase{ 165 | testCase{args: []interface{}{"a", "a"}, expected: true}, 166 | testCase{args: []interface{}{"a", "[ab]"}, expected: true}, 167 | testCase{args: []interface{}{"c", "[ab]"}, expected: false}, 168 | testCase{args: []interface{}{"abc", "c$"}, expected: true}, 169 | testCase{args: []interface{}{float64(1), float64(1)}, expected: false}, 170 | } 171 | 172 | for i, c := range cases { 173 | res := regex(c.args[0], c.args[1]) 174 | if res != c.expected { 175 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 176 | } 177 | } 178 | } 179 | 180 | func BenchmarkRegex(b *testing.B) { 181 | for i := 0; i < b.N; i++ { 182 | regex("a", "a") 183 | } 184 | } 185 | 186 | func BenchmarkRegexPhone(b *testing.B) { 187 | for i := 0; i < b.N; i++ { 188 | regex("+1(555) 555-5555", "\\+\\d\\(\\d+\\) \\d+-\\d+") 189 | } 190 | } 191 | 192 | func TestContains(t *testing.T) { 193 | cases := []testCase{ 194 | testCase{args: []interface{}{[]interface{}{"a", "b"}, "a"}, expected: true}, 195 | testCase{args: []interface{}{[]interface{}{"a", "b"}, "c"}, expected: false}, 196 | testCase{args: []interface{}{[]interface{}{"a", "b"}, float64(1)}, expected: false}, 197 | testCase{args: []interface{}{[]interface{}{float64(1), float64(2)}, float64(1)}, expected: true}, 198 | testCase{args: []interface{}{[]interface{}{float64(1), float64(2)}, float64(3)}, expected: false}, 199 | testCase{args: []interface{}{[]interface{}{float64(1.01), float64(1.02)}, float64(1.01)}, expected: true}, 200 | testCase{args: []interface{}{"abc", "bc"}, expected: true}, 201 | testCase{args: []interface{}{"abc", "de"}, expected: false}, 202 | } 203 | 204 | for i, c := range cases { 205 | res := contains(c.args[0], c.args[1]) 206 | if res != c.expected { 207 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 208 | } 209 | } 210 | } 211 | 212 | func BenchmarkContains(b *testing.B) { 213 | for i := 0; i < b.N; i++ { 214 | contains([]string{"1", "2"}, "1") 215 | } 216 | } 217 | 218 | func BenchmarkStringContains(b *testing.B) { 219 | for i := 0; i < b.N; i++ { 220 | contains("1", "1") 221 | } 222 | } 223 | 224 | func BenchmarkContainsLong50000(b *testing.B) { 225 | var list []interface{} 226 | 227 | // Simulate a list of postal codes 228 | for i := 0; i < 50000; i++ { 229 | list = append(list, fmt.Sprintf("%d", i)) 230 | } 231 | 232 | b.ResetTimer() 233 | for i := 0; i < b.N; i++ { 234 | contains(list, "49999") 235 | } 236 | } 237 | 238 | func TestNotContains(t *testing.T) { 239 | cases := []testCase{ 240 | testCase{args: []interface{}{[]interface{}{}, "a"}, expected: true}, 241 | testCase{args: []interface{}{[]interface{}{"a", "b"}, "a"}, expected: false}, 242 | testCase{args: []interface{}{[]interface{}{"a", "b"}, "c"}, expected: true}, 243 | testCase{args: []interface{}{[]interface{}{"a", "b"}, float64(1)}, expected: true}, 244 | testCase{args: []interface{}{[]interface{}{float64(1), float64(2)}, float64(1)}, expected: false}, 245 | testCase{args: []interface{}{[]interface{}{float64(1), float64(2)}, float64(3)}, expected: true}, 246 | testCase{args: []interface{}{[]interface{}{float64(1.01), float64(1.02)}, float64(1.01)}, expected: false}, 247 | testCase{args: []interface{}{"abc", "bc"}, expected: false}, 248 | testCase{args: []interface{}{"abc", "de"}, expected: true}, 249 | } 250 | 251 | for i, c := range cases { 252 | res := notContains(c.args[0], c.args[1]) 253 | if res != c.expected { 254 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 255 | } 256 | } 257 | } 258 | 259 | func BenchmarkNotContains(b *testing.B) { 260 | for i := 0; i < b.N; i++ { 261 | contains([]string{"1", "2"}, "3") 262 | } 263 | } 264 | 265 | func BenchmarkStringNotContains(b *testing.B) { 266 | for i := 0; i < b.N; i++ { 267 | contains("1", "3") 268 | } 269 | } 270 | 271 | func BenchmarkNotContainsLong50000(b *testing.B) { 272 | var list []interface{} 273 | 274 | // Simulate a list of postal codes 275 | for i := 0; i < 50000; i++ { 276 | list = append(list, fmt.Sprintf("%d", i)) 277 | } 278 | 279 | b.ResetTimer() 280 | for i := 0; i < b.N; i++ { 281 | contains(list, "50000") 282 | } 283 | } 284 | 285 | func BenchmarkOneOf(b *testing.B) { 286 | for i := 0; i < b.N; i++ { 287 | oneOf("2", []string{"1", "2"}) 288 | } 289 | } 290 | 291 | func TestOneOf(t *testing.T) { 292 | cases := []testCase{ 293 | testCase{args: []interface{}{"a", map[interface{}]struct{}{"a": struct{}{}, "b": struct{}{}}}, expected: true}, 294 | testCase{args: []interface{}{"c", map[interface{}]struct{}{"a": struct{}{}, "b": struct{}{}}}, expected: false}, 295 | testCase{args: []interface{}{float64(1), map[interface{}]struct{}{"a": struct{}{}, "b": struct{}{}}}, expected: false}, 296 | testCase{args: []interface{}{float64(1), map[interface{}]struct{}{float64(1): struct{}{}, float64(2): struct{}{}}}, expected: true}, 297 | testCase{args: []interface{}{float64(3), map[interface{}]struct{}{float64(1): struct{}{}, float64(2): struct{}{}}}, expected: false}, 298 | testCase{args: []interface{}{float64(1.01), map[interface{}]struct{}{1.01: struct{}{}, 1.02: struct{}{}}}, expected: true}, 299 | } 300 | for i, c := range cases { 301 | res := oneOf(c.args[0], c.args[1]) 302 | if res != c.expected { 303 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 304 | } 305 | } 306 | } 307 | 308 | func BenchmarkNoneOf(b *testing.B) { 309 | for i := 0; i < b.N; i++ { 310 | noneOf("2", []string{"1", "2"}) 311 | } 312 | } 313 | 314 | func TestNoneOf(t *testing.T) { 315 | cases := []testCase{ 316 | testCase{args: []interface{}{"a", map[interface{}]struct{}{"a": struct{}{}, "b": struct{}{}}}, expected: false}, 317 | testCase{args: []interface{}{"c", map[interface{}]struct{}{"a": struct{}{}, "b": struct{}{}}}, expected: true}, 318 | testCase{args: []interface{}{float64(1), map[interface{}]struct{}{"a": struct{}{}, "b": struct{}{}}}, expected: true}, 319 | testCase{args: []interface{}{float64(1), map[interface{}]struct{}{float64(1): struct{}{}, float64(2): struct{}{}}}, expected: false}, 320 | testCase{args: []interface{}{float64(3), map[interface{}]struct{}{float64(1): struct{}{}, float64(2): struct{}{}}}, expected: true}, 321 | testCase{args: []interface{}{float64(1.01), map[interface{}]struct{}{1.01: struct{}{}, 1.02: struct{}{}}}, expected: false}, 322 | testCase{args: []interface{}{float64(1.03), map[interface{}]struct{}{1.01: struct{}{}, 1.02: struct{}{}}}, expected: true}, 323 | } 324 | 325 | for i, c := range cases { 326 | res := noneOf(c.args[0], c.args[1]) 327 | if res != c.expected { 328 | t.Fatalf("expected case %d to be %v, got %v", i, c.expected, res) 329 | } 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /pluck.go: -------------------------------------------------------------------------------- 1 | package grules 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | // pluck will pull out the value from the props given a path delimited by '.' 8 | func pluck(props map[string]interface{}, path string) interface{} { 9 | parts := strings.Split(path, ".") 10 | for i := 0; i < len(parts)-1; i++ { 11 | var ok bool 12 | props, ok = props[parts[i]].(map[string]interface{}) 13 | if !ok { 14 | return nil 15 | } 16 | } 17 | return props[parts[len(parts)-1]] 18 | } 19 | -------------------------------------------------------------------------------- /pluck_test.go: -------------------------------------------------------------------------------- 1 | package grules 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestPluck(t *testing.T) { 8 | t.Run("key does not exist", func(t *testing.T) { 9 | props := map[string]interface{}{} 10 | val := pluck(props, "email") 11 | if val != nil { 12 | t.Fatal("expected value to be nil") 13 | } 14 | }) 15 | 16 | t.Run("1 level", func(t *testing.T) { 17 | props := map[string]interface{}{ 18 | "email": "test@test.com", 19 | } 20 | val := pluck(props, "email") 21 | if val.(string) != "test@test.com" { 22 | t.Fatal("expected value to match the given") 23 | } 24 | }) 25 | 26 | t.Run("2 levels", func(t *testing.T) { 27 | props := map[string]interface{}{ 28 | "user": map[string]interface{}{ 29 | "name": "Trevor", 30 | }, 31 | } 32 | val := pluck(props, "user.name") 33 | if val.(string) != "Trevor" { 34 | t.Fatal("expected value to match the given") 35 | } 36 | }) 37 | 38 | t.Run("2 levels, key does not exist", func(t *testing.T) { 39 | props := map[string]interface{}{ 40 | "user": map[string]interface{}{ 41 | "name": "Trevor", 42 | }, 43 | } 44 | val := pluck(props, "user.last_name") 45 | if val != nil { 46 | t.Fatal("expected value to be nil") 47 | } 48 | }) 49 | } 50 | 51 | func BenchmarkPluckShallow(b *testing.B) { 52 | props := map[string]interface{}{ 53 | "username": "huttotw", 54 | } 55 | 56 | for i := 0; i < b.N; i++ { 57 | pluck(props, "username") 58 | } 59 | } 60 | 61 | func BenchmarkPluckDeep(b *testing.B) { 62 | props := map[string]interface{}{ 63 | "this": map[string]interface{}{ 64 | "is": map[string]interface{}{ 65 | "a": map[string]interface{}{ 66 | "super": map[string]interface{}{ 67 | "deep": map[string]interface{}{ 68 | "map": map[string]interface{}{ 69 | "hello": "world", 70 | }, 71 | }, 72 | }, 73 | }, 74 | }, 75 | }, 76 | } 77 | 78 | for i := 0; i < b.N; i++ { 79 | pluck(props, "this.is.a.super.deep.map.hello") 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /rule.go: -------------------------------------------------------------------------------- 1 | package grules 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | const ( 8 | // OperatorAnd is what identifies the AND condition in a composite 9 | OperatorAnd = "and" 10 | // OperatorOr is what identifies the OR condition in a composite 11 | OperatorOr = "or" 12 | ) 13 | 14 | // defaultComparators is a map of all the default comparators that 15 | // a new engine should include 16 | var defaultComparators = map[string]Comparator{ 17 | "eq": equal, 18 | "neq": notEqual, 19 | "gt": greaterThan, 20 | "gte": greaterThanEqual, 21 | "lt": lessThan, 22 | "lte": lessThanEqual, 23 | "contains": contains, 24 | "ncontains": notContains, 25 | "oneof": oneOf, 26 | "noneof": noneOf, 27 | "regex": regex, 28 | } 29 | 30 | // Rule is a our smallest unit of measure, each rule will be 31 | // evaluated separately. The comparator is the logical operation to be 32 | // performed, the path is the path into a map, delimited by '.', and 33 | // the value is the value that we expect to match the value at the 34 | // path 35 | type rule struct { 36 | Comparator string `json:"comparator"` 37 | Path string `json:"path"` 38 | Value interface{} `json:"value"` 39 | } 40 | 41 | // MarshalJSON is important because it will put maps back into arrays, we used maps 42 | // to speed up one of 43 | func (r *rule) MarshalJSON() ([]byte, error) { 44 | type unmappedRule struct { 45 | Comparator string `json:"comparator"` 46 | Path string `json:"path"` 47 | Value interface{} `json:"value"` 48 | } 49 | 50 | switch t := r.Value.(type) { 51 | case map[interface{}]struct{}: 52 | var s []interface{} 53 | for k := range t { 54 | s = append(s, k) 55 | } 56 | r.Value = s 57 | } 58 | 59 | umr := unmappedRule{ 60 | Comparator: r.Comparator, 61 | Path: r.Path, 62 | Value: r.Value, 63 | } 64 | 65 | return json.Marshal(umr) 66 | } 67 | 68 | // UnmarshalJSON is important because it will convert arrays in a rule set to a map 69 | // to provide faster lookups 70 | func (r *rule) UnmarshalJSON(data []byte) error { 71 | type mapRule struct { 72 | Comparator string `json:"comparator"` 73 | Path string `json:"path"` 74 | Value interface{} `json:"value"` 75 | } 76 | 77 | var mr mapRule 78 | err := json.Unmarshal(data, &mr) 79 | if err != nil { 80 | return err 81 | } 82 | 83 | switch t := mr.Value.(type) { 84 | case []interface{}: 85 | var m = make(map[interface{}]struct{}) 86 | for _, v := range t { 87 | m[v] = struct{}{} 88 | } 89 | 90 | mr.Value = m 91 | } 92 | 93 | *r = rule{ 94 | Comparator: mr.Comparator, 95 | Path: mr.Path, 96 | Value: mr.Value, 97 | } 98 | 99 | return nil 100 | } 101 | 102 | // Composite is a group of rules that are joined by a logical operator 103 | // AND or OR. If the operator is AND all of the rules must be true, 104 | // if the operator is OR, one of the rules must be true. 105 | type composite struct { 106 | Operator string `json:"operator"` 107 | Rules []rule `json:"rules"` 108 | } 109 | 110 | // Engine is a group of composites. All of the composites must be 111 | // true for the engine's evaluate function to return true. 112 | type Engine struct { 113 | Composites []composite `json:"composites"` 114 | comparators map[string]Comparator 115 | } 116 | 117 | // NewJSONEngine will create a new engine from it's JSON representation 118 | func NewJSONEngine(raw json.RawMessage) (Engine, error) { 119 | var e Engine 120 | err := json.Unmarshal(raw, &e) 121 | if err != nil { 122 | return Engine{}, err 123 | } 124 | e.comparators = defaultComparators 125 | return e, nil 126 | } 127 | 128 | // AddComparator will add a new comparator that can be used in the 129 | // engine's evaluation 130 | func (e Engine) AddComparator(name string, c Comparator) Engine { 131 | e.comparators[name] = c 132 | return e 133 | } 134 | 135 | // Evaluate will ensure all of the composites in the engine are true 136 | func (e Engine) Evaluate(props map[string]interface{}) bool { 137 | for _, c := range e.Composites { 138 | res := c.evaluate(props, e.comparators) 139 | if res == false { 140 | return false 141 | } 142 | } 143 | return true 144 | } 145 | 146 | // Evaluate will ensure all either all of the rules are true, if given 147 | // the AND operator, or that one of the rules is true if given the OR 148 | // operator. 149 | func (c composite) evaluate(props map[string]interface{}, comps map[string]Comparator) bool { 150 | switch c.Operator { 151 | case OperatorAnd: 152 | for _, r := range c.Rules { 153 | res := r.evaluate(props, comps) 154 | if res == false { 155 | return false 156 | } 157 | } 158 | return true 159 | case OperatorOr: 160 | for _, r := range c.Rules { 161 | res := r.evaluate(props, comps) 162 | if res == true { 163 | return true 164 | } 165 | } 166 | return false 167 | } 168 | 169 | return false 170 | } 171 | 172 | // Evaluate will return true if the rule is true, false otherwise 173 | func (r rule) evaluate(props map[string]interface{}, comps map[string]Comparator) bool { 174 | // Make sure we can get a value from the props 175 | val := pluck(props, r.Path) 176 | if val == nil { 177 | return false 178 | } 179 | 180 | comp, ok := comps[r.Comparator] 181 | if !ok { 182 | return false 183 | } 184 | 185 | return comp(val, r.Value) 186 | } 187 | -------------------------------------------------------------------------------- /rule_test.go: -------------------------------------------------------------------------------- 1 | package grules 2 | 3 | import ( 4 | "encoding/json" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func TestRule_evaluate(t *testing.T) { 10 | comparators := map[string]Comparator{ 11 | "eq": equal, 12 | } 13 | props := map[string]interface{}{ 14 | "first_name": "Trevor", 15 | } 16 | t.Run("basic rule", func(t *testing.T) { 17 | r := rule{ 18 | Comparator: "eq", 19 | Path: "first_name", 20 | Value: "Trevor", 21 | } 22 | res := r.evaluate(props, comparators) 23 | if res != true { 24 | t.Fatal("expected rule to be true") 25 | } 26 | }) 27 | 28 | t.Run("unknown path", func(t *testing.T) { 29 | r := rule{ 30 | Comparator: "eq", 31 | Path: "email", 32 | Value: "Trevor", 33 | } 34 | res := r.evaluate(props, comparators) 35 | if res != false { 36 | t.Fatal("expected rule to be false") 37 | } 38 | }) 39 | 40 | t.Run("non comparable types", func(t *testing.T) { 41 | r := rule{ 42 | Comparator: "eq", 43 | Path: "name", 44 | Value: func() {}, 45 | } 46 | res := r.evaluate(props, comparators) 47 | if res != false { 48 | t.Fatal("expected rule to be false") 49 | } 50 | }) 51 | 52 | t.Run("unknown comparator", func(t *testing.T) { 53 | r := rule{ 54 | Comparator: "unknown", 55 | Path: "name", 56 | Value: "Trevor", 57 | } 58 | res := r.evaluate(props, comparators) 59 | if res != false { 60 | t.Fatal("expected rule to be false") 61 | } 62 | }) 63 | } 64 | 65 | func BenchmarkRule_evaluate(b *testing.B) { 66 | r := rule{ 67 | Comparator: "unit", 68 | Path: "name", 69 | Value: "Trevor", 70 | } 71 | props := map[string]interface{}{ 72 | "name": "Trevor", 73 | } 74 | comps := map[string]Comparator{ 75 | "unit": func(a, b interface{}) bool { 76 | return true 77 | }, 78 | } 79 | 80 | b.ResetTimer() 81 | for i := 0; i < b.N; i++ { 82 | r.evaluate(props, comps) 83 | } 84 | } 85 | 86 | func TestRule_MarshalJSON(t *testing.T) { 87 | t.Run("simple engine", func(t *testing.T) { 88 | j := []byte(`{"composites":[{"operator":"and","rules":[{"comparator":"eq","path":"first_name","value":"Trevor"}]}]}`) 89 | e, err := NewJSONEngine(j) 90 | if err != nil { 91 | t.Fatal(err) 92 | } 93 | 94 | b, err := json.Marshal(e) 95 | if err != nil { 96 | t.Fatal(err) 97 | } 98 | 99 | if string(b) != string(j) { 100 | t.Fatal("expected json to be same") 101 | } 102 | }) 103 | 104 | t.Run("list to map", func(t *testing.T) { 105 | j := []byte(`{"composites":[{"operator":"and","rules":[{"comparator":"oneof","path":"first_name","value":["Trevor"]}]}]}`) 106 | e, err := NewJSONEngine(j) 107 | if err != nil { 108 | t.Fatal(err) 109 | } 110 | 111 | b, err := json.Marshal(e) 112 | if err != nil { 113 | t.Fatal(err) 114 | } 115 | 116 | if string(b) != string(j) { 117 | t.Fatal("expected json to be same") 118 | } 119 | }) 120 | } 121 | 122 | func TestComposite_evaluate(t *testing.T) { 123 | comparators := map[string]Comparator{ 124 | "eq": equal, 125 | } 126 | props := map[string]interface{}{ 127 | "name": "Trevor", 128 | "age": float64(23), 129 | } 130 | 131 | t.Run("and", func(t *testing.T) { 132 | c := composite{ 133 | Operator: OperatorAnd, 134 | Rules: []rule{ 135 | rule{ 136 | Comparator: "eq", 137 | Path: "name", 138 | Value: "Trevor", 139 | }, 140 | rule{ 141 | Comparator: "eq", 142 | Path: "age", 143 | Value: float64(23), 144 | }, 145 | }, 146 | } 147 | res := c.evaluate(props, comparators) 148 | if res != true { 149 | t.Fatal("expected composite to be true") 150 | } 151 | }) 152 | 153 | t.Run("or", func(t *testing.T) { 154 | c := composite{ 155 | Operator: OperatorOr, 156 | Rules: []rule{ 157 | rule{ 158 | Comparator: "eq", 159 | Path: "name", 160 | Value: "John", 161 | }, 162 | rule{ 163 | Comparator: "eq", 164 | Path: "age", 165 | Value: float64(23), 166 | }, 167 | }, 168 | } 169 | res := c.evaluate(props, comparators) 170 | if res != true { 171 | t.Fatal("expected composite to be true") 172 | } 173 | }) 174 | 175 | t.Run("unknown operator", func(t *testing.T) { 176 | c := composite{ 177 | Operator: "unknown", 178 | Rules: []rule{ 179 | rule{ 180 | Comparator: "eq", 181 | Path: "name", 182 | Value: "John", 183 | }, 184 | rule{ 185 | Comparator: "eq", 186 | Path: "age", 187 | Value: float64(23), 188 | }, 189 | }, 190 | } 191 | res := c.evaluate(props, comparators) 192 | if res != false { 193 | t.Fatal("expected composite to be true") 194 | } 195 | }) 196 | } 197 | 198 | func BenchmarkComposite_evaluate(b *testing.B) { 199 | c := composite{ 200 | Operator: "or", 201 | Rules: []rule{ 202 | rule{ 203 | Comparator: "unit", 204 | Path: "name", 205 | Value: "Trevor", 206 | }, 207 | }, 208 | } 209 | 210 | props := map[string]interface{}{ 211 | "name": "Trevor", 212 | } 213 | comps := map[string]Comparator{ 214 | "unit": func(a, b interface{}) bool { 215 | return true 216 | }, 217 | } 218 | 219 | b.ResetTimer() 220 | for i := 0; i < b.N; i++ { 221 | c.evaluate(props, comps) 222 | } 223 | } 224 | 225 | func TestAddComparator(t *testing.T) { 226 | comp := func(a, b interface{}) bool { 227 | return false 228 | } 229 | e, err := NewJSONEngine(json.RawMessage(`{}`)) 230 | if err != nil { 231 | t.Fatal(err) 232 | } 233 | e = e.AddComparator("always-false", comp) 234 | if e.comparators["always-false"] == nil { 235 | t.Fatal("expected comparator to be added under key always-false") 236 | } 237 | 238 | e.Composites = []composite{ 239 | composite{ 240 | Operator: OperatorAnd, 241 | Rules: []rule{ 242 | rule{ 243 | Comparator: "always-false", 244 | Path: "user.name", 245 | Value: "Trevor", 246 | }, 247 | }, 248 | }, 249 | } 250 | 251 | props := map[string]interface{}{ 252 | "user": map[string]interface{}{ 253 | "name": "Trevor", 254 | }, 255 | } 256 | 257 | res := e.Evaluate(props) 258 | if res != false { 259 | t.Fatal("expected engine to be false") 260 | } 261 | } 262 | 263 | func TestNewJSONEngine(t *testing.T) { 264 | t.Run("simple engine", func(t *testing.T) { 265 | j := []byte(`{"composites":[{"operator":"and","rules":[{"comparator":"eq","path":"first_name","value":"Trevor"}]}]}`) 266 | e, err := NewJSONEngine(j) 267 | if err != nil { 268 | t.Fatal(err) 269 | } 270 | if len(e.Composites) != 1 { 271 | t.Fatal("expected 1 composite") 272 | } 273 | if len(e.Composites[0].Rules) != 1 { 274 | t.Fatal("expected 1 rule in first composite") 275 | } 276 | }) 277 | 278 | t.Run("list to map", func(t *testing.T) { 279 | j := []byte(`{"composites":[{"operator":"and","rules":[{"comparator":"oneof","path":"first_name","value":["Trevor"]}]}]}`) 280 | e, err := NewJSONEngine(j) 281 | if err != nil { 282 | t.Fatal(err) 283 | } 284 | if len(e.Composites) != 1 { 285 | t.Fatal("expected 1 composite") 286 | } 287 | if len(e.Composites[0].Rules) != 1 { 288 | t.Fatal("expected 1 rule in first composite") 289 | } 290 | 291 | if reflect.TypeOf(e.Composites[0].Rules[0].Value).Kind() != reflect.Map { 292 | t.Fatal("expected list to be transformed to map") 293 | } 294 | }) 295 | } 296 | 297 | func TestEngineEvaluate(t *testing.T) { 298 | t.Run("no composites", func(t *testing.T) { 299 | props := map[string]interface{}{ 300 | "user": map[string]interface{}{ 301 | "email": "test@test.com", 302 | "name": "Trevor", 303 | "id": float64(1234), 304 | }, 305 | } 306 | e, err := NewJSONEngine(json.RawMessage(`{}`)) 307 | if err != nil { 308 | t.Fatal(err) 309 | } 310 | res := e.Evaluate(props) 311 | if res != true { 312 | t.Fatal("expected engine to pass") 313 | } 314 | }) 315 | 316 | t.Run("1 composite, 1 rule", func(t *testing.T) { 317 | props := map[string]interface{}{ 318 | "address": map[string]interface{}{ 319 | "bedroom": map[string]interface{}{ 320 | "furniture": []interface{}{ 321 | "bed", 322 | "tv", 323 | "dresser", 324 | }, 325 | }, 326 | }, 327 | } 328 | e, err := NewJSONEngine(json.RawMessage(`{"composites":[{"operator":"and","rules":[{"comparator":"contains","path":"address.bedroom.furniture","value":"tv"}]}]}`)) 329 | if err != nil { 330 | t.Fatal(err) 331 | } 332 | res := e.Evaluate(props) 333 | if res != true { 334 | t.Fatal("expected engine to pass") 335 | } 336 | }) 337 | 338 | t.Run("2 composites, 1 rule", func(t *testing.T) { 339 | props := map[string]interface{}{ 340 | "user": map[string]interface{}{ 341 | "email": "test@test.com", 342 | "name": "Trevor", 343 | "id": float64(1234), 344 | }, 345 | } 346 | e, err := NewJSONEngine(json.RawMessage(`{"composites":[{"operator":"and","rules":[{"comparator":"eq","path":"user.name","value":"Trevor"},{"comparator":"eq","path":"user.id","value":1234}]},{"operator":"or","rules":[{"comparator":"eq","path":"user.name","value":"Trevor"},{"comparator":"eq","path":"user.id","value":7}]}]}`)) 347 | if err != nil { 348 | t.Fatal(err) 349 | } 350 | res := e.Evaluate(props) 351 | if res != true { 352 | t.Fatal("expected engine to pass") 353 | } 354 | }) 355 | 356 | t.Run("1 composites, 1 rule, strictly typed list", func(t *testing.T) { 357 | props := map[string]interface{}{ 358 | "user": map[string]interface{}{ 359 | "email": "test@test.com", 360 | "name": "Trevor", 361 | "id": float64(1234), 362 | "favorites": []string{ 363 | "golang", 364 | "javascript", 365 | }, 366 | }, 367 | } 368 | e, err := NewJSONEngine(json.RawMessage(`{"composites":[{"operator":"and","rules":[{"comparator":"contains","path":"user.favorites","value":"golang"}]}]}`)) 369 | if err != nil { 370 | t.Fatal(err) 371 | } 372 | res := e.Evaluate(props) 373 | if res != true { 374 | t.Fatal("expected engine to pass") 375 | } 376 | }) 377 | } 378 | 379 | func BenchmarkEngine_Evaluate(b *testing.B) { 380 | e, err := NewJSONEngine(json.RawMessage(`{"composites":[{"operator":"and","rules":[{"comparator":"unit","path":"name","value":"Trevor"}]}]}`)) 381 | if err != nil { 382 | b.Fatal(err) 383 | } 384 | e.AddComparator("unit", func(a, b interface{}) bool { return true }) 385 | props := map[string]interface{}{ 386 | "name": "Trevor", 387 | } 388 | 389 | b.ResetTimer() 390 | for i := 0; i < b.N; i++ { 391 | e.Evaluate(props) 392 | } 393 | } 394 | --------------------------------------------------------------------------------