|
| 1 | +# |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 3 | +# not use this file except in compliance with the License. You may obtain |
| 4 | +# a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 10 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 11 | +# License for the specific language governing permissions and limitations |
| 12 | +# under the License. |
| 13 | + |
| 14 | +import jsonpath_rw |
| 15 | + |
| 16 | + |
| 17 | +class Len(jsonpath_rw.JSONPath): |
| 18 | + """The JSONPath referring to the len of the current object. |
| 19 | +
|
| 20 | + Concrete syntax is '`len`'. |
| 21 | + """ |
| 22 | + |
| 23 | + def find(self, datum): |
| 24 | + datum = jsonpath_rw.DatumInContext.wrap(datum) |
| 25 | + try: |
| 26 | + value = len(datum.value) |
| 27 | + except TypeError: |
| 28 | + return [] |
| 29 | + else: |
| 30 | + return [jsonpath_rw.DatumInContext(value, |
| 31 | + context=None, |
| 32 | + path=Len())] |
| 33 | + |
| 34 | + def __eq__(self, other): |
| 35 | + return isinstance(other, Len) |
| 36 | + |
| 37 | + def __str__(self): |
| 38 | + return '`len`' |
| 39 | + |
| 40 | + def __repr__(self): |
| 41 | + return 'Len()' |
| 42 | + |
| 43 | + |
| 44 | +class GabbiJsonPathParser(jsonpath_rw.parser.JsonPathParser): |
| 45 | + """Custom gabbi LALR-parser for JsonPath""" |
| 46 | + |
| 47 | + def p_jsonpath_named_operator(self, p): |
| 48 | + "jsonpath : NAMED_OPERATOR" |
| 49 | + if p[1] == 'len': |
| 50 | + p[0] = Len() |
| 51 | + else: |
| 52 | + super(GabbiJsonPathParser, self).p_jsonpath_named_operator(p) |
| 53 | + |
| 54 | + |
| 55 | +def parse(path): |
| 56 | + return GabbiJsonPathParser().parse(path) |
0 commit comments