pax_global_header00006660000000000000000000000064136051204270014512gustar00rootroot0000000000000052 comment=8222c622dcd49c2c115ca9d5c583d1d6700e7be7 json-rpc-1.13.0/000077500000000000000000000000001360512042700133275ustar00rootroot00000000000000json-rpc-1.13.0/.circleci/000077500000000000000000000000001360512042700151625ustar00rootroot00000000000000json-rpc-1.13.0/.circleci/config.yml000066400000000000000000000027121360512042700171540ustar00rootroot00000000000000version: 2 workflows: version: 2 test: jobs: - py27 - py34 - py35 - py36 - py37 - py38 - pycodestyle - cov jobs: py36: &test-template docker: - image: circleci/python:3.6 working_directory: ~/repo steps: - checkout - run: name: Install test dependencies command: | python -m venv venv || virtualenv venv venv/bin/pip install tox - run: name: Run tests command: | venv/bin/tox -e $CIRCLE_JOB py27: <<: *test-template docker: - image: circleci/python:2.7 py33: <<: *test-template docker: - image: circleci/python:3.3 py34: <<: *test-template docker: - image: circleci/python:3.4 py35: <<: *test-template docker: - image: circleci/python:3.5 py37: <<: *test-template docker: - image: circleci/python:3.7 py38: <<: *test-template docker: - image: circleci/python:3.8 pycodestyle: <<: *test-template cov: <<: *test-template steps: - checkout - run: name: Install test dependencies command: | python -m venv venv || virtualenv venv venv/bin/pip install tox - run: name: Generate coverage report command: | venv/bin/tox -e $CIRCLE_JOB .tox/cov/bin/codecov --token db4c9cc4-799b-49b0-ab9a-51dde80fb946 json-rpc-1.13.0/.coveragerc000066400000000000000000000003061360512042700154470ustar00rootroot00000000000000[run] omit= jsonrpc/six.py jsonrpc/tests/* source=jsonrpc [report] omit= jsonrpc/six.py jsonrpc/tests/* exclude_lines= raise NotImplementedError() def is_invalid_params_py2 json-rpc-1.13.0/.gitignore000066400000000000000000000001551360512042700153200ustar00rootroot00000000000000*.egg *.egg-info *.py[c|o] .eggs/ .DS_Store .coverage .env .env3 .ropeproject .tox build/ dist/ docs/_build/ json-rpc-1.13.0/AUTHORS000066400000000000000000000021071360512042700143770ustar00rootroot00000000000000Here is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS -- people who have submitted patches, reported bugs, added translations, helped answer newbie questions, and generally made json-rpc that much better: Contributors ------------ Kirill Pavlov (@pavlov99) Jan Willems (@jw) Robby Dermody (@robby-dermody) Mateusz Pawlik (@matee911) Malyshev Artem (@proofit404) Julian Hille (@julianhille) Pavel Evdokimov (@Santinell) Lev Orekhov (@lorehov) Sergey Nikitin (@nikitinsm) Jean-Christophe Bohin (@jcbohin) Arne Brutschy (@arnuschky) Piper Merriam (pipermerriam) Luke Lee (@durden) Mike Purvis (@mikepurvis) Seth Hill (@sethrh) Sergey Magafurov (@smagafurov) Laurent Mazuel (@lmazuel) Igor Melnyk (@liminspace) Ghislain Antony Vaillant (@ghisvail) Chris Jerdonek (@cjerdonek) json-rpc-1.13.0/CODE_OF_CONDUCT.md000066400000000000000000000061711360512042700161330ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [json-rpc@p99.io](mailto:json-rpc@p99.io). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html json-rpc-1.13.0/CONTRIBUTING.md000066400000000000000000000157721360512042700155740ustar00rootroot00000000000000# Contributing to json-rpc :+1::tada: First off all, thanks for taking the time to contribute! :tada::+1: The following is a set of guidelines for contributing to [json-rpc](https://github.com/pavlov99/json-rpc), which is hosted on GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. #### Table Of Contents [Code of Conduct](#code-of-conduct) [I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question) [How Can I Contribute?](#how-can-i-contribute) * [Reporting Bugs](#reporting-bugs) * [Suggesting Enhancements](#suggesting-enhancements) * [Pull Requests](#pull-requests) [Styleguides](#styleguides) * [Git Commit Messages](#git-commit-messages) ## Code of Conduct This project and everyone participating in it is governed by the [json-rpc Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [json-rpc@p99.io](mailto:json-rpc@p99.io). ## I don't want to read this whole thing I just have a question!!! > **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below. We have a message board [Gitter](https://gitter.im/pavlov99/json-rpc) where the community chimes in with helpful advice if you have questions. ## How Can I Contribute? ### Reporting Bugs This section guides you through submitting a bug report for json-rpc. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related reports :mag_right:. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](ISSUE_TEMPLATE.md), the information it asks for helps us resolve issues faster. > **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. #### How Do I Submit A (Good) Bug Report? Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue on that repository and provide the following information by filling in [the template](ISSUE_TEMPLATE.md). Add a label 'bug' to the issue. Explain the problem and include additional details to help maintainers reproduce the problem: * **Use a clear and descriptive title** for the issue to identify the problem. * **Describe the exact steps which reproduce the problem** in as many details as possible. For example, start by explaining how you used json-rpc, e.g. which command exactly you used, which framework if aplicable. When listing steps, **don't just say what you did, but explain how you did it**. * **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). * **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior. * **Explain which behavior you expected to see instead and why.** * **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. * **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below. ### Suggesting Enhancements This section guides you through submitting an enhancement suggestion for json-rpc, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](ISSUE_TEMPLATE.md), including the steps that you imagine you would take if the feature you're requesting existed. #### How Do I Submit A (Good) Enhancement Suggestion? Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue and provide the following information: * **Use a clear and descriptive title** for the issue to identify the suggestion. * **Provide a step-by-step description of the suggested enhancement** in as many details as possible. * **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). * **Describe the current behavior** and **explain which behavior you expected to see instead** and why. * **Include screenshots and animated GIFs** which help you demonstrate the steps. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. ### Pull Requests * Fill in [the required template](PULL_REQUEST_TEMPLATE.md) * Do not include issue numbers in the PR title * Include screenshots and animated GIFs in your pull request whenever possible. * Document your code with [Napoleon style](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/) docstrings. * Add tests and ensure test regression. Pull request would not be accepted if it breaks the build. * End all files with a newline * Squash commits to logical units. If you fix commit "A" with commit "B", squash them into one and open pull request again. * Add you name to the end of [AUTHORS](AUTHORS) list. It approximately follows chronological order. * Make sure you use the same email for your commits. ## Styleguides ### Git Commit Messages * Use the present tense ("Add feature" not "Added feature") * Use the imperative mood ("Move cursor to..." not "Moves cursor to...") * Limit the first line to 72 characters or less * Reference issues and pull requests liberally after the first line * Consider starting the commit message with an applicable emoji: * :art: `:art:` when improving the format/structure of the code * :racehorse: `:racehorse:` when improving performance * :non-potable_water: `:non-potable_water:` when plugging memory leaks * :memo: `:memo:` when writing docs * :bug: `:bug:` when fixing a bug * :fire: `:fire:` when removing code or files * :green_heart: `:green_heart:` when fixing the CI build * :white_check_mark: `:white_check_mark:` when adding tests * :lock: `:lock:` when dealing with security * :shirt: `:shirt:` when removing linter warnings json-rpc-1.13.0/ISSUE_TEMPLATE.md000066400000000000000000000017451360512042700160430ustar00rootroot00000000000000 ### Description [Description of the issue] ### Steps to Reproduce 1. [First Step] 2. [Second Step] 3. [and so on...] **Expected behavior:** [What you expect to happen] **Actual behavior:** [What actually happens] **Reproduces how often:** [What percentage of the time does it reproduce?] ### Versions You can get this information from copy and pasting the output of `python --version` from the command line. Also, please include the OS and what version of the OS you're running. ### Additional Information Any additional information, configuration or data that might be necessary to reproduce the issue. json-rpc-1.13.0/LICENSE.txt000066400000000000000000000021101360512042700151440ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2013-2018 Kirill Pavlov 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. json-rpc-1.13.0/MANIFEST.in000066400000000000000000000001101360512042700150550ustar00rootroot00000000000000include *.py include README.rst include LICENSE.txt include MANIFEST.in json-rpc-1.13.0/Makefile000066400000000000000000000007251360512042700147730ustar00rootroot00000000000000.PHONY: help # target: help - Display callable targets help: @egrep "^# target:" [Mm]akefile .PHONY: clean # target: clean - Display callable targets clean: @rm -rf build dist docs/_build @find . -name \*.py[co] -delete @find . -name *\__pycache__ -delete .PHONY: upload # target: upload - Upload module on PyPI upload: @python setup.py sdist bdist_wheel upload || echo 'Upload already' .PHONY: serve # target: serve - server docs serve: python3 -mhttp.server json-rpc-1.13.0/PULL_REQUEST_TEMPLATE.md000066400000000000000000000021631360512042700171320ustar00rootroot00000000000000### Requirements * Filling out the template is required. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. * All new code requires tests to ensure against regressions. * If pull request breaks tests it would not be merged. ### Description of the Change ### Alternate Designs ### Benefits ### Possible Drawbacks ### Applicable Issues json-rpc-1.13.0/README.rst000066400000000000000000000140161360512042700150200ustar00rootroot00000000000000json-rpc ======== .. image:: https://circleci.com/gh/pavlov99/json-rpc/tree/master.svg?style=svg :target: https://circleci.com/gh/pavlov99/json-rpc/tree/master :alt: Build Status .. image:: https://codecov.io/gh/pavlov99/json-rpc/branch/master/graph/badge.svg :target: https://codecov.io/gh/pavlov99/json-rpc :alt: Coverage Status .. image:: https://readthedocs.org/projects/json-rpc/badge/?version=latest :target: http://json-rpc.readthedocs.io/en/latest/?badge=latest .. image:: https://img.shields.io/pypi/v/json-rpc.svg :target: https://pypi.org/project/json-rpc/ :alt: Latest PyPI version .. image:: https://img.shields.io/pypi/pyversions/json-rpc.svg :target: https://pypi.org/project/json-rpc/ :alt: Supported Python versions .. image:: https://badges.gitter.im/pavlov99/json-rpc.svg :target: https://gitter.im/pavlov99/json-rpc :alt: Gitter .. image:: https://opencollective.com/json-rpc/tiers/backer/badge.svg?label=backer&color=brightgreen :target: https://opencollective.com/json-rpc :alt: Bakers .. image:: https://opencollective.com/json-rpc/tiers/backer/badge.svg?label=sponsor&color=brightgreen :target: https://opencollective.com/json-rpc :alt: Sponsors `JSON-RPC2.0 `_ and `JSON-RPC1.0 `_ transport specification implementation. Supports Python 2.6+, Python 3.3+, PyPy. Has optional Django and Flask support. 200+ tests. Features -------- This implementation does not have any transport functionality realization, only protocol. Any client or server implementation is easy based on current code, but requires transport libraries, such as requests, gevent or zmq, see `examples `_. - Vanilla Python, no dependencies. - 200+ tests for multiple edge cases. - Optional backend support for Django, Flask. - json-rpc 1.1 and 2.0 support. Install ------- .. code-block:: python pip install json-rpc Tests ----- Quickstart ^^^^^^^^^^ This is an essential part of the library as there are a lot of edge cases in JSON-RPC standard. To manage a variety of supported python versions as well as optional backends json-rpc uses `tox`: .. code-block:: bash tox .. TIP:: During local development use your python version with tox runner. For example, if your are using Python 3.6 run `tox -e py36`. It is easier to develop functionality for specific version first and then expands it to all of the supported versions. Continuous integration ^^^^^^^^^^^^^^^^^^^^^^ This project uses `CircleCI `_ for continuous integration. All of the python supported versions are managed via `tox.ini` and `.circleci/config.yml` files. Master branch test status is displayed on the badge in the beginning of this document. Test matrix ^^^^^^^^^^^ json-rpc supports multiple python versions: 2.6+, 3.3+, pypy. This introduces difficulties with testing libraries and optional dependencies management. For example, python before version 3.3 does not support `mock` and there is a limited support for `unittest2`. Every dependency translates into *if-then* blocks in the source code and adds complexity to it. Hence, while cross-python support is a core feature of this library, cross-Django or cross-Flask support is limited. In general, json-rpc uses latest stable release which supports current python version. For example, python 2.6 is compatible with Django 1.6 and not compatible with any future versions. Below is a testing matrix: +--------+-------+-----------+--------+--------+ | Python | mock | unittest | Django | Flask | +========+=======+===========+========+========+ | 2.6 | 2.0.0 | unittest2 | 1.6 | 0.12.2 | +--------+-------+-----------+--------+--------+ | 2.7 | 2.0.0 | | 1.11 | 0.12.2 | +--------+-------+-----------+--------+--------+ | 3.3 | | | 1.11 | 0.12.2 | +--------+-------+-----------+--------+--------+ | 3.4 | | | 1.11 | 0.12.2 | +--------+-------+-----------+--------+--------+ | 3.5 | | | 1.11 | 0.12.2 | +--------+-------+-----------+--------+--------+ | 3.6 | | | 1.11 | 0.12.2 | +--------+-------+-----------+--------+--------+ | pypy | 2.0.0 | | 1.11 | 0.12.2 | +--------+-------+-----------+--------+--------+ | pypy3 | | | 1.11 | 0.12.2 | +--------+-------+-----------+--------+--------+ Quickstart ---------- Server (uses `Werkzeug `_) .. code-block:: python from werkzeug.wrappers import Request, Response from werkzeug.serving import run_simple from jsonrpc import JSONRPCResponseManager, dispatcher @dispatcher.add_method def foobar(**kwargs): return kwargs["foo"] + kwargs["bar"] @Request.application def application(request): # Dispatcher is dictionary {: callable} dispatcher["echo"] = lambda s: s dispatcher["add"] = lambda a, b: a + b response = JSONRPCResponseManager.handle( request.data, dispatcher) return Response(response.json, mimetype='application/json') if __name__ == '__main__': run_simple('localhost', 4000, application) Client (uses `requests `_) .. code-block:: python import requests import json def main(): url = "http://localhost:4000/jsonrpc" # Example echo method payload = { "method": "echo", "params": ["echome!"], "jsonrpc": "2.0", "id": 0, } response = requests.post(url, json=payload).json() assert response["result"] == "echome!" assert response["jsonrpc"] assert response["id"] == 0 if __name__ == "__main__": main() Competitors ----------- There are `several libraries `_ implementing JSON-RPC protocol. List below represents python libraries, none of the supports python3. tinyrpc looks better than others. json-rpc-1.13.0/changelog000066400000000000000000000046701360512042700152100ustar00rootroot000000000000002020-01-06 Kirill Pavlov * FIX: positional arguments support for Django backend 2019-10-17 Kirill Pavlov * ADD: python3.8 support 2019-01-12 Kirill Pavlov * ADD: Ability to override function name with decorator convention in dispatcher * REF: Improve function parameter introspection: use more stable approach for python3, allow both args and kwards parameters check at the same time. * TST: Switch from nose and nose2 to pytest * TST: Switch from Travis CI to CircleCI, test py26-py37 * TST: Switch from coveralls to codecov service * DEL: Remove Flask logging (it broke batch requests) * DEL: Clean Makefile shortcuts, remove unused ones * DOC: Add opencollective badge 2018-08-26 Kirill Pavlov * Add license file to the dist/ 2016-01-31 Kirill Pavlov * Drop support of python 3.2. Pip does not support it, which leads to tests fail 2015-08-07 Kirill Pavlov * Allow custom empty dispatcher parameter for backend-specific api 2015-06-29 Kirill Pavlov * Flask backend support by Lev Orekhov (https://github.com/lorehov) 2015-06-03 Kirill Pavlov * Added support of method prefixes https://github.com/pavlov99/json-rpc/pull/31 2015-05-05 Kirill Pavlov * Add logger to django api client 2014-09-04 Kirill Pavlov * Add custom exception functionality by @julianhille 2014-05-25 Kirill Pavlov * Add python 2.6 support * Update server notification processing * Add functionality to dispatcher, it is possible to init it with class 2013-11-09 Kirill Pavlov * Add JSON-RPC 1.0 support. * Add dispatcher for functions. * Add notification support (separate notification and id=null for JSON-RPC 2.0 request). * Add custom json serializer (based on json) with datetime.Datetime and decimal.Decimal serialization support. * Move JSONRPC* classes to JSONRPC20*, as far as there is JSONRPC10*. * Add dispatcher and JSONRPCManager to jsonrpc/__init__, they are no longer in jsonrpc.jsonrpc module. 2013-10-13 Kirill Pavlov * Add examples of usage. * Init documentation. * Remove six from dependencies. 2013-10-08 Kirill Pavlov * Implement JSON-RPC 2.0 specification. json-rpc-1.13.0/docs/000077500000000000000000000000001360512042700142575ustar00rootroot00000000000000json-rpc-1.13.0/docs/Makefile000066400000000000000000000127111360512042700157210ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/json-rpc.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/json-rpc.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/json-rpc" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/json-rpc" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." json-rpc-1.13.0/docs/_static/000077500000000000000000000000001360512042700157055ustar00rootroot00000000000000json-rpc-1.13.0/docs/_static/README.txt000066400000000000000000000000311360512042700173750ustar00rootroot00000000000000Place static files here. json-rpc-1.13.0/docs/make.bat000066400000000000000000000117541360512042700156740ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\json-rpc.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\json-rpc.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end json-rpc-1.13.0/docs/requirements.txt000066400000000000000000000000351360512042700175410ustar00rootroot00000000000000sphinx>=1.3 sphinx_rtd_theme json-rpc-1.13.0/docs/source/000077500000000000000000000000001360512042700155575ustar00rootroot00000000000000json-rpc-1.13.0/docs/source/conf.py000066400000000000000000000174521360512042700170670ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # json-rpc documentation build configuration file, created by # sphinx-quickstart on Sun Oct 13 15:41:10 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) from jsonrpc import version, PROJECT # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = PROJECT copyright = u'2013-2015, Kirill Pavlov' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. import sphinx_rtd_theme html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'json-rpcdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'json-rpc.tex', u'json-rpc Documentation', u'Kirill Pavlov', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'json-rpc', u'json-rpc Documentation', [u'Kirill Pavlov'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'json-rpc', u'json-rpc Documentation', u'Kirill Pavlov', 'json-rpc', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # lint_ignore=E501 json-rpc-1.13.0/docs/source/dispatcher.rst000066400000000000000000000001661360512042700204420ustar00rootroot00000000000000Method dispatcher ================= .. automodule:: jsonrpc.dispatcher :members: :special-members: __init__ json-rpc-1.13.0/docs/source/django_integration.rst000066400000000000000000000031411360512042700221550ustar00rootroot00000000000000Integration with Django ======================= .. note:: Django backend is optionally supported. Library itself does not depend on Django. Django integration is similar project to project. Starting from version 1.8.4 json-rpc support it and provides convenient way of integration. To add json-rpc to Django project follow steps. Create api instance ------------------- If you want to use default (global) object, skip this step. In most cases it is enougth to start with it, even if you plan to add another version later. Default api is located here: .. code-block:: python from jsonrpc.backend.django import api If you would like to use different api versions (not, you could name methods differently) or use cudtom dispatcher, use .. code-block:: python from jsonrpc.backend.django import JSONRPCAPI api = JSONRPCAPI(dispatcher=) Later on we assume that you use default api instance Add api urls to the project --------------------------- In your urls.py file add .. code-block:: python urlpatterns = patterns( ... url(r'^api/jsonrpc/', include(api.urls)), ) Add methods to api ------------------ .. code-block:: python @api.dispatcher.add_method def my_method(request, *args, **kwargs): return args, kwargs .. note:: first argument of each method should be request. In this case it is possible to get user and control access to data Make requests to api -------------------- To use api, send `POST` request to api address. Make sure your message has correct format. Also json-rpc generates method's map. It is available at `/map` url. json-rpc-1.13.0/docs/source/exceptions.rst000066400000000000000000000100271360512042700204720ustar00rootroot00000000000000Exceptions ========== According to specification, error code should be in response message. Http server should respond with status code 200, even if there is an error. JSON-RPC Errors --------------- .. note:: Error is an object which represent any kind of erros in JSON-RPC specification. It is not python Exception and could not be raised. Errors (Error messages) are members of :class:`~jsonrpc.exceptions.JSONRPCError` class. Any custom error messages should be inherited from it. The class is responsible for specification following and creates response string based on error's attributes. JSON-RPC has several predefined errors, each of them has reserved code, which should not be used for custom errors. +------------------+------------------+------------------------------------------------------------------------------------------------------+ | Code | Message | Meaning | +------------------+------------------+------------------------------------------------------------------------------------------------------+ | -32700 | Parse error | Invalid JSON was received by the server.An error occurred on the server while parsing the JSON text. | +------------------+------------------+------------------------------------------------------------------------------------------------------+ | -32600 | Invalid Request | The JSON sent is not a valid Request object. | +------------------+------------------+------------------------------------------------------------------------------------------------------+ | -32601 | Method not found | The method does not exist / is not available. | +------------------+------------------+------------------------------------------------------------------------------------------------------+ | -32602 | Invalid params | Invalid method parameter(s). | +------------------+------------------+------------------------------------------------------------------------------------------------------+ | -32603 | Internal error | Internal JSON-RPC error. | +------------------+------------------+------------------------------------------------------------------------------------------------------+ | -32000 to -32099 | Server error | Reserved for implementation-defined server-errors. | +------------------+------------------+------------------------------------------------------------------------------------------------------+ :class:`~jsonrpc.manager.JSONRPCResponseManager` handles common errors. If you do not plan to implement own manager, you do not need to write custom errors. To controll error messages and codes, json-rpc has exceptions, covered in next paragraph. JSON-RPC Exceptions ------------------- .. note:: Exception here a json-rpc library object and not related to specification. They are inherited from python Exception and could be raised. JSON-RPC manager handles dispatcher method's exceptions, anything you raise would be catched. There are two ways to generate error message in manager: First is to simply raise exception in your method. Manager will catch it and return :class:`~jsonrpc.exceptions.JSONRPCServerError` message with description. Advantage of this mehtod is that everything is already implemented, just add method to dispatcher and manager will do the job. If you need custom message code or error management, you might need to raise exception, inherited from :class:`~jsonrpc.exceptions.JSONRPCDispatchException`. Make sure, your exception class has error code. .. versionadded:: 1.9.0 Fix `Invalid params` error false generated if method raises TypeError. Now in this case manager introspects the code and returns proper exception. json-rpc-1.13.0/docs/source/flask_integration.rst000066400000000000000000000032111360512042700220110ustar00rootroot00000000000000Integration with Flask ====================== .. note:: Flask backend is optionaly supported. Library itself does not depend on Flask. Create api instance ------------------- If you want to use default (global) object, skip this step. In most cases it is enough to start with it, even if you plan to add another version later. Default api is located here: .. code-block:: python from jsonrpc.backend.flask import api If you would like to use different api versions (not, you could name methods differently) or use custom dispatcher, use .. code-block:: python from jsonrpc.backend.flask import JSONRPCAPI api = JSONRPCAPI(dispatcher=) Later on we assume that you use default api instance. Add api endpoint to the project ------------------------------- You have to options to add new endpoint to your Flask application. First - register as a blueprint. In this case, as small bonus, you got a /map handler, which prints all registered methods. .. code-block:: python from flask import Flask from jsonrpc.backend.flask import api app = Flask(__name__) app.register_blueprint(api.as_blueprint()) Second - register as a usual view. .. code-block:: python from flask import Flask from jsonrpc.backend.flask import api app = Flask(__name__) app.add_url_rule('/', 'api', api.as_view(), methods=['POST']) Add methods to api ------------------ .. code-block:: python @api.dispatcher.add_method def my_method(*args, **kwargs): return args, kwargs Make requests to api -------------------- To use api, send `POST` request to api address. Make sure your message has correct format. json-rpc-1.13.0/docs/source/index.rst000066400000000000000000000027271360512042700174300ustar00rootroot00000000000000.. json-rpc documentation master file, created by sphinx-quickstart on Sun Oct 13 15:41:10 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. JSON-RPC transport implementation ================================= :Source code: https://github.com/pavlov99/json-rpc :Issue tracker: https://github.com/pavlov99/json-rpc/issues JSON-RPC is a stateless, light-weight remote procedure call (RPC) protocol. Primarily this specification defines several data structures and the rules around their processing. It is transport agnostic in that the concepts can be used within the same process, over sockets, over http, or in many various message passing environments. It uses JSON (RFC 4627) as data format. .. raw:: html Features -------- * Supports `JSON-RPC2.0 `_ and `JSON-RPC1.0 `_ * Implementation is complete and 100% tested * Does not depend on transport realisation, no external dependencies * It comes with request manager and optional Django support * Compatible with Python 2.6, 2.7, 3.x >= 3.2, PyPy Contents -------- .. toctree:: :maxdepth: 2 quickstart dispatcher exceptions django_integration flask_integration jsonrpc json-rpc-1.13.0/docs/source/jsonrpc.rst000066400000000000000000000010101360512042700177570ustar00rootroot00000000000000jsonrpc Package =============== JSONRPC ------- .. automodule:: jsonrpc.jsonrpc :members: :undoc-members: :show-inheritance: Exceptions ---------- .. automodule:: jsonrpc.exceptions :members: :undoc-members: :show-inheritance: Manager ------- .. automodule:: jsonrpc.manager :members: :undoc-members: :show-inheritance: jsonrpc.backend.django module ----------------------------- .. automodule:: jsonrpc.backend.django :members: :undoc-members: :show-inheritance: json-rpc-1.13.0/docs/source/quickstart.rst000066400000000000000000000042211360512042700205020ustar00rootroot00000000000000Quickstart ========== Installation ------------ .. highlight:: bash :Requirements: **Python 2.6, 2.7**, **Python 3.x >= 3.2** or **PyPy** To install the latest released version of package:: pip install json-rpc Integration ----------- Package is transport agnostic, integration depends on you framework. As an example we have server with `Werkzeug `_ and client with `requests `_. Server .. code-block:: python from werkzeug.wrappers import Request, Response from werkzeug.serving import run_simple from jsonrpc import JSONRPCResponseManager, dispatcher @dispatcher.add_method def foobar(**kwargs): return kwargs["foo"] + kwargs["bar"] @Request.application def application(request): # Dispatcher is dictionary {: callable} dispatcher["echo"] = lambda s: s dispatcher["add"] = lambda a, b: a + b response = JSONRPCResponseManager.handle( request.data, dispatcher) return Response(response.json, mimetype='application/json') if __name__ == '__main__': run_simple('localhost', 4000, application) Client .. code-block:: python import requests import json def main(): url = "http://localhost:4000/jsonrpc" headers = {'content-type': 'application/json'} # Example echo method payload = { "method": "echo", "params": ["echome!"], "jsonrpc": "2.0", "id": 0, } response = requests.post( url, data=json.dumps(payload), headers=headers).json() assert response["result"] == "echome!" assert response["jsonrpc"] assert response["id"] == 0 if __name__ == "__main__": main() Package ensures that request and response messages have correct format. Besides that it provides :class:`jsonrpc.manager.JSONRPCResponseManager` which handles server common cases, such as incorrect message format or invalid method parameters. Futher topics describe how to add methods to manager, how to handle custom exceptions and optional Django integration. json-rpc-1.13.0/examples/000077500000000000000000000000001360512042700151455ustar00rootroot00000000000000json-rpc-1.13.0/examples/client.py000066400000000000000000000037731360512042700170070ustar00rootroot00000000000000import requests import json def main(): url = "http://localhost:4000/jsonrpc" headers = {'content-type': 'application/json'} # Example echo method payload = { "method": "echo", "params": ["echome!"], "jsonrpc": "2.0", "id": 0, } response = requests.post( url, data=json.dumps(payload), headers=headers).json() assert response["result"] == "echome!" assert response["jsonrpc"] == "2.0" assert response["id"] == 0 # Example echo method JSON-RPC 1.0 payload = { "method": "echo", "params": ["echome!"], "id": 0, } response = requests.post( url, data=json.dumps(payload), headers=headers).json() assert response["result"] == "echome!" assert response["error"] is None assert response["id"] == 0 assert "jsonrpc" not in response # Example add method payload = { "method": "add", "params": [1, 2], "jsonrpc": "2.0", "id": 1, } response = requests.post( url, data=json.dumps(payload), headers=headers).json() assert response["result"] == 3 assert response["jsonrpc"] == "2.0" assert response["id"] == 1 # Example foobar method payload = { "method": "foobar", "params": {"foo": "json", "bar": "-rpc"}, "jsonrpc": "2.0", "id": 3, } response = requests.post( url, data=json.dumps(payload), headers=headers).json() assert response["result"] == "json-rpc" assert response["jsonrpc"] == "2.0" assert response["id"] == 3 # Example exception payload = { "method": "add", "params": [0], "jsonrpc": "2.0", "id": 4, } response = requests.post( url, data=json.dumps(payload), headers=headers).json() assert response["error"]["message"] == "Invalid params" assert response["error"]["code"] == -32602 assert response["jsonrpc"] == "2.0" assert response["id"] == 4 if __name__ == "__main__": main() json-rpc-1.13.0/examples/server.py000066400000000000000000000015641360512042700170330ustar00rootroot00000000000000""" Example of json-rpc usage with Wergzeug and requests. NOTE: there are no Werkzeug and requests in dependencies of json-rpc. NOTE: server handles all url paths the same way (there are no different urls). """ from werkzeug.wrappers import Request, Response from werkzeug.serving import run_simple from jsonrpc import JSONRPCResponseManager, dispatcher @dispatcher.add_method def foobar(**kwargs): return kwargs["foo"] + kwargs["bar"] @Request.application def application(request): # Dispatcher is dictionary {: callable} dispatcher["echo"] = lambda s: s dispatcher["add"] = lambda a, b: a + b response = JSONRPCResponseManager.handle( request.get_data(cache=False, as_text=True), dispatcher) return Response(response.json, mimetype='application/json') if __name__ == '__main__': run_simple('localhost', 4000, application) json-rpc-1.13.0/jsonrpc/000077500000000000000000000000001360512042700150055ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/__init__.py000066400000000000000000000003651360512042700171220ustar00rootroot00000000000000from .manager import JSONRPCResponseManager from .dispatcher import Dispatcher __version = (1, 13, 0) __version__ = version = '.'.join(map(str, __version)) __project__ = PROJECT = __name__ dispatcher = Dispatcher() # lint_ignore=W0611,W0401 json-rpc-1.13.0/jsonrpc/backend/000077500000000000000000000000001360512042700163745ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/backend/__init__.py000066400000000000000000000000001360512042700204730ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/backend/django.py000066400000000000000000000054501360512042700202140ustar00rootroot00000000000000from __future__ import absolute_import from django.views.decorators.csrf import csrf_exempt from django.conf.urls import url from django.conf import settings from django.http import HttpResponse, HttpResponseNotAllowed import copy import json import logging import time from ..exceptions import JSONRPCInvalidRequestException from ..jsonrpc import JSONRPCRequest from ..manager import JSONRPCResponseManager from ..utils import DatetimeDecimalEncoder from ..dispatcher import Dispatcher logger = logging.getLogger(__name__) def response_serialize(obj): """ Serializes response's data object to JSON. """ return json.dumps(obj, cls=DatetimeDecimalEncoder) class JSONRPCAPI(object): def __init__(self, dispatcher=None): self.dispatcher = dispatcher if dispatcher is not None \ else Dispatcher() @property def urls(self): urls = [ url(r'^$', self.jsonrpc, name='endpoint'), ] if getattr(settings, 'JSONRPC_MAP_VIEW_ENABLED', settings.DEBUG): urls.append( url(r'^map$', self.jsonrpc_map, name='map') ) return urls @csrf_exempt def jsonrpc(self, request): """ JSON-RPC 2.0 handler.""" if request.method != "POST": return HttpResponseNotAllowed(["POST"]) request_str = request.body.decode('utf8') try: jsonrpc_request = JSONRPCRequest.from_json(request_str) except (TypeError, ValueError, JSONRPCInvalidRequestException): response = JSONRPCResponseManager.handle( request_str, self.dispatcher) else: jsonrpc_request.params = jsonrpc_request.params or {} jsonrpc_request_params = copy.copy(jsonrpc_request.params) if isinstance(jsonrpc_request.params, dict): jsonrpc_request.params.update(request=request) if isinstance(jsonrpc_request.params, list): jsonrpc_request.params.insert(0, request) t1 = time.time() response = JSONRPCResponseManager.handle_request( jsonrpc_request, self.dispatcher) t2 = time.time() logger.info('{0}({1}) {2:.2f} sec'.format( jsonrpc_request.method, jsonrpc_request_params, t2 - t1)) if response: response.serialize = response_serialize response = response.json return HttpResponse(response, content_type="application/json") def jsonrpc_map(self, request): """ Map of json-rpc available calls. :return str: """ result = "

JSON-RPC map

{0}
".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return HttpResponse(result) api = JSONRPCAPI() json-rpc-1.13.0/jsonrpc/backend/flask.py000066400000000000000000000046321360512042700200530ustar00rootroot00000000000000from __future__ import absolute_import import copy import json import logging import time from uuid import uuid4 from flask import Blueprint, request, Response from ..exceptions import JSONRPCInvalidRequestException from ..jsonrpc import JSONRPCRequest from ..manager import JSONRPCResponseManager from ..utils import DatetimeDecimalEncoder from ..dispatcher import Dispatcher logger = logging.getLogger(__name__) class JSONRPCAPI(object): def __init__(self, dispatcher=None, check_content_type=True): """ :param dispatcher: methods dispatcher :param check_content_type: if True - content-type must be "application/json" :return: """ self.dispatcher = dispatcher if dispatcher is not None \ else Dispatcher() self.check_content_type = check_content_type def as_blueprint(self, name=None): blueprint = Blueprint(name if name else str(uuid4()), __name__) blueprint.add_url_rule( '/', view_func=self.jsonrpc, methods=['POST']) blueprint.add_url_rule( '/map', view_func=self.jsonrpc_map, methods=['GET']) return blueprint def as_view(self): return self.jsonrpc def jsonrpc(self): request_str = self._get_request_str() try: jsonrpc_request = JSONRPCRequest.from_json(request_str) except (TypeError, ValueError, JSONRPCInvalidRequestException): response = JSONRPCResponseManager.handle( request_str, self.dispatcher) else: response = JSONRPCResponseManager.handle_request( jsonrpc_request, self.dispatcher) if response: response.serialize = self._serialize response = response.json return Response(response, content_type="application/json") def jsonrpc_map(self): """ Map of json-rpc available calls. :return str: """ result = "

JSON-RPC map

{0}
".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return Response(result) def _get_request_str(self): if self.check_content_type or request.data: return request.data return list(request.form.keys())[0] @staticmethod def _serialize(s): return json.dumps(s, cls=DatetimeDecimalEncoder) api = JSONRPCAPI() json-rpc-1.13.0/jsonrpc/base.py000066400000000000000000000037621360512042700163010ustar00rootroot00000000000000from .utils import JSONSerializable class JSONRPCBaseRequest(JSONSerializable): """ Base class for JSON-RPC 1.0 and JSON-RPC 2.0 requests.""" def __init__(self, method=None, params=None, _id=None, is_notification=None): self.data = dict() self.method = method self.params = params self._id = _id self.is_notification = is_notification @property def data(self): return self._data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def args(self): """ Method position arguments. :return tuple args: method position arguments. """ return tuple(self.params) if isinstance(self.params, list) else () @property def kwargs(self): """ Method named arguments. :return dict kwargs: method named arguments. """ return self.params if isinstance(self.params, dict) else {} @property def json(self): return self.serialize(self.data) class JSONRPCBaseResponse(JSONSerializable): """ Base class for JSON-RPC 1.0 and JSON-RPC 2.0 responses.""" def __init__(self, **kwargs): self.data = dict() try: self.result = kwargs['result'] except KeyError: pass try: self.error = kwargs['error'] except KeyError: pass self._id = kwargs.get('_id') if 'result' not in kwargs and 'error' not in kwargs: raise ValueError("Either result or error should be used") self.request = None # type: JSONRPCBaseRequest @property def data(self): return self._data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def json(self): return self.serialize(self.data) json-rpc-1.13.0/jsonrpc/dispatcher.py000066400000000000000000000067611360512042700175170ustar00rootroot00000000000000""" Dispatcher is used to add methods (functions) to the server. For usage examples see :meth:`Dispatcher.add_method` """ import functools try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping class Dispatcher(MutableMapping): """ Dictionary like object which maps method_name to method.""" def __init__(self, prototype=None): """ Build method dispatcher. Parameters ---------- prototype : object or dict, optional Initial method mapping. Examples -------- Init object with method dictionary. >>> Dispatcher({"sum": lambda a, b: a + b}) None """ self.method_map = dict() if prototype is not None: self.build_method_map(prototype) def __getitem__(self, key): return self.method_map[key] def __setitem__(self, key, value): self.method_map[key] = value def __delitem__(self, key): del self.method_map[key] def __len__(self): return len(self.method_map) def __iter__(self): return iter(self.method_map) def __repr__(self): return repr(self.method_map) def add_class(self, cls): prefix = cls.__name__.lower() + '.' self.build_method_map(cls(), prefix) def add_object(self, obj): prefix = obj.__class__.__name__.lower() + '.' self.build_method_map(obj, prefix) def add_dict(self, dict, prefix=''): if prefix: prefix += '.' self.build_method_map(dict, prefix) def add_method(self, f=None, name=None): """ Add a method to the dispatcher. Parameters ---------- f : callable Callable to be added. name : str, optional Name to register (the default is function **f** name) Notes ----- When used as a decorator keeps callable object unmodified. Examples -------- Use as method >>> d = Dispatcher() >>> d.add_method(lambda a, b: a + b, name="sum") > Or use as decorator >>> d = Dispatcher() >>> @d.add_method def mymethod(*args, **kwargs): print(args, kwargs) Or use as a decorator with a different function name >>> d = Dispatcher() >>> @d.add_method(name="my.method") def mymethod(*args, **kwargs): print(args, kwargs) """ if name and not f: return functools.partial(self.add_method, name=name) self.method_map[name or f.__name__] = f return f def build_method_map(self, prototype, prefix=''): """ Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispatcher. If given prototype is an object then all public methods will be used. prefix: string, optional Prefix of methods """ if not isinstance(prototype, dict): prototype = dict((method, getattr(prototype, method)) for method in dir(prototype) if not method.startswith('_')) for attr, method in prototype.items(): if callable(method): self[prefix + attr] = method json-rpc-1.13.0/jsonrpc/exceptions.py000066400000000000000000000103041360512042700175360ustar00rootroot00000000000000""" JSON-RPC Exceptions.""" from . import six import json class JSONRPCError(object): """ Error for JSON-RPC communication. When a rpc call encounters an error, the Response Object MUST contain the error member with a value that is a Object with the following members: Parameters ---------- code: int A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. Any code within this range, but not defined explicitly below is reserved for future use. The error codes are nearly the same as those suggested for XML-RPC at the following url: http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php message: str A String providing a short description of the error. The message SHOULD be limited to a concise single sentence. data: int or str or dict or list, optional A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.). """ serialize = staticmethod(json.dumps) deserialize = staticmethod(json.loads) def __init__(self, code=None, message=None, data=None): self._data = dict() self.code = getattr(self.__class__, "CODE", code) self.message = getattr(self.__class__, "MESSAGE", message) self.data = data def __get_code(self): return self._data["code"] def __set_code(self, value): if not isinstance(value, six.integer_types): raise ValueError("Error code should be integer") self._data["code"] = value code = property(__get_code, __set_code) def __get_message(self): return self._data["message"] def __set_message(self, value): if not isinstance(value, six.string_types): raise ValueError("Error message should be string") self._data["message"] = value message = property(__get_message, __set_message) def __get_data(self): return self._data.get("data") def __set_data(self, value): if value is not None: self._data["data"] = value data = property(__get_data, __set_data) @classmethod def from_json(cls, json_str): data = cls.deserialize(json_str) return cls( code=data["code"], message=data["message"], data=data.get("data")) @property def json(self): return self.serialize(self._data) class JSONRPCParseError(JSONRPCError): """ Parse Error. Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text. """ CODE = -32700 MESSAGE = "Parse error" class JSONRPCInvalidRequest(JSONRPCError): """ Invalid Request. The JSON sent is not a valid Request object. """ CODE = -32600 MESSAGE = "Invalid Request" class JSONRPCMethodNotFound(JSONRPCError): """ Method not found. The method does not exist / is not available. """ CODE = -32601 MESSAGE = "Method not found" class JSONRPCInvalidParams(JSONRPCError): """ Invalid params. Invalid method parameter(s). """ CODE = -32602 MESSAGE = "Invalid params" class JSONRPCInternalError(JSONRPCError): """ Internal error. Internal JSON-RPC error. """ CODE = -32603 MESSAGE = "Internal error" class JSONRPCServerError(JSONRPCError): """ Server error. Reserved for implementation-defined server-errors. """ CODE = -32000 MESSAGE = "Server error" class JSONRPCException(Exception): """ JSON-RPC Exception.""" pass class JSONRPCInvalidRequestException(JSONRPCException): """ Request is not valid.""" pass class JSONRPCDispatchException(JSONRPCException): """ JSON-RPC Dispatch Exception. Should be thrown in dispatch methods. """ def __init__(self, code=None, message=None, data=None, *args, **kwargs): super(JSONRPCDispatchException, self).__init__(args, kwargs) self.error = JSONRPCError(code=code, data=data, message=message) json-rpc-1.13.0/jsonrpc/jsonrpc.py000066400000000000000000000014051360512042700170350ustar00rootroot00000000000000""" JSON-RPC wrappers for version 1.0 and 2.0. Objects diring init operation try to choose JSON-RPC 2.0 and in case of error JSON-RPC 1.0. from_json methods could decide what format is it by presence of 'jsonrpc' attribute. """ from .utils import JSONSerializable from .jsonrpc1 import JSONRPC10Request from .jsonrpc2 import JSONRPC20Request class JSONRPCRequest(JSONSerializable): """ JSONRPC Request.""" @classmethod def from_json(cls, json_str): data = cls.deserialize(json_str) return cls.from_data(data) @classmethod def from_data(cls, data): if isinstance(data, dict) and "jsonrpc" not in data: return JSONRPC10Request.from_data(data) else: return JSONRPC20Request.from_data(data) json-rpc-1.13.0/jsonrpc/jsonrpc1.py000066400000000000000000000102061360512042700171150ustar00rootroot00000000000000from . import six from .base import JSONRPCBaseRequest, JSONRPCBaseResponse from .exceptions import JSONRPCInvalidRequestException, JSONRPCError class JSONRPC10Request(JSONRPCBaseRequest): """ JSON-RPC 1.0 Request. A remote method is invoked by sending a request to a remote service. The request is a single object serialized using json. :param str method: The name of the method to be invoked. :param list params: An Array of objects to pass as arguments to the method. :param _id: This can be of any type. It is used to match the response with the request that it is replying to. :param bool is_notification: whether request notification or not. """ JSONRPC_VERSION = "1.0" REQUIRED_FIELDS = set(["method", "params", "id"]) POSSIBLE_FIELDS = set(["method", "params", "id"]) @property def data(self): data = dict((k, v) for k, v in self._data.items()) data["id"] = None if self.is_notification else data["id"] return data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def method(self): return self._data.get("method") @method.setter def method(self, value): if not isinstance(value, six.string_types): raise ValueError("Method should be string") self._data["method"] = str(value) @property def params(self): return self._data.get("params") @params.setter def params(self, value): if not isinstance(value, (list, tuple)): raise ValueError("Incorrect params {0}".format(value)) self._data["params"] = list(value) @property def _id(self): return self._data.get("id") @_id.setter def _id(self, value): self._data["id"] = value @property def is_notification(self): return self._data["id"] is None or self._is_notification @is_notification.setter def is_notification(self, value): if value is None: value = self._id is None if self._id is None and not value: raise ValueError("Can not set attribute is_notification. " + "Request id should not be None") self._is_notification = value @classmethod def from_json(cls, json_str): data = cls.deserialize(json_str) return cls.from_data(data) @classmethod def from_data(cls, data): if not isinstance(data, dict): raise ValueError("data should be dict") if cls.REQUIRED_FIELDS <= set(data.keys()) <= cls.POSSIBLE_FIELDS: return cls( method=data["method"], params=data["params"], _id=data["id"] ) else: extra = set(data.keys()) - cls.POSSIBLE_FIELDS missed = cls.REQUIRED_FIELDS - set(data.keys()) msg = "Invalid request. Extra fields: {0}, Missed fields: {1}" raise JSONRPCInvalidRequestException(msg.format(extra, missed)) class JSONRPC10Response(JSONRPCBaseResponse): JSONRPC_VERSION = "1.0" @property def data(self): data = dict((k, v) for k, v in self._data.items()) return data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def result(self): return self._data.get("result") @result.setter def result(self, value): if self.error: raise ValueError("Either result or error should be used") self._data["result"] = value @property def error(self): return self._data.get("error") @error.setter def error(self, value): self._data.pop('value', None) if value: self._data["error"] = value # Test error JSONRPCError(**value) @property def _id(self): return self._data.get("id") @_id.setter def _id(self, value): if value is None: raise ValueError("id could not be null for JSON-RPC1.0 Response") self._data["id"] = value json-rpc-1.13.0/jsonrpc/jsonrpc2.py000066400000000000000000000203611360512042700171210ustar00rootroot00000000000000from . import six import json from .exceptions import JSONRPCError, JSONRPCInvalidRequestException from .base import JSONRPCBaseRequest, JSONRPCBaseResponse class JSONRPC20Request(JSONRPCBaseRequest): """ A rpc call is represented by sending a Request object to a Server. :param str method: A String containing the name of the method to be invoked. Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46) are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else. :param params: A Structured value that holds the parameter values to be used during the invocation of the method. This member MAY be omitted. :type params: iterable or dict :param _id: An identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null [1] and Numbers SHOULD NOT contain fractional parts [2]. :type _id: str or int or None :param bool is_notification: Whether request is notification or not. If value is True, _id is not included to request. It allows to create requests with id = null. The Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects. [1] The use of Null as a value for the id member in a Request object is discouraged, because this specification uses a value of Null for Responses with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null for Notifications this could cause confusion in handling. [2] Fractional parts may be problematic, since many decimal fractions cannot be represented exactly as binary fractions. """ JSONRPC_VERSION = "2.0" REQUIRED_FIELDS = set(["jsonrpc", "method"]) POSSIBLE_FIELDS = set(["jsonrpc", "method", "params", "id"]) @property def data(self): data = dict( (k, v) for k, v in self._data.items() if not (k == "id" and self.is_notification) ) data["jsonrpc"] = self.JSONRPC_VERSION return data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def method(self): return self._data.get("method") @method.setter def method(self, value): if not isinstance(value, six.string_types): raise ValueError("Method should be string") if value.startswith("rpc."): raise ValueError( "Method names that begin with the word rpc followed by a " + "period character (U+002E or ASCII 46) are reserved for " + "rpc-internal methods and extensions and MUST NOT be used " + "for anything else.") self._data["method"] = str(value) @property def params(self): return self._data.get("params") @params.setter def params(self, value): if value is not None and not isinstance(value, (list, tuple, dict)): raise ValueError("Incorrect params {0}".format(value)) value = list(value) if isinstance(value, tuple) else value if value is not None: self._data["params"] = value @property def _id(self): return self._data.get("id") @_id.setter def _id(self, value): if value is not None and \ not isinstance(value, six.string_types + six.integer_types): raise ValueError("id should be string or integer") self._data["id"] = value @classmethod def from_json(cls, json_str): data = cls.deserialize(json_str) return cls.from_data(data) @classmethod def from_data(cls, data): is_batch = isinstance(data, list) data = data if is_batch else [data] if not data: raise JSONRPCInvalidRequestException("[] value is not accepted") if not all(isinstance(d, dict) for d in data): raise JSONRPCInvalidRequestException( "Each request should be an object (dict)") result = [] for d in data: if not cls.REQUIRED_FIELDS <= set(d.keys()) <= cls.POSSIBLE_FIELDS: extra = set(d.keys()) - cls.POSSIBLE_FIELDS missed = cls.REQUIRED_FIELDS - set(d.keys()) msg = "Invalid request. Extra fields: {0}, Missed fields: {1}" raise JSONRPCInvalidRequestException(msg.format(extra, missed)) try: result.append(JSONRPC20Request( method=d["method"], params=d.get("params"), _id=d.get("id"), is_notification="id" not in d, )) except ValueError as e: raise JSONRPCInvalidRequestException(str(e)) return JSONRPC20BatchRequest(*result) if is_batch else result[0] class JSONRPC20BatchRequest(object): """ Batch JSON-RPC 2.0 Request. :param JSONRPC20Request *requests: requests """ JSONRPC_VERSION = "2.0" def __init__(self, *requests): self.requests = requests @classmethod def from_json(cls, json_str): return JSONRPC20Request.from_json(json_str) @property def json(self): return json.dumps([r.data for r in self.requests]) def __iter__(self): return iter(self.requests) class JSONRPC20Response(JSONRPCBaseResponse): """ JSON-RPC response object to JSONRPC20Request. When a rpc call is made, the Server MUST reply with a Response, except for in the case of Notifications. The Response is expressed as a single JSON Object, with the following members: :param str jsonrpc: A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0". :param result: This member is REQUIRED on success. This member MUST NOT exist if there was an error invoking the method. The value of this member is determined by the method invoked on the Server. :param dict error: This member is REQUIRED on error. This member MUST NOT exist if there was no error triggered during invocation. The value for this member MUST be an Object. :param id: This member is REQUIRED. It MUST be the same as the value of the id member in the Request Object. If there was an error in detecting the id in the Request object (e.g. Parse error/Invalid Request), it MUST be Null. :type id: str or int or None Either the result member or error member MUST be included, but both members MUST NOT be included. """ JSONRPC_VERSION = "2.0" @property def data(self): data = dict((k, v) for k, v in self._data.items()) data["jsonrpc"] = self.JSONRPC_VERSION return data @data.setter def data(self, value): if not isinstance(value, dict): raise ValueError("data should be dict") self._data = value @property def result(self): return self._data.get("result") @result.setter def result(self, value): if self.error: raise ValueError("Either result or error should be used") self._data["result"] = value @property def error(self): return self._data.get("error") @error.setter def error(self, value): self._data.pop('value', None) if value: self._data["error"] = value # Test error JSONRPCError(**value) @property def _id(self): return self._data.get("id") @_id.setter def _id(self, value): if value is not None and \ not isinstance(value, six.string_types + six.integer_types): raise ValueError("id should be string or integer") self._data["id"] = value class JSONRPC20BatchResponse(object): JSONRPC_VERSION = "2.0" def __init__(self, *responses): self.responses = responses self.request = None # type: JSONRPC20BatchRequest @property def data(self): return [r.data for r in self.responses] @property def json(self): return json.dumps(self.data) def __iter__(self): return iter(self.responses) json-rpc-1.13.0/jsonrpc/manager.py000066400000000000000000000104101360512042700167650ustar00rootroot00000000000000import json import logging from .utils import is_invalid_params from .exceptions import ( JSONRPCInvalidParams, JSONRPCInvalidRequest, JSONRPCInvalidRequestException, JSONRPCMethodNotFound, JSONRPCParseError, JSONRPCServerError, JSONRPCDispatchException, ) from .jsonrpc1 import JSONRPC10Response from .jsonrpc2 import ( JSONRPC20BatchRequest, JSONRPC20BatchResponse, JSONRPC20Response, ) from .jsonrpc import JSONRPCRequest logger = logging.getLogger(__name__) class JSONRPCResponseManager(object): """ JSON-RPC response manager. Method brings syntactic sugar into library. Given dispatcher it handles request (both single and batch) and handles errors. Request could be handled in parallel, it is server responsibility. :param str request_str: json string. Will be converted into JSONRPC20Request, JSONRPC20BatchRequest or JSONRPC10Request :param dict dispather: dict. """ RESPONSE_CLASS_MAP = { "1.0": JSONRPC10Response, "2.0": JSONRPC20Response, } @classmethod def handle(cls, request_str, dispatcher): if isinstance(request_str, bytes): request_str = request_str.decode("utf-8") try: data = json.loads(request_str) except (TypeError, ValueError): return JSONRPC20Response(error=JSONRPCParseError()._data) try: request = JSONRPCRequest.from_data(data) except JSONRPCInvalidRequestException: return JSONRPC20Response(error=JSONRPCInvalidRequest()._data) return cls.handle_request(request, dispatcher) @classmethod def handle_request(cls, request, dispatcher): """ Handle request data. At this moment request has correct jsonrpc format. :param dict request: data parsed from request_str. :param jsonrpc.dispatcher.Dispatcher dispatcher: .. versionadded: 1.8.0 """ rs = request if isinstance(request, JSONRPC20BatchRequest) \ else [request] responses = [r for r in cls._get_responses(rs, dispatcher) if r is not None] # notifications if not responses: return if isinstance(request, JSONRPC20BatchRequest): response = JSONRPC20BatchResponse(*responses) response.request = request return response else: return responses[0] @classmethod def _get_responses(cls, requests, dispatcher): """ Response to each single JSON-RPC Request. :return iterator(JSONRPC20Response): .. versionadded: 1.9.0 TypeError inside the function is distinguished from Invalid Params. """ for request in requests: def make_response(**kwargs): response = cls.RESPONSE_CLASS_MAP[request.JSONRPC_VERSION]( _id=request._id, **kwargs) response.request = request return response output = None try: method = dispatcher[request.method] except KeyError: output = make_response(error=JSONRPCMethodNotFound()._data) else: try: result = method(*request.args, **request.kwargs) except JSONRPCDispatchException as e: output = make_response(error=e.error._data) except Exception as e: data = { "type": e.__class__.__name__, "args": e.args, "message": str(e), } logger.exception("API Exception: {0}".format(data)) if isinstance(e, TypeError) and is_invalid_params( method, *request.args, **request.kwargs): output = make_response( error=JSONRPCInvalidParams(data=data)._data) else: output = make_response( error=JSONRPCServerError(data=data)._data) else: output = make_response(result=result) finally: if not request.is_notification: yield output json-rpc-1.13.0/jsonrpc/six.py000066400000000000000000000511261360512042700161670ustar00rootroot00000000000000"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2013 Benjamin Peterson # # 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. import operator import sys import types __author__ = "Benjamin Peterson " __version__ = "1.4.1" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # This is a bit ugly, but it avoids running this again. delattr(tp, self.name) return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _MovedItems(types.ModuleType): """Lazy loading of moved objects""" _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) del attr moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves") class Module_six_moves_urllib_parse(types.ModuleType): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("urlencode", "urllib", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr sys.modules[__name__ + ".moves.urllib_parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse") sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib.parse") class Module_six_moves_urllib_error(types.ModuleType): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr sys.modules[__name__ + ".moves.urllib_error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib_error") sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error") class Module_six_moves_urllib_request(types.ModuleType): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr sys.modules[__name__ + ".moves.urllib_request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib_request") sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request") class Module_six_moves_urllib_response(types.ModuleType): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr sys.modules[__name__ + ".moves.urllib_response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib_response") sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response") class Module_six_moves_urllib_robotparser(types.ModuleType): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr sys.modules[__name__ + ".moves.urllib_robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib_robotparser") sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" parse = sys.modules[__name__ + ".moves.urllib_parse"] error = sys.modules[__name__ + ".moves.urllib_error"] request = sys.modules[__name__ + ".moves.urllib_request"] response = sys.modules[__name__ + ".moves.urllib_response"] robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"] sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" _iterkeys = "keys" _itervalues = "values" _iteritems = "items" _iterlists = "lists" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" _iterkeys = "iterkeys" _itervalues = "itervalues" _iteritems = "iteritems" _iterlists = "iterlists" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) def iterkeys(d, **kw): """Return an iterator over the keys of a dictionary.""" return iter(getattr(d, _iterkeys)(**kw)) def itervalues(d, **kw): """Return an iterator over the values of a dictionary.""" return iter(getattr(d, _itervalues)(**kw)) def iteritems(d, **kw): """Return an iterator over the (key, value) pairs of a dictionary.""" return iter(getattr(d, _iteritems)(**kw)) def iterlists(d, **kw): """Return an iterator over the (key, [values]) pairs of a dictionary.""" return iter(getattr(d, _iterlists)(**kw)) if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr if sys.version_info[1] <= 1: def int2byte(i): return bytes((i,)) else: # This is about 2x faster than the implementation above on 3.2+ int2byte = operator.methodcaller("to_bytes", 1, "big") byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO else: def b(s): return s def u(s): return unicode(s, "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) def iterbytes(buf): return (ord(byte) for byte in buf) import StringIO StringIO = BytesIO = StringIO.StringIO _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) _add_doc(reraise, """Reraise an exception.""") def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" return meta("NewBase", bases, {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) for slots_var in orig_vars.get('__slots__', ()): orig_vars.pop(slots_var) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapperjson-rpc-1.13.0/jsonrpc/tests/000077500000000000000000000000001360512042700161475ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/tests/__init__.py000066400000000000000000000000001360512042700202460ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/tests/py35_utils.py000066400000000000000000000003151360512042700205400ustar00rootroot00000000000000# Python3.5+ code. # This won't even parse in earlier versions, so it's kept in a separate file # and imported when needed. def distance(a: float, b: float) -> float: return (a ** 2 + b ** 2) ** 0.5 json-rpc-1.13.0/jsonrpc/tests/test_backend_django/000077500000000000000000000000001360512042700221175ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/tests/test_backend_django/__init__.py000066400000000000000000000000001360512042700242160ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/tests/test_backend_django/settings.py000066400000000000000000000004571360512042700243370ustar00rootroot00000000000000SECRET_KEY = 'secret' ROOT_URLCONF = 'jsonrpc.tests.test_backend_django.urls' ALLOWED_HOSTS = ['testserver'] DATABASE_ENGINE = 'django.db.backends.sqlite3' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } JSONRPC_MAP_VIEW_ENABLED = True json-rpc-1.13.0/jsonrpc/tests/test_backend_django/test_backend.py000066400000000000000000000065721360512042700251310ustar00rootroot00000000000000""" Test Django Backend.""" from __future__ import absolute_import import os try: from django.core.urlresolvers import RegexURLPattern from django.test import TestCase except ImportError: import unittest raise unittest.SkipTest('Django not found for testing') from ...backend.django import JSONRPCAPI, api import json class TestDjangoBackend(TestCase): @classmethod def setUpClass(cls): os.environ['DJANGO_SETTINGS_MODULE'] = \ 'jsonrpc.tests.test_backend_django.settings' super(TestDjangoBackend, cls).setUpClass() def test_urls(self): self.assertTrue(isinstance(api.urls, list)) for api_url in api.urls: self.assertTrue(isinstance(api_url, RegexURLPattern)) def test_client(self): @api.dispatcher.add_method def dummy(request): return "" json_data = { "id": "0", "jsonrpc": "2.0", "method": "dummy", } response = self.client.post( '', json.dumps(json_data), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode('utf8')) self.assertEqual(data['result'], '') def test_positional_args(self): @api.dispatcher.add_method def positional_args(request, name): return name json_data = { "id": "0", "jsonrpc": "2.0", "method": "positional_args", "params": ["echome!"], } response = self.client.post( '', json.dumps(json_data), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode('utf8')) self.assertEqual(data['result'], json_data['params'][0]) def test_method_not_allowed(self): response = self.client.get( '', content_type='application/json', ) self.assertEqual(response.status_code, 405, "Should allow only POST") def test_invalid_request(self): response = self.client.post( '', '{', content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.content.decode('utf8')) self.assertEqual(data['error']['code'], -32700) self.assertEqual(data['error']['message'], 'Parse error') def test_resource_map(self): response = self.client.get('/map') self.assertEqual(response.status_code, 200) data = response.content.decode('utf8') self.assertIn("JSON-RPC map", data) def test_method_not_allowed_prefix(self): response = self.client.get( '/prefix/', content_type='application/json', ) self.assertEqual(response.status_code, 405) def test_resource_map_prefix(self): response = self.client.get('/prefix/map') self.assertEqual(response.status_code, 200) def test_empty_initial_dispatcher(self): class SubDispatcher(type(api.dispatcher)): pass custom_dispatcher = SubDispatcher() custom_api = JSONRPCAPI(custom_dispatcher) self.assertEqual(type(custom_api.dispatcher), SubDispatcher) self.assertEqual(id(custom_api.dispatcher), id(custom_dispatcher)) json-rpc-1.13.0/jsonrpc/tests/test_backend_django/urls.py000066400000000000000000000002561360512042700234610ustar00rootroot00000000000000from django.conf.urls import url, include from jsonrpc.backend.django import api urlpatterns = [ url(r'', include(api.urls)), url(r'^prefix/', include(api.urls)), ] json-rpc-1.13.0/jsonrpc/tests/test_backend_flask/000077500000000000000000000000001360512042700217555ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/tests/test_backend_flask/__init__.py000066400000000000000000000000001360512042700240540ustar00rootroot00000000000000json-rpc-1.13.0/jsonrpc/tests/test_backend_flask/test_backend.py000066400000000000000000000134321360512042700247600ustar00rootroot00000000000000import json import sys if sys.version_info < (3, 3): from mock import patch else: from unittest.mock import patch if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Flask is supported only for python2 and python3.3+ if sys.version_info < (3, 0) or sys.version_info >= (3, 3): try: from flask import Flask except ImportError: raise unittest.SkipTest('Flask not found for testing') from ...backend.flask import JSONRPCAPI, api @api.dispatcher.add_method def dummy(): return "" @unittest.skipIf((3, 0) <= sys.version_info < (3, 3), 'Flask does not support python 3.0 - 3.2') class TestFlaskBackend(unittest.TestCase): REQUEST = json.dumps({ "id": "0", "jsonrpc": "2.0", "method": "dummy", }) def setUp(self): self.client = self._get_test_client(JSONRPCAPI()) def _get_test_client(self, api): @api.dispatcher.add_method def dummy(): return "" app = Flask(__name__) app.config["TESTING"] = True app.register_blueprint(api.as_blueprint()) return app.test_client() def test_client(self): response = self.client.post( '/', data=self.REQUEST, content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['result'], '') def test_method_not_allowed(self): response = self.client.get( '/', content_type='application/json', ) self.assertEqual(response.status_code, 405, "Should allow only POST") def test_parse_error(self): response = self.client.post( '/', data='{', content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32700) self.assertEqual(data['error']['message'], 'Parse error') def test_wrong_content_type(self): response = self.client.post( '/', data=self.REQUEST, content_type='application/x-www-form-urlencoded', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32700) self.assertEqual(data['error']['message'], 'Parse error') def test_invalid_request(self): response = self.client.post( '/', data='{"method": "dummy", "id": 1}', content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32600) self.assertEqual(data['error']['message'], 'Invalid Request') def test_method_not_found(self): data = { "jsonrpc": "2.0", "method": "dummy2", "id": 1 } response = self.client.post( '/', data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32601) self.assertEqual(data['error']['message'], 'Method not found') def test_invalid_parameters(self): data = { "jsonrpc": "2.0", "method": "dummy", "params": [42], "id": 1 } response = self.client.post( '/', data=json.dumps(data), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['error']['code'], -32602) self.assertEqual(data['error']['message'], 'Invalid params') def test_resource_map(self): response = self.client.get('/map') self.assertEqual(response.status_code, 200) self.assertTrue("JSON-RPC map" in response.data.decode('utf8')) def test_method_not_allowed_prefix(self): response = self.client.get( '/', content_type='application/json', ) self.assertEqual(response.status_code, 405) def test_resource_map_prefix(self): response = self.client.get('/map') self.assertEqual(response.status_code, 200) def test_as_view(self): api = JSONRPCAPI() with patch.object(api, 'jsonrpc') as mock_jsonrpc: self.assertIs(api.as_view(), mock_jsonrpc) def test_not_check_content_type(self): client = self._get_test_client(JSONRPCAPI(check_content_type=False)) response = client.post( '/', data=self.REQUEST, ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['result'], '') def test_check_content_type(self): client = self._get_test_client(JSONRPCAPI(check_content_type=False)) response = client.post( '/', data=self.REQUEST, content_type="application/x-www-form-urlencoded" ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode('utf8')) self.assertEqual(data['result'], '') def test_empty_initial_dispatcher(self): class SubDispatcher(type(api.dispatcher)): pass custom_dispatcher = SubDispatcher() custom_api = JSONRPCAPI(custom_dispatcher) self.assertEqual(type(custom_api.dispatcher), SubDispatcher) self.assertEqual(id(custom_api.dispatcher), id(custom_dispatcher)) json-rpc-1.13.0/jsonrpc/tests/test_base.py000066400000000000000000000016501360512042700204740ustar00rootroot00000000000000""" Test base JSON-RPC classes.""" import sys from ..base import JSONRPCBaseRequest, JSONRPCBaseResponse if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestJSONRPCBaseRequest(unittest.TestCase): """ Test JSONRPCBaseRequest functionality.""" def test_data(self): request = JSONRPCBaseRequest() self.assertEqual(request.data, {}) with self.assertRaises(ValueError): request.data = [] with self.assertRaises(ValueError): request.data = None class TestJSONRPCBaseResponse(unittest.TestCase): """ Test JSONRPCBaseResponse functionality.""" def test_data(self): response = JSONRPCBaseResponse(result="") self.assertEqual(response.data, {}) with self.assertRaises(ValueError): response.data = [] with self.assertRaises(ValueError): response.data = None json-rpc-1.13.0/jsonrpc/tests/test_bug29.py000066400000000000000000000015311360512042700205100ustar00rootroot00000000000000""" Exmples of usage with tests. Tests in this file represent examples taken from JSON-RPC specification. http://www.jsonrpc.org/specification#examples """ import sys import json from ..manager import JSONRPCResponseManager if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest def isjsonequal(json1, json2): return json.loads(json1) == json.loads(json2) class TestJSONRPCExamples(unittest.TestCase): def setUp(self): self.dispatcher = { "return_none": lambda: None, } def test_none_as_result(self): req = '{"jsonrpc": "2.0", "method": "return_none", "id": 0}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": null, "id": 0}' )) json-rpc-1.13.0/jsonrpc/tests/test_dispatcher.py000066400000000000000000000060201360512042700217040ustar00rootroot00000000000000from ..dispatcher import Dispatcher import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class Math: def sum(self, a, b): return a + b def diff(self, a, b): return a - b class TestDispatcher(unittest.TestCase): """ Test Dispatcher functionality.""" def test_getter(self): d = Dispatcher() with self.assertRaises(KeyError): d["method"] d["add"] = lambda *args: sum(args) self.assertEqual(d["add"](1, 1), 2) def test_in(self): d = Dispatcher() d["method"] = lambda: "" self.assertIn("method", d) def test_add_method(self): d = Dispatcher() @d.add_method def add(x, y): return x + y self.assertIn("add", d) self.assertEqual(d["add"](1, 1), 2) def test_add_method_with_name(self): d = Dispatcher() @d.add_method(name="this.add") def add(x, y): return x + y self.assertNotIn("add", d) self.assertIn("this.add", d) self.assertEqual(d["this.add"](1, 1), 2) def test_add_class(self): d = Dispatcher() d.add_class(Math) self.assertIn("math.sum", d) self.assertIn("math.diff", d) self.assertEqual(d["math.sum"](3, 8), 11) self.assertEqual(d["math.diff"](6, 9), -3) def test_add_object(self): d = Dispatcher() d.add_object(Math()) self.assertIn("math.sum", d) self.assertIn("math.diff", d) self.assertEqual(d["math.sum"](5, 2), 7) self.assertEqual(d["math.diff"](15, 9), 6) def test_add_dict(self): d = Dispatcher() d.add_dict({"sum": lambda *args: sum(args)}, "util") self.assertIn("util.sum", d) self.assertEqual(d["util.sum"](13, -2), 11) def test_add_method_keep_function_definitions(self): d = Dispatcher() @d.add_method def one(x): return x self.assertIsNotNone(one) def test_del_method(self): d = Dispatcher() d["method"] = lambda: "" self.assertIn("method", d) del d["method"] self.assertNotIn("method", d) def test_to_dict(self): d = Dispatcher() def func(): return "" d["method"] = func self.assertEqual(dict(d), {"method": func}) def test_init_from_object_instance(self): class Dummy(): def one(self): pass def two(self): pass dummy = Dummy() d = Dispatcher(dummy) self.assertIn("one", d) self.assertIn("two", d) self.assertNotIn("__class__", d) def test_init_from_dictionary(self): dummy = { 'one': lambda x: x, 'two': lambda x: x, } d = Dispatcher(dummy) self.assertIn("one", d) self.assertIn("two", d) def test_dispatcher_representation(self): d = Dispatcher() self.assertEqual('{}', repr(d)) json-rpc-1.13.0/jsonrpc/tests/test_examples20.py000066400000000000000000000177071360512042700215540ustar00rootroot00000000000000""" Exmples of usage with tests. Tests in this file represent examples taken from JSON-RPC specification. http://www.jsonrpc.org/specification#examples """ import sys import json from ..manager import JSONRPCResponseManager from ..jsonrpc2 import JSONRPC20Request, JSONRPC20BatchRequest if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest def isjsonequal(json1, json2): return json.loads(json1) == json.loads(json2) class TestJSONRPCExamples(unittest.TestCase): def setUp(self): self.dispatcher = { "subtract": lambda a, b: a - b, } def test_rpc_call_with_positional_parameters(self): req = '{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}' # noqa response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": 19, "id": 1}' )) req = '{"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}' # noqa response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": -19, "id": 2}' )) def test_rpc_call_with_named_parameters(self): def subtract(minuend=None, subtrahend=None): return minuend - subtrahend dispatcher = { "subtract": subtract, "sum": lambda *args: sum(args), "get_data": lambda: ["hello", 5], } req = '{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}' # noqa response = JSONRPCResponseManager.handle(req, dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": 19, "id": 3}' )) req = '{"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}' # noqa response = JSONRPCResponseManager.handle(req, dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "result": 19, "id": 4}', )) def test_notification(self): req = '{"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertEqual(response, None) req = '{"jsonrpc": "2.0", "method": "foobar"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertEqual(response, None) def test_rpc_call_of_non_existent_method(self): req = '{"jsonrpc": "2.0", "method": "foobar", "id": "1"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}' # noqa )) def test_rpc_call_with_invalid_json(self): req = '{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}' # noqa )) def test_rpc_call_with_invalid_request_object(self): req = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa )) def test_rpc_call_batch_invalid_json(self): req = """[ {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method" ]""" response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}' # noqa )) def test_rpc_call_with_an_empty_array(self): req = '[]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa )) def test_rpc_call_with_rpc_call_with_an_invalid_batch_but_not_empty(self): req = '[1]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isjsonequal( response.json, '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa )) def test_rpc_call_with_invalid_batch(self): req = '[1,2,3]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue( response, json.loads("""[ {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}, {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}, {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null} ]""") ) def test_rpc_call_batch(self): req = """[ {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"}, {"foo": "boo"}, {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"}, {"jsonrpc": "2.0", "method": "get_data", "id": "9"} ]""" response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue( response, json.loads("""[ {"jsonrpc": "2.0", "result": 7, "id": "1"}, {"jsonrpc": "2.0", "result": 19, "id": "2"}, {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}, {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "5"}, {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"} ]""") ) def test_rpc_call_batch_all_notifications(self): req = """[ {"jsonrpc": "2.0", "method": "notify_sum", "params": [1,2,4]}, {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]} ]""" response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertEqual(response, None) def test_rpc_call_response_request(self): req = '{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}' # noqa response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isinstance( response.request, JSONRPC20Request )) self.assertTrue(isjsonequal( response.request.json, req )) def test_rpc_call_response_request_batch(self): req = """[ {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"}, {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"}, {"jsonrpc": "2.0", "method": "get_data", "id": "9"} ]""" response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isinstance( response.request, JSONRPC20BatchRequest )) self.assertTrue(isjsonequal( response.request.json, req )) json-rpc-1.13.0/jsonrpc/tests/test_jsonrpc.py000066400000000000000000000000461360512042700212360ustar00rootroot00000000000000""" Tets base JSON-RPC structures.""" json-rpc-1.13.0/jsonrpc/tests/test_jsonrpc1.py000066400000000000000000000324251360512042700213250ustar00rootroot00000000000000import json import sys from ..exceptions import JSONRPCInvalidRequestException from ..jsonrpc1 import ( JSONRPC10Request, JSONRPC10Response, ) if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestJSONRPC10Request(unittest.TestCase): """ Test JSONRPC10Request functionality.""" def setUp(self): self.request_params = { "method": "add", "params": [1, 2], "_id": 1, } def test_correct_init(self): """ Test object is created.""" JSONRPC10Request(**self.request_params) def test_validation_incorrect_no_parameters(self): with self.assertRaises(ValueError): JSONRPC10Request() def test_method_validation_str(self): self.request_params.update({"method": "add"}) JSONRPC10Request(**self.request_params) def test_method_validation_not_str(self): self.request_params.update({"method": []}) with self.assertRaises(ValueError): JSONRPC10Request(**self.request_params) self.request_params.update({"method": {}}) with self.assertRaises(ValueError): JSONRPC10Request(**self.request_params) self.request_params.update({"method": None}) with self.assertRaises(ValueError): JSONRPC10Request(**self.request_params) def test_params_validation_list(self): self.request_params.update({"params": []}) JSONRPC10Request(**self.request_params) self.request_params.update({"params": [0]}) JSONRPC10Request(**self.request_params) def test_params_validation_tuple(self): self.request_params.update({"params": ()}) JSONRPC10Request(**self.request_params) self.request_params.update({"params": tuple([0])}) JSONRPC10Request(**self.request_params) def test_params_validation_dict(self): self.request_params.update({"params": {}}) with self.assertRaises(ValueError): JSONRPC10Request(**self.request_params) self.request_params.update({"params": {"a": 0}}) with self.assertRaises(ValueError): JSONRPC10Request(**self.request_params) def test_params_validation_none(self): self.request_params.update({"params": None}) with self.assertRaises(ValueError): JSONRPC10Request(**self.request_params) def test_params_validation_incorrect(self): self.request_params.update({"params": "str"}) with self.assertRaises(ValueError): JSONRPC10Request(**self.request_params) def test_request_args(self): self.assertEqual(JSONRPC10Request("add", []).args, ()) self.assertEqual(JSONRPC10Request("add", [1, 2]).args, (1, 2)) def test_id_validation_string(self): self.request_params.update({"_id": "id"}) JSONRPC10Request(**self.request_params) def test_id_validation_int(self): self.request_params.update({"_id": 0}) JSONRPC10Request(**self.request_params) def test_id_validation_null(self): self.request_params.update({"_id": "null"}) JSONRPC10Request(**self.request_params) def test_id_validation_none(self): self.request_params.update({"_id": None}) JSONRPC10Request(**self.request_params) def test_id_validation_float(self): self.request_params.update({"_id": 0.1}) JSONRPC10Request(**self.request_params) def test_id_validation_list_tuple(self): self.request_params.update({"_id": []}) JSONRPC10Request(**self.request_params) self.request_params.update({"_id": ()}) JSONRPC10Request(**self.request_params) def test_id_validation_default_id_none(self): del self.request_params["_id"] JSONRPC10Request(**self.request_params) def test_data_method_1(self): r = JSONRPC10Request("add", []) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_method_2(self): r = JSONRPC10Request(method="add", params=[]) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_params_1(self): r = JSONRPC10Request("add", params=[], _id=None) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_params_2(self): r = JSONRPC10Request("add", ()) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_params_3(self): r = JSONRPC10Request("add", (1, 2)) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [1, 2], "id": None, }) def test_data_id_1(self): r = JSONRPC10Request("add", [], _id="null") self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": "null", }) def test_data_id_1_notification(self): r = JSONRPC10Request("add", [], _id="null", is_notification=True) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_id_2(self): r = JSONRPC10Request("add", [], _id=None) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_id_2_notification(self): r = JSONRPC10Request("add", [], _id=None, is_notification=True) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_id_3(self): r = JSONRPC10Request("add", [], _id="id") self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": "id", }) def test_data_id_3_notification(self): r = JSONRPC10Request("add", [], _id="id", is_notification=True) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_data_id_4(self): r = JSONRPC10Request("add", [], _id=0) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": 0, }) def test_data_id_4_notification(self): r = JSONRPC10Request("add", [], _id=0, is_notification=True) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "method": "add", "params": [], "id": None, }) def test_is_notification(self): r = JSONRPC10Request("add", []) self.assertTrue(r.is_notification) r = JSONRPC10Request("add", [], _id=None) self.assertTrue(r.is_notification) r = JSONRPC10Request("add", [], _id="null") self.assertFalse(r.is_notification) r = JSONRPC10Request("add", [], _id=0) self.assertFalse(r.is_notification) r = JSONRPC10Request("add", [], is_notification=True) self.assertTrue(r.is_notification) r = JSONRPC10Request("add", [], is_notification=True, _id=None) self.assertTrue(r.is_notification) r = JSONRPC10Request("add", [], is_notification=True, _id=0) self.assertTrue(r.is_notification) def test_set_unset_notification_keep_id(self): r = JSONRPC10Request("add", [], is_notification=True, _id=0) self.assertTrue(r.is_notification) self.assertEqual(r.data["id"], None) r.is_notification = False self.assertFalse(r.is_notification) self.assertEqual(r.data["id"], 0) def test_error_if_notification_true_but_id_none(self): r = JSONRPC10Request("add", [], is_notification=True, _id=None) with self.assertRaises(ValueError): r.is_notification = False def test_from_json_invalid_request_method(self): str_json = json.dumps({ "params": [1, 2], "id": 0, }) with self.assertRaises(JSONRPCInvalidRequestException): JSONRPC10Request.from_json(str_json) def test_from_json_invalid_request_params(self): str_json = json.dumps({ "method": "add", "id": 0, }) with self.assertRaises(JSONRPCInvalidRequestException): JSONRPC10Request.from_json(str_json) def test_from_json_invalid_request_id(self): str_json = json.dumps({ "method": "add", "params": [1, 2], }) with self.assertRaises(JSONRPCInvalidRequestException): JSONRPC10Request.from_json(str_json) def test_from_json_invalid_request_extra_data(self): str_json = json.dumps({ "method": "add", "params": [1, 2], "id": 0, "is_notification": True, }) with self.assertRaises(JSONRPCInvalidRequestException): JSONRPC10Request.from_json(str_json) def test_from_json_request(self): str_json = json.dumps({ "method": "add", "params": [1, 2], "id": 0, }) request = JSONRPC10Request.from_json(str_json) self.assertTrue(isinstance(request, JSONRPC10Request)) self.assertEqual(request.method, "add") self.assertEqual(request.params, [1, 2]) self.assertEqual(request._id, 0) self.assertFalse(request.is_notification) def test_from_json_request_notification(self): str_json = json.dumps({ "method": "add", "params": [1, 2], "id": None, }) request = JSONRPC10Request.from_json(str_json) self.assertTrue(isinstance(request, JSONRPC10Request)) self.assertEqual(request.method, "add") self.assertEqual(request.params, [1, 2]) self.assertEqual(request._id, None) self.assertTrue(request.is_notification) def test_from_json_string_not_dict(self): with self.assertRaises(ValueError): JSONRPC10Request.from_json("[]") with self.assertRaises(ValueError): JSONRPC10Request.from_json("0") def test_data_setter(self): request = JSONRPC10Request(**self.request_params) with self.assertRaises(ValueError): request.data = [] with self.assertRaises(ValueError): request.data = "" with self.assertRaises(ValueError): request.data = None class TestJSONRPC10Response(unittest.TestCase): """ Test JSONRPC10Response functionality.""" def setUp(self): self.response_success_params = { "result": "", "error": None, "_id": 1, } self.response_error_params = { "result": None, "error": { "code": 1, "message": "error", }, "_id": 1, } def test_correct_init(self): """ Test object is created.""" JSONRPC10Response(**self.response_success_params) JSONRPC10Response(**self.response_error_params) def test_validation_incorrect_no_parameters(self): with self.assertRaises(ValueError): JSONRPC10Response() def test_validation_success_incorrect(self): wrong_params = self.response_success_params del wrong_params["_id"] with self.assertRaises(ValueError): JSONRPC10Response(**wrong_params) def test_validation_error_incorrect(self): wrong_params = self.response_error_params del wrong_params["_id"] with self.assertRaises(ValueError): JSONRPC10Response(**wrong_params) def _test_validation_incorrect_result_and_error(self): # @todo: remove # It is OK because result is an mepty string, it is still result with self.assertRaises(ValueError): JSONRPC10Response(result="", error="", _id=0) response = JSONRPC10Response(error="", _id=0) with self.assertRaises(ValueError): response.result = "" def test_data(self): r = JSONRPC10Response(result="", _id=0) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "result": "", "id": 0, }) def test_data_setter(self): response = JSONRPC10Response(**self.response_success_params) with self.assertRaises(ValueError): response.data = [] with self.assertRaises(ValueError): response.data = "" with self.assertRaises(ValueError): response.data = None def test_validation_id(self): response = JSONRPC10Response(**self.response_success_params) self.assertEqual(response._id, self.response_success_params["_id"]) json-rpc-1.13.0/jsonrpc/tests/test_jsonrpc2.py000066400000000000000000000554121360512042700213270ustar00rootroot00000000000000import json import sys from ..exceptions import JSONRPCInvalidRequestException from ..jsonrpc2 import ( JSONRPC20Request, JSONRPC20BatchRequest, JSONRPC20Response, JSONRPC20BatchResponse, ) if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestJSONRPC20Request(unittest.TestCase): """ Test JSONRPC20Request functionality.""" def setUp(self): self.request_params = { "method": "add", "params": [1, 2], "_id": 1, } def test_correct_init(self): """ Test object is created.""" JSONRPC20Request(**self.request_params) def test_validation_incorrect_no_parameters(self): with self.assertRaises(ValueError): JSONRPC20Request() def test_method_validation_str(self): self.request_params.update({"method": "add"}) JSONRPC20Request(**self.request_params) def test_method_validation_not_str(self): self.request_params.update({"method": []}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) self.request_params.update({"method": {}}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) def test_method_validation_str_rpc_prefix(self): """ Test method SHOULD NOT starts with rpc. """ self.request_params.update({"method": "rpc."}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) self.request_params.update({"method": "rpc.test"}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) self.request_params.update({"method": "rpccorrect"}) JSONRPC20Request(**self.request_params) self.request_params.update({"method": "rpc"}) JSONRPC20Request(**self.request_params) def test_params_validation_list(self): self.request_params.update({"params": []}) JSONRPC20Request(**self.request_params) self.request_params.update({"params": [0]}) JSONRPC20Request(**self.request_params) def test_params_validation_tuple(self): self.request_params.update({"params": ()}) JSONRPC20Request(**self.request_params) self.request_params.update({"params": tuple([0])}) JSONRPC20Request(**self.request_params) def test_params_validation_dict(self): self.request_params.update({"params": {}}) JSONRPC20Request(**self.request_params) self.request_params.update({"params": {"a": 0}}) JSONRPC20Request(**self.request_params) def test_params_validation_none(self): self.request_params.update({"params": None}) JSONRPC20Request(**self.request_params) def test_params_validation_incorrect(self): self.request_params.update({"params": "str"}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) def test_request_args(self): self.assertEqual(JSONRPC20Request("add").args, ()) self.assertEqual(JSONRPC20Request("add", []).args, ()) self.assertEqual(JSONRPC20Request("add", {"a": 1}).args, ()) self.assertEqual(JSONRPC20Request("add", [1, 2]).args, (1, 2)) def test_request_kwargs(self): self.assertEqual(JSONRPC20Request("add").kwargs, {}) self.assertEqual(JSONRPC20Request("add", [1, 2]).kwargs, {}) self.assertEqual(JSONRPC20Request("add", {}).kwargs, {}) self.assertEqual(JSONRPC20Request("add", {"a": 1}).kwargs, {"a": 1}) def test_id_validation_string(self): self.request_params.update({"_id": "id"}) JSONRPC20Request(**self.request_params) def test_id_validation_int(self): self.request_params.update({"_id": 0}) JSONRPC20Request(**self.request_params) def test_id_validation_null(self): self.request_params.update({"_id": "null"}) JSONRPC20Request(**self.request_params) def test_id_validation_none(self): self.request_params.update({"_id": None}) JSONRPC20Request(**self.request_params) def test_id_validation_float(self): self.request_params.update({"_id": 0.1}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) def test_id_validation_incorrect(self): self.request_params.update({"_id": []}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) self.request_params.update({"_id": ()}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) def test_data_method_1(self): r = JSONRPC20Request("add") self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": None, }) def test_data_method_2(self): r = JSONRPC20Request(method="add") self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": None, }) def test_data_method_3(self): r = JSONRPC20Request("add", None) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": None, }) def test_data_params_1(self): r = JSONRPC20Request("add", params=None, _id=None) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": None, }) def test_data_params_2(self): r = JSONRPC20Request("add", []) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "params": [], "id": None, }) def test_data_params_3(self): r = JSONRPC20Request("add", ()) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "params": [], "id": None, }) def test_data_params_4(self): r = JSONRPC20Request("add", (1, 2)) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "params": [1, 2], "id": None, }) def test_data_params_5(self): r = JSONRPC20Request("add", {"a": 0}) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "params": {"a": 0}, "id": None, }) def test_data_id_1(self): r = JSONRPC20Request("add", _id="null") self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": "null", }) def test_data_id_1_notification(self): r = JSONRPC20Request("add", _id="null", is_notification=True) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", }) def test_data_id_2(self): r = JSONRPC20Request("add", _id=None) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": None, }) def test_data_id_2_notification(self): r = JSONRPC20Request("add", _id=None, is_notification=True) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", }) def test_data_id_3(self): r = JSONRPC20Request("add", _id="id") self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": "id", }) def test_data_id_3_notification(self): r = JSONRPC20Request("add", _id="id", is_notification=True) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", }) def test_data_id_4(self): r = JSONRPC20Request("add", _id=0) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", "id": 0, }) def test_data_id_4_notification(self): r = JSONRPC20Request("add", _id=0, is_notification=True) self.assertEqual(r.data, { "jsonrpc": "2.0", "method": "add", }) def test_is_notification(self): r = JSONRPC20Request("add") self.assertFalse(r.is_notification) r = JSONRPC20Request("add", _id=None) self.assertFalse(r.is_notification) r = JSONRPC20Request("add", _id="null") self.assertFalse(r.is_notification) r = JSONRPC20Request("add", _id=0) self.assertFalse(r.is_notification) r = JSONRPC20Request("add", is_notification=True) self.assertTrue(r.is_notification) r = JSONRPC20Request("add", is_notification=True, _id=None) self.assertTrue(r.is_notification) self.assertNotIn("id", r.data) r = JSONRPC20Request("add", is_notification=True, _id=0) self.assertTrue(r.is_notification) self.assertNotIn("id", r.data) def test_set_unset_notification_keep_id(self): r = JSONRPC20Request("add", is_notification=True, _id=0) self.assertTrue(r.is_notification) self.assertFalse("id" in r.data) r.is_notification = False self.assertFalse(r.is_notification) self.assertTrue("id" in r.data) self.assertEqual(r.data["id"], 0) def test_serialize_method_1(self): r = JSONRPC20Request("add") self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": None, }, json.loads(r.json)) def test_serialize_method_2(self): r = JSONRPC20Request(method="add") self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": None, }, json.loads(r.json)) def test_serialize_method_3(self): r = JSONRPC20Request("add", None) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": None, }, json.loads(r.json)) def test_serialize_params_1(self): r = JSONRPC20Request("add", params=None, _id=None) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": None, }, json.loads(r.json)) def test_serialize_params_2(self): r = JSONRPC20Request("add", []) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "params": [], "id": None, }, json.loads(r.json)) def test_serialize_params_3(self): r = JSONRPC20Request("add", ()) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "params": [], "id": None, }, json.loads(r.json)) def test_serialize_params_4(self): r = JSONRPC20Request("add", (1, 2)) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "params": [1, 2], "id": None, }, json.loads(r.json)) def test_serialize_params_5(self): r = JSONRPC20Request("add", {"a": 0}) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "params": {"a": 0}, "id": None, }, json.loads(r.json)) def test_serialize_id_1(self): r = JSONRPC20Request("add", _id="null") self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": "null", }, json.loads(r.json)) def test_serialize_id_2(self): r = JSONRPC20Request("add", _id=None) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": None, }, json.loads(r.json)) def test_serialize_id_3(self): r = JSONRPC20Request("add", _id="id") self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": "id", }, json.loads(r.json)) def test_serialize_id_4(self): r = JSONRPC20Request("add", _id=0) self.assertTrue({ "jsonrpc": "2.0", "method": "add", "id": 0, }, json.loads(r.json)) def test_from_json_request_no_id(self): str_json = json.dumps({ "method": "add", "params": [1, 2], "jsonrpc": "2.0", }) request = JSONRPC20Request.from_json(str_json) self.assertTrue(isinstance(request, JSONRPC20Request)) self.assertEqual(request.method, "add") self.assertEqual(request.params, [1, 2]) self.assertEqual(request._id, None) self.assertTrue(request.is_notification) def test_from_json_request_no_params(self): str_json = json.dumps({ "method": "add", "jsonrpc": "2.0", }) request = JSONRPC20Request.from_json(str_json) self.assertTrue(isinstance(request, JSONRPC20Request)) self.assertEqual(request.method, "add") self.assertEqual(request.params, None) self.assertEqual(request._id, None) self.assertTrue(request.is_notification) def test_from_json_request_null_id(self): str_json = json.dumps({ "method": "add", "jsonrpc": "2.0", "id": None, }) request = JSONRPC20Request.from_json(str_json) self.assertTrue(isinstance(request, JSONRPC20Request)) self.assertEqual(request.method, "add") self.assertEqual(request.params, None) self.assertEqual(request._id, None) self.assertFalse(request.is_notification) def test_from_json_request(self): str_json = json.dumps({ "method": "add", "params": [0, 1], "jsonrpc": "2.0", "id": "id", }) request = JSONRPC20Request.from_json(str_json) self.assertTrue(isinstance(request, JSONRPC20Request)) self.assertEqual(request.method, "add") self.assertEqual(request.params, [0, 1]) self.assertEqual(request._id, "id") self.assertFalse(request.is_notification) def test_from_json_invalid_request_jsonrpc(self): str_json = json.dumps({ "method": "add", }) with self.assertRaises(JSONRPCInvalidRequestException): JSONRPC20Request.from_json(str_json) def test_from_json_invalid_request_method(self): str_json = json.dumps({ "jsonrpc": "2.0", }) with self.assertRaises(JSONRPCInvalidRequestException): JSONRPC20Request.from_json(str_json) def test_from_json_invalid_request_extra_data(self): str_json = json.dumps({ "jsonrpc": "2.0", "method": "add", "is_notification": True, }) with self.assertRaises(JSONRPCInvalidRequestException): JSONRPC20Request.from_json(str_json) def test_data_setter(self): request = JSONRPC20Request(**self.request_params) with self.assertRaises(ValueError): request.data = [] with self.assertRaises(ValueError): request.data = "" with self.assertRaises(ValueError): request.data = None class TestJSONRPC20BatchRequest(unittest.TestCase): """ Test JSONRPC20BatchRequest functionality.""" def test_batch_request(self): request = JSONRPC20BatchRequest( JSONRPC20Request("devide", {"num": 1, "denom": 2}, _id=1), JSONRPC20Request("devide", {"num": 3, "denom": 2}, _id=2), ) self.assertEqual(json.loads(request.json), [ {"method": "devide", "params": {"num": 1, "denom": 2}, "id": 1, "jsonrpc": "2.0"}, {"method": "devide", "params": {"num": 3, "denom": 2}, "id": 2, "jsonrpc": "2.0"}, ]) def test_from_json_batch(self): str_json = json.dumps([ {"method": "add", "params": [1, 2], "jsonrpc": "2.0"}, {"method": "mul", "params": [1, 2], "jsonrpc": "2.0"}, ]) requests = JSONRPC20BatchRequest.from_json(str_json) self.assertTrue(isinstance(requests, JSONRPC20BatchRequest)) for r in requests: self.assertTrue(isinstance(r, JSONRPC20Request)) self.assertTrue(r.method in ["add", "mul"]) self.assertEqual(r.params, [1, 2]) self.assertEqual(r._id, None) self.assertTrue(r.is_notification) def test_from_json_batch_one(self): str_json = json.dumps([ {"method": "add", "params": [1, 2], "jsonrpc": "2.0", "id": None}, ]) requests = JSONRPC20Request.from_json(str_json) self.assertTrue(isinstance(requests, JSONRPC20BatchRequest)) requests = list(requests) self.assertEqual(len(requests), 1) r = requests[0] self.assertTrue(isinstance(r, JSONRPC20Request)) self.assertEqual(r.method, "add") self.assertEqual(r.params, [1, 2]) self.assertEqual(r._id, None) self.assertFalse(r.is_notification) def test_response_iterator(self): requests = JSONRPC20BatchRequest( JSONRPC20Request("devide", {"num": 1, "denom": 2}, _id=1), JSONRPC20Request("devide", {"num": 3, "denom": 2}, _id=2), ) for request in requests: self.assertTrue(isinstance(request, JSONRPC20Request)) self.assertEqual(request.method, "devide") class TestJSONRPC20Response(unittest.TestCase): """ Test JSONRPC20Response functionality.""" def setUp(self): self.response_success_params = { "result": "", "_id": 1, } self.response_error_params = { "error": { "code": 1, "message": "error", }, "_id": 1, } def test_correct_init(self): """ Test object is created.""" JSONRPC20Response(**self.response_success_params) def test_validation_incorrect_no_parameters(self): with self.assertRaises(ValueError): JSONRPC20Response() def test_validation_incorrect_result_and_error(self): response = JSONRPC20Response(error={"code": 1, "message": ""}) with self.assertRaises(ValueError): response.result = "" def test_validation_error_correct(self): JSONRPC20Response(**self.response_error_params) def test_validation_error_incorrect(self): self.response_error_params["error"].update({"code": "str"}) with self.assertRaises(ValueError): JSONRPC20Response(**self.response_error_params) def test_validation_error_incorrect_no_code(self): del self.response_error_params["error"]["code"] with self.assertRaises(ValueError): JSONRPC20Response(**self.response_error_params) def test_validation_error_incorrect_no_message(self): del self.response_error_params["error"]["message"] with self.assertRaises(ValueError): JSONRPC20Response(**self.response_error_params) def test_validation_error_incorrect_message_not_str(self): self.response_error_params["error"].update({"message": 0}) with self.assertRaises(ValueError): JSONRPC20Response(**self.response_error_params) def test_validation_id(self): response = JSONRPC20Response(**self.response_success_params) self.assertEqual(response._id, self.response_success_params["_id"]) def test_validation_id_incorrect_type(self): response = JSONRPC20Response(**self.response_success_params) with self.assertRaises(ValueError): response._id = [] with self.assertRaises(ValueError): response._id = {} with self.assertRaises(ValueError): response._id = 0.1 def test_data_result(self): r = JSONRPC20Response(result="") self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "jsonrpc": "2.0", "result": "", "id": None, }) def test_data_result_id_none(self): r = JSONRPC20Response(result="", _id=None) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "jsonrpc": "2.0", "result": "", "id": None, }) def test_data_result_id(self): r = JSONRPC20Response(result="", _id=0) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "jsonrpc": "2.0", "result": "", "id": 0, }) def test_data_error(self): r = JSONRPC20Response(error={"code": 0, "message": ""}) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "jsonrpc": "2.0", "error": { "code": 0, "message": "", }, "id": None, }) def test_data_error_id_none(self): r = JSONRPC20Response(error={"code": 0, "message": ""}, _id=None) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "jsonrpc": "2.0", "error": { "code": 0, "message": "", }, "id": None, }) def test_data_error_id(self): r = JSONRPC20Response(error={"code": 0, "message": ""}, _id=0) self.assertEqual(json.loads(r.json), r.data) self.assertEqual(r.data, { "jsonrpc": "2.0", "error": { "code": 0, "message": "", }, "id": 0, }) def test_data_setter(self): response = JSONRPC20Response(**self.response_success_params) with self.assertRaises(ValueError): response.data = [] with self.assertRaises(ValueError): response.data = "" with self.assertRaises(ValueError): response.data = None class TestJSONRPC20BatchResponse(unittest.TestCase): """ Test JSONRPC20BatchResponse functionality.""" def test_batch_response(self): response = JSONRPC20BatchResponse( JSONRPC20Response(result="result", _id=1), JSONRPC20Response(error={"code": 0, "message": ""}, _id=2), ) self.assertEqual(json.loads(response.json), [ {"result": "result", "id": 1, "jsonrpc": "2.0"}, {"error": {"code": 0, "message": ""}, "id": 2, "jsonrpc": "2.0"}, ]) def test_response_iterator(self): responses = JSONRPC20BatchResponse( JSONRPC20Response(result="result", _id=1), JSONRPC20Response(result="result", _id=2), ) for response in responses: self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.result, "result") def test_batch_response_data(self): response = JSONRPC20BatchResponse( JSONRPC20Response(result="result", _id=1), JSONRPC20Response(result="result", _id=2), JSONRPC20Response(result="result"), ) self.assertEqual(response.data, [ {"id": 1, "jsonrpc": "2.0", "result": "result"}, {"id": 2, "jsonrpc": "2.0", "result": "result"}, {"id": None, "jsonrpc": "2.0", "result": "result"}, ]) json-rpc-1.13.0/jsonrpc/tests/test_jsonrpc_errors.py000066400000000000000000000110401360512042700226260ustar00rootroot00000000000000import json import sys from ..exceptions import ( JSONRPCError, JSONRPCInternalError, JSONRPCInvalidParams, JSONRPCInvalidRequest, JSONRPCMethodNotFound, JSONRPCParseError, JSONRPCServerError, JSONRPCDispatchException, ) if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestJSONRPCError(unittest.TestCase): def setUp(self): self.error_params = { "code": 0, "message": "", } def test_correct_init(self): """ Test object is created.""" JSONRPCError(**self.error_params) def test_validation_incorrect_no_parameters(self): with self.assertRaises(ValueError): JSONRPCError() def test_code_validation_int(self): self.error_params.update({"code": 32000}) JSONRPCError(**self.error_params) def test_code_validation_no_code(self): del self.error_params["code"] with self.assertRaises(ValueError): JSONRPCError(**self.error_params) def test_code_validation_str(self): self.error_params.update({"code": "0"}) with self.assertRaises(ValueError): JSONRPCError(**self.error_params) def test_message_validation_str(self): self.error_params.update({"message": ""}) JSONRPCError(**self.error_params) def test_message_validation_none(self): del self.error_params["message"] with self.assertRaises(ValueError): JSONRPCError(**self.error_params) def test_message_validation_int(self): self.error_params.update({"message": 0}) with self.assertRaises(ValueError): JSONRPCError(**self.error_params) def test_data_validation_none(self): self.error_params.update({"data": None}) JSONRPCError(**self.error_params) def test_data_validation(self): self.error_params.update({"data": {}}) JSONRPCError(**self.error_params) self.error_params.update({"data": ""}) JSONRPCError(**self.error_params) def test_json(self): error = JSONRPCError(**self.error_params) self.assertEqual( json.loads(error.json), self.error_params, ) def test_from_json(self): str_json = json.dumps({ "code": 0, "message": "", "data": {}, }) request = JSONRPCError.from_json(str_json) self.assertTrue(isinstance(request, JSONRPCError)) self.assertEqual(request.code, 0) self.assertEqual(request.message, "") self.assertEqual(request.data, {}) class TestJSONRPCParseError(unittest.TestCase): def test_code_message(self): error = JSONRPCParseError() self.assertEqual(error.code, -32700) self.assertEqual(error.message, "Parse error") self.assertEqual(error.data, None) class TestJSONRPCServerError(unittest.TestCase): def test_code_message(self): error = JSONRPCServerError() self.assertEqual(error.code, -32000) self.assertEqual(error.message, "Server error") self.assertEqual(error.data, None) class TestJSONRPCInternalError(unittest.TestCase): def test_code_message(self): error = JSONRPCInternalError() self.assertEqual(error.code, -32603) self.assertEqual(error.message, "Internal error") self.assertEqual(error.data, None) class TestJSONRPCInvalidParams(unittest.TestCase): def test_code_message(self): error = JSONRPCInvalidParams() self.assertEqual(error.code, -32602) self.assertEqual(error.message, "Invalid params") self.assertEqual(error.data, None) class TestJSONRPCInvalidRequest(unittest.TestCase): def test_code_message(self): error = JSONRPCInvalidRequest() self.assertEqual(error.code, -32600) self.assertEqual(error.message, "Invalid Request") self.assertEqual(error.data, None) class TestJSONRPCMethodNotFound(unittest.TestCase): def test_code_message(self): error = JSONRPCMethodNotFound() self.assertEqual(error.code, -32601) self.assertEqual(error.message, "Method not found") self.assertEqual(error.data, None) class TestJSONRPCDispatchException(unittest.TestCase): def test_code_message(self): error = JSONRPCDispatchException(message="message", code=400, data={"param": 1}) self.assertEqual(error.error.code, 400) self.assertEqual(error.error.message, "message") self.assertEqual(error.error.data, {"param": 1}) json-rpc-1.13.0/jsonrpc/tests/test_manager.py000066400000000000000000000202351360512042700211740ustar00rootroot00000000000000import sys from ..manager import JSONRPCResponseManager from ..jsonrpc2 import ( JSONRPC20BatchRequest, JSONRPC20BatchResponse, JSONRPC20Request, JSONRPC20Response, ) from ..jsonrpc1 import JSONRPC10Request, JSONRPC10Response from ..exceptions import JSONRPCDispatchException if sys.version_info < (3, 3): from mock import MagicMock else: from unittest.mock import MagicMock if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestJSONRPCResponseManager(unittest.TestCase): def setUp(self): def raise_(e): raise e self.long_time_method = MagicMock() self.dispatcher = { "add": sum, "multiply": lambda a, b: a * b, "list_len": len, "101_base": lambda **kwargs: int("101", **kwargs), "error": lambda: raise_(KeyError("error_explanation")), "type_error": lambda: raise_(TypeError("TypeError inside method")), "long_time_method": self.long_time_method, "dispatch_error": lambda x: raise_( JSONRPCDispatchException(code=4000, message="error", data={"param": 1})), } def test_dispatch_error(self): request = JSONRPC20Request("dispatch_error", ["test"], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "error") self.assertEqual(response.error["code"], 4000) self.assertEqual(response.error["data"], {"param": 1}) def test_returned_type_response(self): request = JSONRPC20Request("add", [[]], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) def test_returned_type_butch_response(self): request = JSONRPC20BatchRequest( JSONRPC20Request("add", [[]], _id=0)) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20BatchResponse)) def test_returned_type_response_rpc10(self): request = JSONRPC10Request("add", [[]], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC10Response)) def test_parse_error(self): req = '{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Parse error") self.assertEqual(response.error["code"], -32700) def test_invalid_request(self): req = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}' response = JSONRPCResponseManager.handle(req, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid Request") self.assertEqual(response.error["code"], -32600) def test_method_not_found(self): request = JSONRPC20Request("does_not_exist", [[]], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Method not found") self.assertEqual(response.error["code"], -32601) def test_invalid_params(self): request = JSONRPC20Request("add", {"a": 0}, _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) self.assertIn(response.error["data"]["message"], [ 'sum() takes no keyword arguments', "sum() got an unexpected keyword argument 'a'", 'sum() takes at least 1 positional argument (0 given)', ]) def test_invalid_params_custom_function(self): request = JSONRPC20Request("multiply", [0], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) request = JSONRPC20Request("multiply", [0, 1, 2], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) request = JSONRPC20Request("multiply", {"a": 1}, _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) request = JSONRPC20Request("multiply", {"a": 1, "b": 2, "c": 3}, _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) def test_server_error(self): request = JSONRPC20Request("error", _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Server error") self.assertEqual(response.error["code"], -32000) self.assertEqual(response.error["data"]['type'], "KeyError") self.assertEqual( response.error["data"]['args'], ('error_explanation',)) self.assertEqual( response.error["data"]['message'], "'error_explanation'") def test_notification_calls_method(self): request = JSONRPC20Request("long_time_method", is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) self.long_time_method.assert_called_once_with() def test_notification_does_not_return_error_does_not_exist(self): request = JSONRPC20Request("does_not_exist", is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) def test_notification_does_not_return_error_invalid_params(self): request = JSONRPC20Request("add", {"a": 0}, is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) def test_notification_does_not_return_error(self): request = JSONRPC20Request("error", is_notification=True) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertEqual(response, None) def test_type_error_inside_method(self): request = JSONRPC20Request("type_error", _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Server error") self.assertEqual(response.error["code"], -32000) self.assertEqual(response.error["data"]['type'], "TypeError") self.assertEqual( response.error["data"]['args'], ('TypeError inside method',)) self.assertEqual( response.error["data"]['message'], 'TypeError inside method') def test_invalid_params_before_dispatcher_error(self): request = JSONRPC20Request( "dispatch_error", ["invalid", "params"], _id=0) response = JSONRPCResponseManager.handle(request.json, self.dispatcher) self.assertTrue(isinstance(response, JSONRPC20Response)) self.assertEqual(response.error["message"], "Invalid params") self.assertEqual(response.error["code"], -32602) json-rpc-1.13.0/jsonrpc/tests/test_pep3107.py000066400000000000000000000016131360512042700206600ustar00rootroot00000000000000from ..manager import JSONRPCResponseManager import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestJSONRPCResponseManager(unittest.TestCase): @unittest.skipIf(sys.version_info < (3, 5), "Test Py3.5+ functionality") def test_typeerror_with_annotations(self): """If a function has Python3 annotations and is called with improper arguments, make sure the framework doesn't fail with inspect.getargspec """ from .py35_utils import distance dispatcher = { "distance": distance, } req = '{"jsonrpc": "2.0", "method": "distance", "params": [], "id": 1}' result = JSONRPCResponseManager.handle(req, dispatcher) # Make sure this returns JSONRPCInvalidParams rather than raising # UnboundLocalError self.assertEqual(result.error['code'], -32602) json-rpc-1.13.0/jsonrpc/tests/test_utils.py000066400000000000000000000076601360512042700207310ustar00rootroot00000000000000""" Test utility functionality.""" from ..utils import JSONSerializable, DatetimeDecimalEncoder, is_invalid_params import datetime import decimal import json import sys if sys.version_info < (3, 3): from mock import patch else: from unittest.mock import patch if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestJSONSerializable(unittest.TestCase): """ Test JSONSerializable functionality.""" def setUp(self): class A(JSONSerializable): @property def json(self): pass self._class = A def test_abstract_class(self): with self.assertRaises(TypeError): JSONSerializable() self._class() def test_definse_serialize_deserialize(self): """ Test classmethods of inherited class.""" self.assertEqual(self._class.serialize({}), "{}") self.assertEqual(self._class.deserialize("{}"), {}) def test_from_json(self): self.assertTrue(isinstance(self._class.from_json('{}'), self._class)) def test_from_json_incorrect(self): with self.assertRaises(ValueError): self._class.from_json('[]') class TestDatetimeDecimalEncoder(unittest.TestCase): """ Test DatetimeDecimalEncoder functionality.""" def test_date_encoder(self): obj = datetime.date.today() with self.assertRaises(TypeError): json.dumps(obj) self.assertEqual( json.dumps(obj, cls=DatetimeDecimalEncoder), '"{0}"'.format(obj.isoformat()), ) def test_datetime_encoder(self): obj = datetime.datetime.now() with self.assertRaises(TypeError): json.dumps(obj) self.assertEqual( json.dumps(obj, cls=DatetimeDecimalEncoder), '"{0}"'.format(obj.isoformat()), ) def test_decimal_encoder(self): obj = decimal.Decimal('0.1') with self.assertRaises(TypeError): json.dumps(obj) result = json.dumps(obj, cls=DatetimeDecimalEncoder) self.assertTrue(isinstance(result, str)) self.assertEqual(float(result), float(0.1)) def test_default(self): encoder = DatetimeDecimalEncoder() with patch.object(json.JSONEncoder, 'default') as json_default: encoder.default("") self.assertEqual(json_default.call_count, 1) class TestUtils(unittest.TestCase): """ Test utils functions.""" def test_is_invalid_params_builtin(self): self.assertTrue(is_invalid_params(sum, 0, 0)) # NOTE: builtin functions could not be recognized by inspect.isfunction # It would raise TypeError if parameters are incorrect already. # self.assertFalse(is_invalid_params(sum, [0, 0])) # <- fails def test_is_invalid_params_args(self): self.assertTrue(is_invalid_params(lambda a, b: None, 0)) self.assertTrue(is_invalid_params(lambda a, b: None, 0, 1, 2)) def test_is_invalid_params_kwargs(self): self.assertTrue(is_invalid_params(lambda a: None, **{})) self.assertTrue(is_invalid_params(lambda a: None, **{"a": 0, "b": 1})) def test_invalid_params_correct(self): self.assertFalse(is_invalid_params(lambda: None)) self.assertFalse(is_invalid_params(lambda a: None, 0)) self.assertFalse(is_invalid_params(lambda a, b=0: None, 0)) self.assertFalse(is_invalid_params(lambda a, b=0: None, 0, 0)) def test_is_invalid_params_mixed(self): self.assertFalse(is_invalid_params(lambda a, b: None, 0, **{"b": 1})) self.assertFalse(is_invalid_params( lambda a, b, c=0: None, 0, **{"b": 1})) def test_is_invalid_params_py2(self): with patch('jsonrpc.utils.sys') as mock_sys: mock_sys.version_info = (2, 7) with patch('jsonrpc.utils.is_invalid_params_py2') as mock_func: is_invalid_params(lambda a: None, 0) assert mock_func.call_count == 1 json-rpc-1.13.0/jsonrpc/utils.py000066400000000000000000000075651360512042700165340ustar00rootroot00000000000000""" Utility functions for package.""" from abc import ABCMeta, abstractmethod import datetime import decimal import inspect import json import sys from . import six class JSONSerializable(six.with_metaclass(ABCMeta, object)): """ Common functionality for json serializable objects.""" serialize = staticmethod(json.dumps) deserialize = staticmethod(json.loads) @abstractmethod def json(self): raise NotImplementedError() @classmethod def from_json(cls, json_str): data = cls.deserialize(json_str) if not isinstance(data, dict): raise ValueError("data should be dict") return cls(**data) class DatetimeDecimalEncoder(json.JSONEncoder): """ Encoder for datetime and decimal serialization. Usage: json.dumps(object, cls=DatetimeDecimalEncoder) NOTE: _iterencode does not work """ def default(self, o): """ Encode JSON. :return str: A JSON encoded string """ if isinstance(o, decimal.Decimal): return float(o) if isinstance(o, (datetime.datetime, datetime.date)): return o.isoformat() return json.JSONEncoder.default(self, o) def is_invalid_params_py2(func, *args, **kwargs): """ Check, whether function 'func' accepts parameters 'args', 'kwargs'. NOTE: Method is called after funct(*args, **kwargs) generated TypeError, it is aimed to destinguish TypeError because of invalid parameters from TypeError from inside the function. .. versionadded: 1.9.0 """ funcargs, varargs, varkwargs, defaults = inspect.getargspec(func) unexpected = set(kwargs.keys()) - set(funcargs) if len(unexpected) > 0: return True params = [funcarg for funcarg in funcargs if funcarg not in kwargs] funcargs_required = funcargs[:-len(defaults)] \ if defaults is not None \ else funcargs params_required = [ funcarg for funcarg in funcargs_required if funcarg not in kwargs ] return not (len(params_required) <= len(args) <= len(params)) def is_invalid_params_py3(func, *args, **kwargs): """ Use inspect.signature instead of inspect.getargspec or inspect.getfullargspec (based on inspect.signature itself) as it provides more information about function parameters. .. versionadded: 1.11.2 """ signature = inspect.signature(func) parameters = signature.parameters unexpected = set(kwargs.keys()) - set(parameters.keys()) if len(unexpected) > 0: return True params = [ parameter for name, parameter in parameters.items() if name not in kwargs ] params_required = [ param for param in params if param.default is param.empty ] return not (len(params_required) <= len(args) <= len(params)) def is_invalid_params(func, *args, **kwargs): """ Method: Validate pre-defined criteria, if any is True - function is invalid 0. func should be callable 1. kwargs should not have unexpected keywords 2. remove kwargs.keys from func.parameters 3. number of args should be <= remaining func.parameters 4. number of args should be >= remaining func.parameters less default """ # For builtin functions inspect.getargspec(funct) return error. If builtin # function generates TypeError, it is because of wrong parameters. if not inspect.isfunction(func): return True if sys.version_info >= (3, 3): return is_invalid_params_py3(func, *args, **kwargs) else: # NOTE: use Python2 method for Python 3.2 as well. Starting from Python # 3.3 it is recommended to use inspect.signature instead. # In Python 3.0 - 3.2 inspect.getfullargspec is preferred but these # versions are almost not supported. Users should consider upgrading. return is_invalid_params_py2(func, *args, **kwargs) json-rpc-1.13.0/setup.cfg000066400000000000000000000001321360512042700151440ustar00rootroot00000000000000[aliases] test=pytest [bdist_wheel] universal = 1 [metadata] license_file = LICENSE.txt json-rpc-1.13.0/setup.py000066400000000000000000000031011360512042700150340ustar00rootroot00000000000000#!/usr/bin/env python import os.path import sys from setuptools import setup, find_packages from jsonrpc import version def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return "" setup_requires = ["pytest-runner"] if sys.argv in ['pytest', 'test'] else [] setup( name="json-rpc", version=version, packages=find_packages(), setup_requires=setup_requires, tests_require=["pytest"], # metadata for upload to PyPI author="Kirill Pavlov", author_email="k@p99.io", url="https://github.com/pavlov99/json-rpc", description="JSON-RPC transport implementation", long_description=read('README.rst'), # Full list: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", ], license="MIT", ) json-rpc-1.13.0/tox.ini000066400000000000000000000025461360512042700146510ustar00rootroot00000000000000[tox] envlist = py{26, 27, 33, 34, 35, 36, 37, 38}, pypy, pypy3, pycodestyle, cov [testenv] commands = pytest setenv = DJANGO_SETTINGS_MODULE=jsonrpc.tests.test_backend_django.settings deps = pytest==5.2.2 Django==2.2.7 Flask==1.1.1 # Python 2.6 configuration. Latest Django support is 1.6 [testenv:py26] deps = pytest==4.0.2 attrs==19.1.0 Django==1.6 Flask==0.12.2 mock==2.0.0 unittest2==1.1.0 # Python 2.7 configuration. # Django 1.11 is likely to be the last version to support Python 2.7 # https://www.djangoproject.com/weblog/2015/jun/25/roadmap/ [testenv:py27] deps = pytest==4.0.2 attrs==19.1.0 mock==2.0.0 Django==1.11 Flask==0.12.2 [testenv:py33] deps = pytest==4.0.2 attrs==19.1.0 Django==1.11 Flask==0.12.2 [testenv:py34] deps = pytest==4.0.2 attrs==19.1.0 Django==1.11 Flask==0.12.2 [testenv:pypy] deps = pytest==4.0.2 attrs==19.1.0 mock==2.0.0 Django==1.11 Flask==0.12.2 [testenv:pycodestyle] deps = pycodestyle commands = pycodestyle setup.py jsonrpc --exclude=jsonrpc/six.py --show-source --show-pep8 [testenv:pylama] deps = pylama==1.5.4 commands = pylama --linters=pep8,pep257,mccabe,pyflakes,pylint jsonrpc [testenv:cov] deps = {[testenv]deps} coverage==4.5.2 codecov==2.0.15 commands = coverage run -m pytest coverage report