pax_global_header00006660000000000000000000000064136364472650014532gustar00rootroot0000000000000052 comment=32f517c69c77114fc8b806ec2d7817902c6b81e8 python-rison-0.1.3/000077500000000000000000000000001363644726500142045ustar00rootroot00000000000000python-rison-0.1.3/.gitignore000066400000000000000000000022051363644726500161730ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ python-rison-0.1.3/LICENSE000066400000000000000000000020361363644726500152120ustar00rootroot00000000000000Copyright 2019 Beto Dealmeida Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-rison-0.1.3/MANIFEST.in000066400000000000000000000000001363644726500157300ustar00rootroot00000000000000python-rison-0.1.3/README.md000066400000000000000000000320201363644726500154600ustar00rootroot00000000000000# Prison, a Python encoder/decoder for Rison ## Quickstart ```bash $ pip install prison ``` ```python >>> import prison >>> prison.dumps({'foo': 'bar'}) '(foo:bar)' >>> prison.loads('(foo:bar)') {'foo': 'bar'} ``` ## Rison - Compact Data in URIs This page describes *Rison*, a data serialization format optimized for compactness in URIs. Rison is a slight variation of JSON that looks vastly superior after URI encoding. Rison still expresses exactly the same set of data structures as JSON, so data can be translated back and forth without loss or guesswork. You can skip straight to some [examples](#examples), or read on for more background. ### Why another data serialization format? Rison is intended to meet the following goals, in roughly this order: - Comply with [URI specifications](http://gbiv.com/protocols/uri/rfc/rfc3986.html) and usage - Express **nested** data structures - Be **human-readable** - Be **compact** Rison is necessary because the obvious alternatives fail to meet these goals: - URI-encoded XML and JSON are illegible and inefficient. - [HTML Form encoding](http://www.w3.org/TR/html4/interact/forms.html#form-content-type) rules the web but can only represent a flat list of string pairs. - Ian Bicking's [FormEncode](http://formencode.org/) package includes the [variabledecode](http://formencode.org/Validator.html#id16) parser, an interesting convention for form encoding that allows nested lists and dictionaries. However, it becomes inefficient with deeper nesting, and allows no terminal datatypes except strings. Note that these goals are shaped almost entirely by the constraints of URIs, though Rison has turned out to be useful in command-line tools as well. In the *body* of an HTTP request or response, length is less critical and URI encoding can be avoided, so JSON would usually be preferred to Rison. Given that a new syntax is needed, Rison tries to innovate as little as possible: - It uses the same data model as, and a very similar syntax to [JSON](http://json.org/). The Rison grammar is only a slight alteration of the JSON grammar. - It introduces very little additional quoting, since we assume that URI encoding will be applied on top of the Rison encoding. ### Differences from JSON syntax * no whitespace is permitted except inside quoted strings. * almost all character escaping is left to the uri encoder. * single-quotes are used for quoting, but quotes can and should be left off strings when the strings are simple identifiers. * the `e+` exponent format is forbidden, since `+` is not safe in form values and the plain `e` format is equivalent. * the `E`, `E+`, and `E` exponent formats are removed. * object keys should be lexically sorted when encoding. the intent is to improve url cacheability. * uri-safe tokens are used in place of the standard json tokens: |rison token|json token|meaning | |:----------|:---------|:------------| |`'` |`"` |string quote | |`!` |`\` |string escape| |`(...)` |`{...}` |object | |`!(...)` |`[...]` |array | * the JSON literals that look like identifiers (`true`, `false` and `null`) are represented as `!` sequences: |rison token|json token| |:----------|:---------| |`!t` |`true` | |`!f` |`false` | |`!n` |`null` | The `!` character plays two similar but different roles, as an escape character within strings, and as a marker for special values. This may be confusing. Notice that services can distinguish Rison-encoded strings from JSON-encoded strings by checking the first character. Rison structures start with `(` or `!(`. JSON structures start with `[` or `{`. This means that a service which expects a JSON encoded object or array can accept Rison-encoded objects without loss of compatibility. ### Interaction with URI %-encoding Rison syntax is designed to produce strings that be legible after being [form-encoded](http://www.w3.org/TR/html4/interact/forms.html#form-content-type) for the [query](http://gbiv.com/protocols/uri/rfc/rfc3986.html#query) section of a URI. None of the characters in the Rison syntax need to be URI encoded in that context, though the data itself may require URI encoding. Rison tries to be orthogonal to the %-encoding process - it just defines a string format that should survive %-encoding with very little bloat. Rison quoting is only applied when necessary to quote characters that might otherwise be interpreted as special syntax. Note that most URI encoding libraries are very conservative, percent-encoding many characters that are legal according to [RFC 3986](http://gbiv.com/protocols/uri/rfc/rfc3986.html). For example, Javascript's builtin `encodeURIComponent()` function will still make Rison strings difficult to read. The rison.js library includes a more tolerant URI encoder. Rison uses its own quoting for strings, using the single quote (**`'`**) as a string delimiter and the exclamation point (**`!`**) as the string escape character. Both of these characters are legal in uris. Rison quoting is largely inspired by Unix shell command line parsing. All Unicode characters other than **`'`** and **`!`** are legal inside quoted strings. This includes newlines and control characters. Quoting all such characters is left to the %-encoding process. ### Interaction with IRIs This still needs to be addressed. Advice from an IRI expert would be very welcome. Particular attention should be paid to Unicode characters that may be interpreted as Rison syntax characters. The *idchars* set is hard to define well. The goal is to include foreign language alphanumeric characters and some punctuation that is common in identifiers (`_`, `-`, `.`, `/`, and others). However, whitespace and most punctuation characters should require quoting. ### Emailing URIs Most text emailers are conservative about what they turn into a hyperlink, and they will assume that characters like `(` mean the end of the URI. This results in broken, truncated links. This is actually a problem with URI encoding rather than with Rison, but it comes up a lot in practice. You could use Rison with a more aggressive URI encoder to generate emailable URIs. You can also wrap your emailed URIs in angle brackets: `` which some mail readers have better luck with. ### Further Rationale **Passing data in URIs** is necessary in many situations. Many web services rely on the HTTP GET method, which can take advantage of an extensive deployed caching infrastructure. Browsers also have different capabilities for GET, including the crucial ability to make cross-site requests. It is also very convenient to store the state of a small browser application in the URI. **Human readability** makes everything go faster. Primarily this means avoiding URI encoding whenever possible. This requires careful choice of characters for the syntax, and a tolerant URI encoder that only encodes characters when absolutely necessary. **Compactness** is important because of implementation limits on URI length. Internet Explorer is once again the weakest link at 2K. One could certainly invent a more compact representation by dropping the human-readable constraint and using a compression algorithm. ### Variations There are several variations on Rison which are useful or at least thought-provoking. #### O-Rison When you know the parameter being encoded will always be an object, always wrapping it in a containing `()` is unnecessary and hard to explain. Until you've dealt with nested structures, the need for parentheses is hard to explain. In this case you may wish to declare that the argument is encoded in *O-Rison*, which can be translated to Rison by wrapping it in parentheses. Here's a URI with a single query argument which is a nested structure: `http://example.com/service?query=(q:'*',start:10,count:10)` This is more legible if you specify that the argument is O-Rison instead of Rison, and leave the containing `()` as implied: `http://example.com/service?query=q:'*',start:10,count:10` This seems to be useful in enough situations that it is worth defining the term *O-Rison*. #### A-Rison Similarly, sometimes you know the value will always be an array. Instead of specifying a Rison argument: `.../?items=!(item1,item2,item3)` you can specify the far more legible A-Rison argument: `.../?items=item1,item2,item3` #### Accepting other delimiters Notice that O-Rison looks almost like a drop-in replacement for [URL form encoding](http://www.w3.org/TR/html4/interact/forms.html#form-content-type), with two substitutions: - `:` for `=` - `,` for `&` We could expand the Rison parser to treat all of `,`, `&`, and `;` as valid item separators and both `:` and `=` as key-value separators. In this case the vast majority of URI queries would form a flat subset of O-Rison. The exceptions are services that depend on ordering of query parameters or allow duplicate parameter names. This extension doesn't change the parsing of standard Rison strings because `&`, `=`, and `;` are already illegal in Rison identifiers. ### Examples These examples compare Rison and JSON representations of identical values. | Rison | JSON | URI-encoded Rison | URI-encoded JSON | Roundtrip test | Compression | | --- | --- | --- | --- | --- | --- | | `(a:0,b:1)` | `{"a": 0, "b": 1}` | `(a:0,b:1)` | `%7B%22a%22:+0,+%22b%22:+1%7D` | ok | 67.86% | | `(a:0,b:foo,c:'23skidoo')` | `{"a": 0, "b": "foo", "c": "23skidoo"}` | `(a:0,b:foo,c:'23skidoo')` | `%7B%22a%22:+0,+%22b%22:+%22foo%22,+%22c%22:+%2223skidoo%22%7D` | ok | 60.66% | | `!t` | `true` | `!t` | `true` | ok | 50.00% | | `1.5` | `1.5` | `1.5` | `1.5` | ok | 0.00% | | `-3` | `-3` | `-3` | `-3` | ok | 0.00% | | `1e30` | `1e+30` | `1e30` | `1e%2B30` | ok | 42.86% | | `1e-30` | `1e-30` | `1e-30` | `1e-30` | ok | 0.00% | | `a` | `"a"` | `a` | `%22a%22` | ok | 85.71% | | `'0a'` | `"0a"` | `'0a'` | `%220a%22` | ok | 50.00% | | `'abc def'` | `"abc def"` | `%27abc+def%27` | `%22abc+def%22` | ok | 0.00% | | `(a:0)` | `{"a": 0}` | `(a:0)` | `%7B%22a%22:+0%7D` | ok | 68.75% | | `(id:!n,type:/common/document)` | `{"id": null, "type": "/common/document"}` | `(id:!n,type:/common/document)` | `%7B%22id%22:+null,+%22type%22:+%22/common/document%22%7D` | ok | 48.21% | | `!(!t,!f,!n,'')` | `[true, false, null, ""]` | `!(!t,!f,!n,'')` | `%5Btrue,+false,+null,+%22%22%5D` | ok | 54.84% | | `'-h'` | `"-h"` | `'-h'` | `%22-h%22` | ok | 50.00% | | `a-z` | `"a-z"` | `a-z` | `%22a-z%22` | ok | 66.67% | | `'wow!!'` | `"wow!"` | `'wow!!'` | `%22wow%21%22` | ok | 41.67% | | `domain.com` | `"domain.com"` | `domain.com` | `%22domain.com%22` | ok | 37.50% | | `'user@domain.com'` | `"user@domain.com"` | `'user@domain.com'` | `%22user@domain.com%22` | ok | 19.05% | | `'US $10'` | `"US $10"` | `%27US+$10%27` | `%22US+$10%22` | ok | 0.00% | | `'can!'t'` | `"can't"` | `'can!'t'` | `%22can%27t%22` | ok | 38.46% | | `'Control-F: '` | `"Control-F: \u0006"` | `%27Control-F:+%06%27` | `%22Control-F:+%5Cu0006%22` | ok | 20.00% | | `'Unicode: ௫'` | `"Unicode: \u0beb"` | `%27Unicode:+%E0%AF%AB%27` | `%22Unicode:+%5Cu0beb%22` | ok | -4.35% | The compression ratio column shows (1 - encoded_rison_size / encoded_json_size). On a log of Freebase mqlread service URIs, the queries were from 35% to 45% smaller when encoded with Rison. URI encoding is done with a custom URI encoder which is less aggressive than Javascript's built-in `encodeURIComponent()`. ### Grammar Modified from the [json.org](https://web.archive.org/web/20130910064110/http://json.org/) grammar. - _object_ - `()` - `(` _members_ `)` - _members_ - _pair_ - _pair_ `,` _members_ - _pair_ - _key_ `:` _value_ - _array_ - `!()` - `!(` _elements_ `)` - _elements_ - _value_ - _value_ `,` _elements_ - _key_ - _id_ - _string_ - _value_ - _id_ - _string_ - _number_ - _object_ - _array_ - `!t` - `!f` - `!n`
    ──────────── - _id_ - _idstart_ - _idstart_ _idchars_ - _idchars_ - _idchar_ - _idchar_ _idchars_ - _idchar_ - any alphanumeric ASCII character - any ASCII character from the set `-` `_` `.` `/` `~` - any non-ASCII Unicode character - _idstart_ - any _idchar_ not in `-`, _digit_
    ──────────── - _string_ - `''` - `'` _strchars_ `'` - _strchars_ - _strchar_ - _strchar_ _strchars_ - _strchar_ - any Unicode character except ASCII `'` and `!` - `!!` - `!'`
    ──────────── - _number_ - _int_ - _int_ _frac_ - _int_ _exp_ - _int_ _frac_ _exp_ - _int_ - _digit_ - _digit1-9_ _digits_ - `-` digit - `-` digit1-9 digits - _frac_ - `.` _digits_ - _exp_ - _e_ _digits_ - _digits_ - _digit_ - _digit_ _digits_ - _e_ - `e` - `e-` ## History Rison original website is now dead. You can find an archive [here](https://web.archive.org/web/20130910064110/http://www.mjtemplate.org/examples/rison.html). Prison was forked from https://github.com/pifantastic/python-rison and updated for Python 3 compatibility. It was named "prison" because the original "rison" package entry still exists in PyPI, although without a downloadable link. python-rison-0.1.3/prison/000077500000000000000000000000001363644726500155165ustar00rootroot00000000000000python-rison-0.1.3/prison/__init__.py000066400000000000000000000001241363644726500176240ustar00rootroot00000000000000from .decoder import loads from .encoder import dumps __all__ = ['loads', 'dumps'] python-rison-0.1.3/prison/__version__.py000066400000000000000000000000261363644726500203470ustar00rootroot00000000000000__version__ = '0.1.3' python-rison-0.1.3/prison/constants.py000066400000000000000000000011301363644726500200770ustar00rootroot00000000000000import re WHITESPACE = '' IDCHAR_PUNCTUATION = '_-./~' NOT_IDCHAR = ''.join([c for c in (chr(i) for i in range(127)) if not (c.isalnum() or c in IDCHAR_PUNCTUATION)]) # Additionally, we need to distinguish ids and numbers by first char. NOT_IDSTART = '-0123456789' # Regexp string matching a valid id. IDRX = ('[^' + NOT_IDSTART + NOT_IDCHAR + '][^' + NOT_IDCHAR + ']*') # Regexp to check for valid rison ids. ID_OK_RE = re.compile('^' + IDRX + '$', re.M) # Regexp to find the end of an id when parsing. NEXT_ID_RE = re.compile(IDRX, re.M) python-rison-0.1.3/prison/decoder.py000066400000000000000000000125361363644726500175040ustar00rootroot00000000000000# encoding: utf-8 import re from .constants import NEXT_ID_RE, WHITESPACE class ParserException(Exception): pass class Parser(object): def __init__(self): self.string = None self.index = 0 """ This parser supports RISON, RISON-A and RISON-O. """ def parse(self, string, format=str): if string == "(": raise ParserException("unmatched '('") if format in [list, 'A']: self.string = "!({0})".format(string) elif format in [dict, 'O']: self.string = "({0})".format(string) elif format is str: self.string = string else: raise ValueError("""Parse format should be one of str, list, dict, 'A' (alias for list), '0' (alias for dict).""") self.index = 0 value = self.read_value() if self.next(): raise ParserException("unable to parse rison string %r" % (string,)) return value def read_value(self): c = self.next() if c == '!': return self.parse_bang() if c == '(': return self.parse_open_paren() if c == "'": return self.parse_single_quote() if c in '-0123456789': return self.parse_number() # fell through table, parse as an id s = self.string i = self.index-1 m = NEXT_ID_RE.match(s, i) if m: _id = m.group(0) self.index = i + len(_id) return _id if c: raise ParserException("invalid character: '" + c + "'") raise ParserException("empty expression") def parse_array(self): ar = [] while 1: c = self.next() if c == ')': return ar if c is None: raise ParserException("unmatched '!('") if len(ar): if c != ',': raise ParserException("missing ','") elif c == ',': raise ParserException("extra ','") else: self.index -= 1 n = self.read_value() ar.append(n) def parse_bang(self): s = self.string c = s[self.index] self.index += 1 if c is None: raise ParserException('"!" at end of input') if c not in self.bangs: raise ParserException('unknown literal: "!' + c + '"') x = self.bangs[c] if callable(x): return x(self) return x def parse_open_paren(self): count = 0 o = {} while 1: c = self.next() if c == ')': return o if count: if c != ',': raise ParserException("missing ','") elif c == ',': raise ParserException("extra ','") else: self.index -= 1 k = self.read_value() if self.next() != ':': raise ParserException("missing ':'") v = self.read_value() o[k] = v count += 1 def parse_single_quote(self): s = self.string i = self.index start = i segments = [] while 1: if i >= len(s): raise ParserException('unmatched "\'"') c = s[i] i += 1 if c == "'": break if c == '!': if start < i-1: segments.append(s[start:i-1]) c = s[i] i += 1 if c in "!'": segments.append(c) else: raise ParserException('invalid string escape: "!'+c+'"') start = i if start < i-1: segments.append(s[start:i-1]) self.index = i return ''.join(segments) # Also any number start (digit or '-') def parse_number(self): s = self.string i = self.index start = i-1 state = 'int' permitted_signs = '-' transitions = { 'int+.': 'frac', 'int+e': 'exp', 'frac+e': 'exp' } while 1: if i >= len(s): i += 1 break c = s[i] i += 1 if '0' <= c <= '9': continue if permitted_signs.find(c) >= 0: permitted_signs = '' continue state = transitions.get(state + '+' + c.lower(), None) if state is None: break if state == 'exp': permitted_signs = '-' self.index = i - 1 s = s[start:self.index] if s == '-': raise ParserException("invalid number") if re.search('[.e]', s): return float(s) return int(s) # return the next non-whitespace character, or undefined def next(self): s = self.string i = self.index while 1: if i == len(s): return None c = s[i] i += 1 if c not in WHITESPACE: break self.index = i return c bangs = { 't': True, 'f': False, 'n': None, '(': parse_array } def loads(s, format=str): return Parser().parse(s, format=format) python-rison-0.1.3/prison/encoder.py000066400000000000000000000053631363644726500175160ustar00rootroot00000000000000import re from six import string_types from .utils import quote from .constants import ID_OK_RE class Encoder(object): def __init__(self): pass @staticmethod def encoder(v): if isinstance(v, list): return Encoder.list elif isinstance(v, string_types): return Encoder.string elif isinstance(v, bool): return Encoder.bool elif isinstance(v, (float, int)): return Encoder.number elif isinstance(v, type(None)): return Encoder.none elif isinstance(v, dict): return Encoder.dict else: raise AssertionError('Unable to encode type: {0}'.format(type(v))) @staticmethod def encode(v): encoder = Encoder.encoder(v) return encoder(v) @staticmethod def list(x): a = ['!('] b = None for i in range(len(x)): v = x[i] f = Encoder.encoder(v) if f: v = f(v) if isinstance(v, string_types): if b: a.append(',') a.append(v) b = True a.append(')') return ''.join(a) @staticmethod def number(v): return str(v).replace('+', '') @staticmethod def none(_): return '!n' @staticmethod def bool(v): return '!t' if v else '!f' @staticmethod def string(v): if v == '': return "''" if ID_OK_RE.match(v): return v def replace(match): if match.group(0) in ["'", '!']: return '!' + match.group(0) return match.group(0) v = re.sub(r'([\'!])', replace, v) return "'" + v + "'" @staticmethod def dict(x): a = ['('] b = None ks = sorted(x.keys()) for i in ks: v = x[i] f = Encoder.encoder(v) if f: v = f(v) if isinstance(v, string_types): if b: a.append(',') a.append(Encoder.string(i)) a.append(':') a.append(v) b = True a.append(')') return ''.join(a) def encode_array(v): if not isinstance(v, list): raise AssertionError('encode_array expects a list argument') r = dumps(v) return r[2, len(r)-1] def encode_object(v): if not isinstance(v, dict) or v is None or isinstance(v, list): raise AssertionError('encode_object expects an dict argument') r = dumps(v) return r[1, len(r)-1] def encode_uri(v): return quote(dumps(v)) def dumps(string): return Encoder.encode(string) python-rison-0.1.3/prison/utils.py000066400000000000000000000006121363644726500172270ustar00rootroot00000000000000import re import urllib RE_QUOTE = re.compile('^[-A-Za-z0-9~!*()_.\',:@$/]*$') def quote(x): if RE_QUOTE.match(x): return x return urllib.quote(x.encode('utf-8'))\ .replace('%2C', ',', 'g')\ .replace('%3A', ':', 'g')\ .replace('%40', '@', 'g')\ .replace('%24', '$', 'g')\ .replace('%2F', '/', 'g')\ .replace('%20', '+', 'g') python-rison-0.1.3/setup.cfg000066400000000000000000000000001363644726500160130ustar00rootroot00000000000000python-rison-0.1.3/setup.py000066400000000000000000000055321363644726500157230ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package metadata. NAME = 'prison' DESCRIPTION = 'Rison encoder/decoder' URL = 'https://github.com/betodealmeida/python-rison' EMAIL = 'beto@dealmeida.net' AUTHOR = 'Beto Dealmeida' REQUIRED = [ 'six', ] development_extras = [ 'nose', 'pipreqs', 'twine', ] here = os.path.abspath(os.path.dirname(__file__)) long_description = '' # Load the package's __version__.py module as a dictionary. about = {} with open(os.path.join(here, NAME, '__version__.py')) as f: exec(f.read(), about) class UploadCommand(Command): """Support setup.py upload.""" description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): """Prints things in bold.""" print('\033[1m{0}\033[0m'.format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Removing previous builds…') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution…') os.system( '{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) self.status('Uploading the package to PyPi via Twine…') os.system('twine upload dist/*') sys.exit() # Where the magic happens: setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, author=AUTHOR, author_email=EMAIL, url=URL, packages=find_packages(exclude=('tests',)), # If your package is a single module, use this instead of 'packages': # py_modules=['mypackage'], entry_points={}, install_requires=REQUIRED, extras_require={ 'dev': development_extras, }, include_package_data=True, license='MIT', classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], # $ setup.py publish support. cmdclass={ 'upload': UploadCommand, }, ) python-rison-0.1.3/tests/000077500000000000000000000000001363644726500153465ustar00rootroot00000000000000python-rison-0.1.3/tests/__init__.py000066400000000000000000000000001363644726500174450ustar00rootroot00000000000000python-rison-0.1.3/tests/context.py000066400000000000000000000001741363644726500174060ustar00rootroot00000000000000import os import sys sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))) import prison python-rison-0.1.3/tests/test_decoder.py000066400000000000000000000043311363644726500203650ustar00rootroot00000000000000import unittest try: import prison except ImportError: from .context import prison class TestDecoder(unittest.TestCase): def test_dict(self): self.assertEqual(prison.loads('()'), {}) self.assertEqual(prison.loads('(a:0,b:1)'), { 'a': 0, 'b': 1 }) self.assertEqual(prison.loads("(a:0,b:foo,c:'23skidoo')"), { 'a': 0, 'c': '23skidoo', 'b': 'foo' }) self.assertEqual(prison.loads('(id:!n,type:/common/document)'), { 'type': '/common/document', 'id': None }) self.assertEqual(prison.loads("(a:0)"), { 'a': 0 }) def test_bool(self): self.assertEqual(prison.loads('!t'), True) self.assertEqual(prison.loads('!f'), False) def test_invalid(self): with self.assertRaises(prison.decoder.ParserException): prison.loads('(') def test_none(self): self.assertEqual(prison.loads('!n'), None) def test_list(self): self.assertEqual(prison.loads('!(1,2,3)'), [1, 2, 3]) self.assertEqual(prison.loads('!()'), []) self.assertEqual(prison.loads("!(!t,!f,!n,'')"), [True, False, None, '']) def test_number(self): self.assertEqual(prison.loads('0'), 0) self.assertEqual(prison.loads('1.5'), 1.5) self.assertEqual(prison.loads('-3'), -3) self.assertEqual(prison.loads('1e30'), 1e+30) self.assertEqual(prison.loads('1e-30'), 1.0000000000000001e-30) def test_string(self): self.assertEqual(prison.loads("''"), '') self.assertEqual(prison.loads('G.'), 'G.') self.assertEqual(prison.loads('a'), 'a') self.assertEqual(prison.loads("'0a'"), '0a') self.assertEqual(prison.loads("'abc def'"), 'abc def') self.assertEqual(prison.loads("'-h'"), '-h') self.assertEqual(prison.loads('a-z'), 'a-z') self.assertEqual(prison.loads("'wow!!'"), 'wow!') self.assertEqual(prison.loads('domain.com'), 'domain.com') self.assertEqual(prison.loads("'user@domain.com'"), 'user@domain.com') self.assertEqual(prison.loads("'US $10'"), 'US $10') self.assertEqual(prison.loads("'can!'t'"), "can't") python-rison-0.1.3/tests/test_encoder.py000066400000000000000000000041371363644726500204030ustar00rootroot00000000000000import unittest try: import prison except ImportError: from .context import prison class TestEncoder(unittest.TestCase): def test_dict(self): self.assertEqual('()', prison.dumps({})) self.assertEqual('(a:0,b:1)', prison.dumps({ 'a': 0, 'b': 1 })) self.assertEqual("(a:0,b:foo,c:'23skidoo')", prison.dumps({ 'a': 0, 'c': '23skidoo', 'b': 'foo' })) self.assertEqual('(id:!n,type:/common/document)', prison.dumps({ 'type': '/common/document', 'id': None })) self.assertEqual("(a:0)", prison.dumps({ 'a': 0 })) def test_bool(self): self.assertEqual('!t', prison.dumps(True)) self.assertEqual('!f', prison.dumps(False)) def test_none(self): self.assertEqual('!n', prison.dumps(None)) def test_list(self): self.assertEqual('!(1,2,3)', prison.dumps([1, 2, 3])) self.assertEqual('!()', prison.dumps([])) self.assertEqual("!(!t,!f,!n,'')", prison.dumps([True, False, None, ''])) def test_number(self): self.assertEqual('0', prison.dumps(0)) self.assertEqual('1.5', prison.dumps(1.5)) self.assertEqual('-3', prison.dumps(-3)) self.assertEqual('1e30', prison.dumps(1e+30)) self.assertEqual('1e-30', prison.dumps(1.0000000000000001e-30)) def test_string(self): self.assertEqual("''", prison.dumps('')) self.assertEqual('G.', prison.dumps('G.')) self.assertEqual('a', prison.dumps('a')) self.assertEqual("'0a'", prison.dumps('0a')) self.assertEqual("'abc def'", prison.dumps('abc def')) self.assertEqual("'-h'", prison.dumps('-h')) self.assertEqual('a-z', prison.dumps('a-z')) self.assertEqual("'wow!!'", prison.dumps('wow!')) self.assertEqual('domain.com', prison.dumps('domain.com')) self.assertEqual("'user@domain.com'", prison.dumps('user@domain.com')) self.assertEqual("'US $10'", prison.dumps('US $10')) self.assertEqual("'can!'t'", prison.dumps("can't"))