├── LICENSE ├── README.md ├── rule.go ├── rule_test.go ├── ruler.go └── ruler_test.go /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 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-ruler 2 | 3 | json-y object testing in go 4 | 5 | ## Installation 6 | 7 | ``` 8 | go get github.com/hopkinsth/go-ruler 9 | ``` 10 | 11 | ## Introduction 12 | 13 | go-ruler is an implementaion of [ruler](https://github.com/RedVentures/ruler) in go, partly as an experiment, eventually as an optimization strategy. go-ruler supports programmatically constructing rules in a way similar to js-ruler and can also process rules stored in arrays of JSON objects with this structure: 14 | 15 | ```json 16 | { 17 | "comparator": "eq", 18 | "path": "library.name", 19 | "value": "go-ruler" 20 | } 21 | ``` 22 | 23 | Each of those objects (or 'filters') describes a condition for a property on some JSON object or json-object-esque structure. (In this go implementation, we're using `map[string]interface{}`.) 24 | 25 | ## Example 26 | 27 | ```go 28 | package main 29 | 30 | import "github.com/hopkinsth/go-ruler" 31 | import "fmt" 32 | 33 | func main() { 34 | rules := []byte(`[ 35 | {"comparator": "eq", "path": "library.name", "value": "go-ruler"}, 36 | {"comparator": "gt", "path": "library.age", "value": 0.5} 37 | ]`) 38 | 39 | // supports loading rules from JSON data 40 | engine, _ := ruler.NewRulerWithJson(rules) 41 | 42 | // can also build rules programmatically 43 | engine = ruler.NewRuler() 44 | engine.Rule("library.name"). 45 | Eq("go-ruler"). 46 | End(). 47 | Rule("library.age"). 48 | Gt(0.5) 49 | 50 | result := engine.Test(map[string]interface{}{ 51 | "library": map[string]interface{}{ 52 | "name": "go-ruler", 53 | "age": 1.24, 54 | }, 55 | }) 56 | 57 | fmt.Println(result == true) 58 | } 59 | ``` 60 | 61 | ## License 62 | Copyright 2015 Thomas Hopkins 63 | 64 | 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: 65 | 66 | http://www.apache.org/licenses/LICENSE-2.0 67 | 68 | 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. -------------------------------------------------------------------------------- /rule.go: -------------------------------------------------------------------------------- 1 | package ruler 2 | 3 | /* 4 | This struct is the main format for rules or conditions in ruler-compatable libraries. 5 | Here's a sample in JSON format: 6 | { 7 | "comparator": "eq", 8 | "path": "person.name", 9 | "value": "James" 10 | } 11 | 12 | Valid comparators are: eq, neq, lt, lte, gt, gte, contains (regex), ncontains (!regex) 13 | 14 | This struct is exported here so that you can include it in your own JSON encoding/decoding, 15 | but go-ruler has a facility to help decode your rules from JSON into its own structs. 16 | */ 17 | type Rule struct { 18 | Comparator string `json:"comparator"` 19 | Path string `json:"path"` 20 | Value interface{} `json:"value"` 21 | } 22 | 23 | /* 24 | A RulerRule combines a single rule and a whole set of rules and is used 25 | when building rules programmatically through Ruler's Rule() function. 26 | It's not meant to be created directly. 27 | */ 28 | type RulerRule struct { 29 | *Ruler 30 | *Rule 31 | } 32 | 33 | // adds an equals condition 34 | func (rf *RulerRule) Eq(value interface{}) *RulerRule { 35 | return rf.compare(eq, value) 36 | } 37 | 38 | // adds a not equals condition 39 | func (rf *RulerRule) Neq(value interface{}) *RulerRule { 40 | return rf.compare(neq, value) 41 | } 42 | 43 | // adds a less than condition 44 | func (rf *RulerRule) Lt(value interface{}) *RulerRule { 45 | return rf.compare(lt, value) 46 | } 47 | 48 | // adds a less than or equal condition 49 | func (rf *RulerRule) Lte(value interface{}) *RulerRule { 50 | return rf.compare(lte, value) 51 | } 52 | 53 | // adds a greater than condition 54 | func (rf *RulerRule) Gt(value interface{}) *RulerRule { 55 | return rf.compare(gt, value) 56 | } 57 | 58 | // adds a greater than or equal to condition 59 | func (rf *RulerRule) Gte(value interface{}) *RulerRule { 60 | return rf.compare(gte, value) 61 | } 62 | 63 | // adds a matches (regex) condition 64 | func (rf *RulerRule) Matches(value interface{}) *RulerRule { 65 | return rf.compare(matches, value) 66 | } 67 | 68 | // adds a not matches condition (ncontains, in the way this thinks of it) 69 | func (rf *RulerRule) NotMatches(value interface{}) *RulerRule { 70 | return rf.compare(ncontains, value) 71 | } 72 | 73 | // Stops chaining for the current rule, allowing you 74 | // to add rules for other properties 75 | func (rf *RulerRule) End() *Ruler { 76 | return rf.Ruler 77 | } 78 | 79 | // comparator will either create a new ruler filter and add its filter 80 | func (rf *RulerRule) compare(comp int, value interface{}) *RulerRule { 81 | var comparator string 82 | switch comp { 83 | case eq: 84 | comparator = "eq" 85 | case neq: 86 | comparator = "neq" 87 | case lt: 88 | comparator = "lt" 89 | case lte: 90 | comparator = "lte" 91 | case gt: 92 | comparator = "gt" 93 | case gte: 94 | comparator = "gte" 95 | case contains: 96 | comparator = "contains" 97 | case matches: 98 | comparator = "matches" 99 | case ncontains: 100 | comparator = "ncontains" 101 | } 102 | 103 | // if this thing has a comparator already, we need to make a new ruler filter 104 | if rf.Comparator != "" { 105 | rf = &RulerRule{ 106 | rf.Ruler, 107 | &Rule{ 108 | comparator, 109 | rf.Path, 110 | value, 111 | }, 112 | } 113 | // attach the new filter to the ruler 114 | rf.Ruler.rules = append(rf.Ruler.rules, rf.Rule) 115 | } else { 116 | //if there is no comparator, we can just set things on the current filter 117 | rf.Comparator = comparator 118 | rf.Value = value 119 | } 120 | 121 | return rf 122 | } 123 | -------------------------------------------------------------------------------- /rule_test.go: -------------------------------------------------------------------------------- 1 | package ruler 2 | 3 | import "testing" 4 | 5 | func TestNewFilterWhenComparatorExists(t *testing.T) { 6 | rule := &Rule{ 7 | Comparator: "eq", 8 | Path: "name", 9 | Value: "Bob", 10 | } 11 | 12 | r := &Ruler{ 13 | rules: []*Rule{rule}, 14 | } 15 | 16 | rf := &RulerRule{ 17 | r, 18 | rule, 19 | } 20 | 21 | res := rf.Gt("sup") 22 | 23 | if res == rf { 24 | t.Error("RulerFilter should return a new struct if there is an existing comparator!") 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ruler.go: -------------------------------------------------------------------------------- 1 | package ruler 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/tj/go-debug" 6 | "reflect" 7 | "regexp" 8 | "strings" 9 | ) 10 | 11 | var ruleDebug = debug.Debug("ruler:rule") 12 | 13 | // we'll use these values 14 | // to avoid passing strings to our 15 | // special comparison func for these comparators 16 | const ( 17 | eq = iota 18 | neq = iota 19 | gt = iota 20 | gte = iota 21 | lt = iota 22 | lte = iota 23 | exists = iota 24 | nexists = iota 25 | regex = iota 26 | matches = iota 27 | contains = iota 28 | ncontains = iota 29 | ) 30 | 31 | type Ruler struct { 32 | rules []*Rule 33 | } 34 | 35 | // creates a new Ruler for you 36 | // optionally accepts a pointer to a slice of filters 37 | // if you have filters that you want to start with 38 | func NewRuler(rules []*Rule) *Ruler { 39 | if rules != nil { 40 | return &Ruler{ 41 | rules, 42 | } 43 | } 44 | 45 | return &Ruler{} 46 | } 47 | 48 | // returns a new ruler with filters parsed from JSON data 49 | // expects JSON as a slice of bytes and will parse your JSON for you! 50 | func NewRulerWithJson(jsonstr []byte) (*Ruler, error) { 51 | var rules []*Rule 52 | 53 | err := json.Unmarshal(jsonstr, &rules) 54 | if err != nil { 55 | return nil, err 56 | } 57 | 58 | return NewRuler(rules), nil 59 | } 60 | 61 | // adds a new rule for the property at `path` 62 | // returns a RulerFilter that you can use to add conditions 63 | // and more filters 64 | func (r *Ruler) Rule(path string) *RulerRule { 65 | rule := &Rule{ 66 | "", 67 | path, 68 | nil, 69 | } 70 | 71 | r.rules = append(r.rules, rule) 72 | 73 | return &RulerRule{ 74 | r, 75 | rule, 76 | } 77 | } 78 | 79 | // tests all the rules (i.e. filters) in your set of rules, 80 | // given a map that looks like a JSON object 81 | // (map[string]interface{}) 82 | func (r *Ruler) Test(o map[string]interface{}) bool { 83 | for _, f := range r.rules { 84 | val := pluck(o, f.Path) 85 | 86 | if val != nil { 87 | // both the actual and expected value must be comparable 88 | a := reflect.TypeOf(val) 89 | e := reflect.TypeOf(f.Value) 90 | 91 | if !a.Comparable() || !e.Comparable() { 92 | return false 93 | } 94 | 95 | if !r.compare(f, val) { 96 | return false 97 | } 98 | } else if val == nil && (f.Comparator == "exists" || f.Comparator == "nexists") { 99 | // either one of these can be done 100 | return r.compare(f, val) 101 | } else { 102 | ruleDebug("did not find property (%s) on map", f.Path) 103 | // if we couldn't find the value on the map 104 | // and the comparator isn't exists/nexists, this fails 105 | return false 106 | } 107 | 108 | } 109 | 110 | return true 111 | } 112 | 113 | // compares real v. actual values 114 | func (r *Ruler) compare(f *Rule, actual interface{}) bool { 115 | ruleDebug("beginning comparison") 116 | expected := f.Value 117 | switch f.Comparator { 118 | case "eq": 119 | return actual == expected 120 | 121 | case "neq": 122 | return actual != expected 123 | 124 | case "gt": 125 | return r.inequality(gt, actual, expected) 126 | 127 | case "gte": 128 | return r.inequality(gte, actual, expected) 129 | 130 | case "lt": 131 | return r.inequality(lt, actual, expected) 132 | 133 | case "lte": 134 | return r.inequality(lte, actual, expected) 135 | 136 | case "exists": 137 | // not sure this makes complete sense 138 | return actual != nil 139 | 140 | case "nexists": 141 | return actual == nil 142 | 143 | case "regex": 144 | fallthrough 145 | case "contains": 146 | fallthrough 147 | case "matches": 148 | return r.regexp(actual, expected) 149 | 150 | case "ncontains": 151 | return !r.regexp(actual, expected) 152 | default: 153 | //should probably return an error or something 154 | //but this is good for now 155 | //if comparator is not implemented, return false 156 | ruleDebug("unknown comparator %s", f.Comparator) 157 | return false 158 | } 159 | } 160 | 161 | // runs equality comparison 162 | // separated in a different function because 163 | // we need to do another type assertion here 164 | // and some other acrobatics 165 | func (r *Ruler) inequality(op int, actual, expected interface{}) bool { 166 | // need some variables for these deals 167 | ruleDebug("entered inequality comparison") 168 | var cmpStr [2]string 169 | var cmpUint [2]uint64 170 | var cmpInt [2]int64 171 | var cmpFloat [2]float64 172 | 173 | for idx, i := range []interface{}{actual, expected} { 174 | switch t := i.(type) { 175 | case uint8: 176 | cmpUint[idx] = uint64(t) 177 | case uint16: 178 | cmpUint[idx] = uint64(t) 179 | case uint32: 180 | cmpUint[idx] = uint64(t) 181 | case uint64: 182 | cmpUint[idx] = t 183 | case uint: 184 | cmpUint[idx] = uint64(t) 185 | case int8: 186 | cmpInt[idx] = int64(t) 187 | case int16: 188 | cmpInt[idx] = int64(t) 189 | case int32: 190 | cmpInt[idx] = int64(t) 191 | case int64: 192 | cmpInt[idx] = t 193 | case int: 194 | cmpInt[idx] = int64(t) 195 | case float32: 196 | cmpFloat[idx] = float64(t) 197 | case float64: 198 | cmpFloat[idx] = t 199 | case string: 200 | cmpStr[idx] = t 201 | default: 202 | ruleDebug("invalid type for inequality comparison") 203 | return false 204 | } 205 | } 206 | 207 | // whichever of these works, we're happy with 208 | // but if you're trying to compare a string to an int, oh well! 209 | switch op { 210 | case gt: 211 | return cmpStr[0] > cmpStr[1] || 212 | cmpUint[0] > cmpUint[1] || 213 | cmpInt[0] > cmpInt[1] || 214 | cmpFloat[0] > cmpFloat[1] 215 | case gte: 216 | return cmpStr[0] >= cmpStr[1] || 217 | cmpUint[0] >= cmpUint[1] || 218 | cmpInt[0] >= cmpInt[1] || 219 | cmpFloat[0] >= cmpFloat[1] 220 | case lt: 221 | return cmpStr[0] < cmpStr[1] || 222 | cmpUint[0] < cmpUint[1] || 223 | cmpInt[0] < cmpInt[1] || 224 | cmpFloat[0] < cmpFloat[1] 225 | case lte: 226 | return cmpStr[0] <= cmpStr[1] || 227 | cmpUint[0] <= cmpUint[1] || 228 | cmpInt[0] <= cmpInt[1] || 229 | cmpFloat[0] <= cmpFloat[1] 230 | } 231 | 232 | return false 233 | } 234 | 235 | func (r *Ruler) regexp(actual, expected interface{}) bool { 236 | ruleDebug("beginning regexp") 237 | // regexps must be strings 238 | var streg string 239 | var ok bool 240 | if streg, ok = expected.(string); !ok { 241 | ruleDebug("expected value not actually a string, bailing") 242 | return false 243 | } 244 | 245 | var astring string 246 | if astring, ok = actual.(string); !ok { 247 | ruleDebug("actual value not actually a string, bailing") 248 | return false 249 | } 250 | 251 | reg, err := regexp.Compile(streg) 252 | if err != nil { 253 | ruleDebug("regexp is bad, bailing") 254 | return false 255 | } 256 | 257 | return reg.MatchString(astring) 258 | } 259 | 260 | // given a map, pull a property from it at some deeply nested depth 261 | // this reimplements (most of) JS `pluck` in go: https://github.com/gjohnson/pluck 262 | func pluck(o map[string]interface{}, path string) interface{} { 263 | // support dots for now ebcause thats all we need 264 | parts := strings.Split(path, ".") 265 | 266 | if len(parts) == 1 && o[parts[0]] != nil { 267 | // if there is only one part, just return that property value 268 | return o[parts[0]] 269 | } else if len(parts) > 1 && o[parts[0]] != nil { 270 | var prev map[string]interface{} 271 | var ok bool 272 | if prev, ok = o[parts[0]].(map[string]interface{}); !ok { 273 | // not an object type! ...or a map, yeah, that. 274 | return nil 275 | } 276 | 277 | for i := 1; i < len(parts)-1; i += 1 { 278 | // we need to check the existence of another 279 | // map[string]interface for every property along the way 280 | cp := parts[i] 281 | 282 | if prev[cp] == nil { 283 | // didn't find the property, it's missing 284 | return nil 285 | } 286 | var ok bool 287 | if prev, ok = prev[cp].(map[string]interface{}); !ok { 288 | return nil 289 | } 290 | } 291 | 292 | if prev[parts[len(parts)-1]] != nil { 293 | return prev[parts[len(parts)-1]] 294 | } else { 295 | return nil 296 | } 297 | } 298 | 299 | return nil 300 | } 301 | -------------------------------------------------------------------------------- /ruler_test.go: -------------------------------------------------------------------------------- 1 | package ruler 2 | 3 | import "testing" 4 | 5 | func TestRules(t *testing.T) { 6 | 7 | cases := []struct { 8 | rules []*Rule 9 | o map[string]interface{} 10 | name string 11 | }{ 12 | { 13 | []*Rule{ 14 | &Rule{ 15 | "eq", 16 | "basic.property", 17 | "foobar", 18 | }, 19 | }, 20 | map[string]interface{}{ 21 | "basic": map[string]interface{}{ 22 | "property": "foobar", 23 | }, 24 | }, 25 | 26 | "testing basic property equality (string)", 27 | }, 28 | { 29 | []*Rule{ 30 | &Rule{ 31 | "eq", 32 | "basic.property", 33 | 12, 34 | }, 35 | }, 36 | map[string]interface{}{ 37 | "basic": map[string]interface{}{ 38 | "property": 12, 39 | }, 40 | }, 41 | "testing basic property equality (int)", 42 | }, 43 | { 44 | []*Rule{ 45 | &Rule{ 46 | "gt", 47 | "basic.property", 48 | 45, 49 | }, 50 | }, 51 | map[string]interface{}{ 52 | "basic": map[string]interface{}{ 53 | "property": 100, 54 | }, 55 | }, 56 | "testing greater than (int)", 57 | }, 58 | { 59 | []*Rule{ 60 | &Rule{ 61 | "gte", 62 | "basic.property", 63 | 100, 64 | }, 65 | }, 66 | map[string]interface{}{ 67 | "basic": map[string]interface{}{ 68 | "property": 100, 69 | }, 70 | }, 71 | "testing greater than or equal to (int)", 72 | }, 73 | { 74 | []*Rule{ 75 | &Rule{ 76 | "lt", 77 | "basic.property", 78 | 45, 79 | }, 80 | }, 81 | map[string]interface{}{ 82 | "basic": map[string]interface{}{ 83 | "property": 10, 84 | }, 85 | }, 86 | "testing less than (int)", 87 | }, 88 | { 89 | []*Rule{ 90 | &Rule{ 91 | "lte", 92 | "basic.property", 93 | 45, 94 | }, 95 | }, 96 | map[string]interface{}{ 97 | "basic": map[string]interface{}{ 98 | "property": 45, 99 | }, 100 | }, 101 | "testing less than or equal to (int)", 102 | }, 103 | 104 | { 105 | []*Rule{ 106 | &Rule{ 107 | "regex", 108 | "basic.property", 109 | "a[0-9]*b", 110 | }, 111 | }, 112 | map[string]interface{}{ 113 | "basic": map[string]interface{}{ 114 | "property": "a9394b", 115 | }, 116 | }, 117 | "testing regexp", 118 | }, 119 | } 120 | 121 | for _, c := range cases { 122 | r := &Ruler{ 123 | rules: c.rules, 124 | } 125 | 126 | if !r.Test(c.o) { 127 | t.Errorf("rule test failed! %s\n rules: %s", 128 | c.name, 129 | c.rules, 130 | ) 131 | } 132 | } 133 | } 134 | 135 | func TestPluck(t *testing.T) { 136 | exps := []struct { 137 | o map[string]interface{} 138 | seeking string 139 | value interface{} 140 | name string 141 | }{ 142 | 143 | { 144 | map[string]interface{}{ 145 | "hey": map[string]interface{}{ 146 | "hello": "bob", 147 | }, 148 | }, 149 | "hey.hello", 150 | "bob", 151 | `test extracting a simple property`, 152 | }, 153 | 154 | { 155 | map[string]interface{}{ 156 | "hey": map[string]interface{}{ 157 | "hello": "bob", 158 | }, 159 | }, 160 | "hey.nope", 161 | nil, 162 | `test getting a nonexistent property 163 | on an existing object`, 164 | }, 165 | { 166 | map[string]interface{}{ 167 | "hey": map[string]interface{}{ 168 | "hello": "bob", 169 | }, 170 | }, 171 | "hey.what.something.very.important", 172 | nil, 173 | `test getting a nonexistent property 174 | for a nonexistent object`, 175 | }, 176 | { 177 | map[string]interface{}{ 178 | "hey": map[string]interface{}{ 179 | "hello": "bob", 180 | }, 181 | }, 182 | "hey.hello.something.very.important", 183 | nil, 184 | `test getting a property on a thing 185 | that isn't or doesn't assert to be a map`, 186 | }, 187 | 188 | { 189 | map[string]interface{}{ 190 | "hey": map[string]interface{}{ 191 | "sup": 1, 192 | }, 193 | }, 194 | "hey.sup", 195 | 1, 196 | `test plucking something that isn't 197 | a string`, 198 | }, 199 | { 200 | map[string]interface{}{}, 201 | "hey.lol", 202 | nil, 203 | `test plucking where the base obj doesn't exist`, 204 | }, 205 | { 206 | map[string]interface{}{ 207 | "test": map[string]interface{}{ 208 | "thing": map[string]interface{}{ 209 | "here": map[string]interface{}{ 210 | "today": map[string]interface{}{ 211 | "is": map[string]interface{}{ 212 | "awesome": map[string]interface{}{ 213 | "with": map[string]interface{}{ 214 | "thestuff": "no dice", 215 | }, 216 | }, 217 | }, 218 | }, 219 | }, 220 | }, 221 | }, 222 | }, 223 | "test.thing.here.today.is.awesome.with.thestuff", 224 | "no dice", 225 | "testing deeply nested property", 226 | }, 227 | } 228 | 229 | for _, e := range exps { 230 | res := pluck(e.o, e.seeking) 231 | if res != e.value { 232 | t.Errorf( 233 | "error with: %s\nfailed to pluck! %s != %s", 234 | e.name, 235 | res, 236 | e.value, 237 | ) 238 | } 239 | } 240 | } 241 | 242 | func BenchmarkPluckShallow(b *testing.B) { 243 | o := map[string]interface{}{ 244 | "hey": map[string]interface{}{ 245 | "there": 4, 246 | }, 247 | } 248 | 249 | for i := 0; i < b.N; i += 1 { 250 | r := pluck(o, "hey.there") 251 | if r != 4 { 252 | b.Errorf("fail bench, val was %s", r) 253 | } 254 | } 255 | } 256 | 257 | func BenchmarkPluckDeep(b *testing.B) { 258 | o := map[string]interface{}{ 259 | "test": map[string]interface{}{ 260 | "thing": map[string]interface{}{ 261 | "here": map[string]interface{}{ 262 | "today": map[string]interface{}{ 263 | "is": map[string]interface{}{ 264 | "awesome": map[string]interface{}{ 265 | "with": map[string]interface{}{ 266 | "thestuff": "no dice", 267 | }, 268 | }, 269 | }, 270 | }, 271 | }, 272 | }, 273 | }, 274 | } 275 | 276 | for i := 0; i < b.N; i += 1 { 277 | r := pluck(o, "test.thing.here.today.is.awesome.with.thestuff") 278 | if r != "no dice" { 279 | b.Errorf("fail bench, val was %s", r) 280 | } 281 | } 282 | } 283 | 284 | func TestNewRulerWithJson(t *testing.T) { 285 | theJson := []byte(`[ 286 | {"comparator": "eq", "path": "name", "value": "Thomas"} 287 | ] 288 | `) 289 | 290 | r, err := NewRulerWithJson(theJson) 291 | if err != nil { 292 | t.Errorf("Error getting new ruler w/json: %s", err) 293 | } 294 | 295 | data := map[string]interface{}{ 296 | "name": "Thomas", 297 | } 298 | 299 | if !r.Test(data) { 300 | t.Error("newRulerWithJson didn't do something properly!") 301 | } 302 | } 303 | 304 | func BenchmarkNewRulerWithJson(b *testing.B) { 305 | theJson := []byte(`[ 306 | {"comparator": "eq", "path": "name", "value": "Thomas"} 307 | ] 308 | `) 309 | data := map[string]interface{}{ 310 | "name": "Thomas", 311 | } 312 | 313 | for i := 0; i < b.N; i += 1 { 314 | r, err := NewRulerWithJson(theJson) 315 | if err != nil { 316 | b.Errorf("Error getting new ruler w/json: %s", err) 317 | } 318 | 319 | if !r.Test(data) { 320 | b.Error("newRulerWithJson didn't do something properly!") 321 | } 322 | } 323 | } 324 | 325 | func BenchmarkNewRulerWithRulesSimple(b *testing.B) { 326 | filters := []*Rule{ 327 | &Rule{ 328 | Comparator: "eq", 329 | Path: "name", 330 | Value: "Bob", 331 | }, 332 | } 333 | 334 | data := map[string]interface{}{ 335 | "name": "Bob", 336 | } 337 | 338 | for i := 0; i < b.N; i += 1 { 339 | r := NewRuler(filters) 340 | 341 | if !r.Test(data) { 342 | b.Error("NewRuler didn't do something properly!") 343 | } 344 | } 345 | } 346 | 347 | func BenchmarkNewRulerWithRulesTen(b *testing.B) { 348 | filters := []*Rule{ 349 | &Rule{ 350 | Comparator: "eq", 351 | Path: "name", 352 | Value: "Bob", 353 | }, 354 | &Rule{ 355 | Comparator: "ncontains", 356 | Path: "name", 357 | Value: "Jones", 358 | }, 359 | &Rule{ 360 | Comparator: "contains", 361 | Path: "location.name", 362 | Value: "Florida", 363 | }, 364 | &Rule{ 365 | Comparator: "gte", 366 | Path: "location.x", 367 | Value: 45.63, 368 | }, 369 | &Rule{ 370 | Comparator: "lte", 371 | Path: "location.y", 372 | Value: 35.10, 373 | }, 374 | &Rule{ 375 | Comparator: "gt", 376 | Path: "location.pop", 377 | Value: 100000, 378 | }, 379 | &Rule{ 380 | Comparator: "lt", 381 | Path: "location.elev", 382 | Value: 1000, 383 | }, 384 | &Rule{ 385 | Comparator: "eq", 386 | Path: "location.extra.fips", 387 | Value: "12-24000", 388 | }, 389 | &Rule{ 390 | Comparator: "eq", 391 | Path: "location.extra.time.zone", 392 | Value: "America/New_York", 393 | }, 394 | &Rule{ 395 | Comparator: "eq", 396 | Path: "location.extra.time.speed.you-made-it-this-far.reward", 397 | Value: "you", 398 | }, 399 | } 400 | 401 | data := map[string]interface{}{ 402 | "name": "Bob", 403 | "location": map[string]interface{}{ 404 | "name": "Fort Lauderdale, Florida", 405 | "x": 93.23, 406 | "y": 22.32, 407 | "pop": 324234234, 408 | "elev": 72, 409 | "extra": map[string]interface{}{ 410 | "fips": "12-24000", 411 | "time": map[string]interface{}{ 412 | "zone": "America/New_York", 413 | "isDst": "maybe", 414 | "speed": map[string]interface{}{ 415 | "you-made-it-this-far": map[string]interface{}{ 416 | "so": "now", 417 | "we": "will", 418 | "reward": "you", 419 | }, 420 | }, 421 | }, 422 | }, 423 | }, 424 | } 425 | 426 | for i := 0; i < b.N; i += 1 { 427 | r := NewRuler(filters) 428 | 429 | if !r.Test(data) { 430 | b.Error("NewRuler didn't do something properly!") 431 | } 432 | } 433 | } 434 | --------------------------------------------------------------------------------