Jean-Tiare Le Bigot avatar Jean-Tiare Le Bigot committed c18ee8f

add documentation

Comments (0)

Files changed (16)

 This section documents all user visible changes included between Onctuous
 versions 0.5.0 and Onctuous versions 0.5.1
 
+Additions
+---------
+
+- official documentation
+
 Changes
 -------
 
-Onctuous is a Python data validation library
-==============================================
+Onctuous -- a Python data validation library
 
-This Code was originally written by Alec Thomas <alec@swapoff.org> under the name
-'Voluptuous'. This fork brings many improvements and maintenance :)
+Presentation
+============
 
-Onctuous, *despite* the name, is a Python data validation library. It is
-primarily intended for validating data coming into Python as JSON, YAML,
-etc.
+**Onctuous** is a fluid and pleasing to use validation tool you will love to
+use. Originally based on `Voluptuous <https://github.com/alecthomas/voluptuous>`_
+code by Alec Thomas <alec@swapoff.org>, we first fixed long outstanding issues
+like Python builtins collision and added support for default values.
 
-It has three goals:
+The goal of **Onctuous** is to make it simple and smooth.
+ - You *can* write your own validators
+ - You *can* specify defaults. The best ? They are *not* required to pass validation themselves
+ - You *can* write readable code. This is not based on json schema specification, on purpose
 
-1. Simplicity.
-2. Support for complex data structures.
-3. Provide useful error messages.
+ You can use Onctuous to validate ``list``, ``scalar`` (regular variables) or
+``dict``. For this purpose, you will need to define a so-called ``Schema`` and
+call the Schema with the input to validate. In case of success, it will return
+the validated input, possibly filtered or edited according to your rules
 
-.. contents:: Table of Contents
+Installation
+============
 
-Show me an example
-------------------
-Twitter's `user search API
-<http://apiwiki.twitter.com/Twitter-REST-API-Method:-users-search>`_ accepts
-query URLs like::
+::
 
-  $ curl 'http://api.twitter.com/1/users/search.json?q=python&per_page=20&page=1
+    $ pip install onctuous
 
-To validate this we might use a schema like::
 
-  >>> from onctuous import Schema
-  >>> schema = Schema({
-  ...   'q': str,
-  ...   'per_page': int,
-  ...   'page': int,
-  ... })
+Developing
+==========
 
-This schema very succinctly and roughly describes the data required by the API,
-and will work fine. But it has a few problems. Firstly, it doesn't fully
-express the constraints of the API. According to the API, ``per_page`` should
-be restricted to at most 20, for example. To describe the semantics of the API
-more accurately, our schema will need to be more thoroughly defined::
+::
 
-  >>> from onctuous import required, all, length, range
-  >>> schema = Schema({
-  ...   required('q'): all(str, length(min=1)),
-  ...   'per_page': all(int, range(min=1, max=20)),
-  ...   'page': all(int, range(min=0)),
-  ... })
-
-This schema fully enforces the interface defined in Twitter's documentation,
-and goes a little further for completeness.
-
-"q" is required::
-
-  >>> schema({})
-  Traceback (most recent call last):
-  ...
-  InvalidList: required key not provided @ data['q']
-
-...must be a string::
-
-  >>> schema({'q': 123})
-  Traceback (most recent call last):
-  ...
-  InvalidList: expected str for dictionary value @ data['q']
-
-...and must be at least one character in length::
-
-  >>> schema({'q': ''})
-  Traceback (most recent call last):
-  ...
-  InvalidList: length of value must be at least 1 for dictionary value @ data['q']
-  >>> schema({'q': '#topic'})
-  {'q': '#topic'}
-
-"per_page" is a positive integer no greater than 20::
-
-  >>> schema({'q': '#topic', 'per_page': 900})
-  Traceback (most recent call last):
-  ...
-  InvalidList: value must be at most 20 for dictionary value @ data['per_page']
-  >>> schema({'q': '#topic', 'per_page': -10})
-  Traceback (most recent call last):
-  ...
-  InvalidList: value must be at least 1 for dictionary value @ data['per_page']
-
-"page" is an integer >= 0::
-
-  >>> schema({'q': '#topic', 'page': 'one'})
-  Traceback (most recent call last):
-  ...
-  InvalidList: expected int for dictionary value @ data['page']
-  >>> schema({'q': '#topic', 'page': 1})
-  {'q': '#topic', 'page': 1}
-
-Defining schemas
-----------------
-Schemas are nested data structures consisting of dictionaries, lists,
-scalars and *validators*. Each node in the input schema is pattern matched
-against corresponding nodes in the input data.
-
-Literals
-~~~~~~~~
-Literals in the schema are matched using normal equality checks::
-
-  >>> schema = Schema(1)
-  >>> schema(1)
-  1
-  >>> schema = Schema('a string')
-  >>> schema('a string')
-  'a string'
-
-Types
-~~~~~
-Types in the schema are matched by checking if the corresponding value is an
-instance of the type::
-
-  >>> schema = Schema(int)
-  >>> schema(1)
-  1
-  >>> schema('one')
-  Traceback (most recent call last):
-  ...
-  InvalidList: expected int
-
-Lists
-~~~~~
-Lists in the schema are treated as a set of valid values. Each element in the
-schema list is compared to each value in the input data::
-
-  >>> schema = Schema([1, 'a', 'string'])
-  >>> schema([1])
-  [1]
-  >>> schema([1, 1, 1])
-  [1, 1, 1]
-  >>> schema(['a', 1, 'string', 1, 'string'])
-  ['a', 1, 'string', 1, 'string']
-
-Validation functions
-~~~~~~~~~~~~~~~~~~~~
-Validators are simple callables that raise an ``Invalid`` exception when they
-encounter invalid data. The criteria for determining validity is entirely up to
-the implementation; it may check that a value is a valid username with
-``pwd.getpwnam()``, it may check that a value is of a specific type, and so on.
-
-In addition to simply determining if a value is valid, validators may mutate
-the value into a valid form. An example of this is the ``coerce(type)``
-function, which returns a function that coerces its argument to the given
-type::
-
-  def coerce(type, msg=None):
-      """Coerce a value to a type.
-
-      If the type constructor throws a ValueError, the value will be marked as
-      Invalid.
-      """
-      def f(v):
-          try:
-              return type(v)
-          except ValueError:
-              raise Invalid(msg or ('expected %s' % type.__name__))
-      return f
-
-This example also shows a common idiom where an optional human-readable
-message can be provided. This can vastly improve the usefulness of the
-resulting error messages.
-
-.. _extra:
-
-Dictionaries
-~~~~~~~~~~~~
-Each key-value pair in a schema dictionary is validated against each key-value
-pair in the corresponding data dictionary::
-
-  >>> schema = Schema({1: 'one', 2: 'two'})
-  >>> schema({1: 'one'})
-  {1: 'one'}
-
-Extra dictionary keys
-`````````````````````
-By default any additional keys in the data, not in the schema will trigger
-exceptions::
-
-  >>> schema = Schema({2: 3})
-  >>> schema({1: 2, 2: 3})
-  Traceback (most recent call last):
-  ...
-  InvalidList: extra keys not allowed @ data[1]
-
-This behaviour can be altered on a per-schema basis with ``Schema(..., extra=True)``::
-
-  >>> schema = Schema({2: 3}, extra=True)
-  >>> schema({1: 2, 2: 3})
-  {1: 2, 2: 3}
-
-It can also be overridden per-dictionary by using the catch-all marker token
-``extra`` as a key::
-
-  >>> from onctuous import extra
-  >>> schema = Schema({1: {extra: object}})
-  >>> schema({1: {'foo': 'bar'}})
-  {1: {'foo': 'bar'}}
-
-Required dictionary keys
-````````````````````````
-By default, keys in the schema are not required to be in the data::
-
-  >>> schema = Schema({1: 2, 3: 4})
-  >>> schema({3: 4})
-  {3: 4}
-
-Similarly to how extra_ keys work, this behaviour can be overridden per-schema::
-
-  >>> schema = Schema({1: 2, 3: 4}, required=True)
-  >>> schema({3: 4})
-  Traceback (most recent call last):
-  ...
-  InvalidList: required key not provided @ data[1]
-
-And per-key, with the marker token ``required(key)``::
-
-  >>> schema = Schema({required(1): 2, 3: 4})
-  >>> schema({3: 4})
-  Traceback (most recent call last):
-  ...
-  InvalidList: required key not provided @ data[1]
-  >>> schema({1: 2})
-  {1: 2}
-
-Optional dictionary keys
-````````````````````````
-If a schema has ``required=True``, keys may be individually marked as optional
-using the marker token ``optional(key)``::
-
-  >>> from onctuous import optional
-  >>> schema = Schema({1: 2, optional(3): 4}, required=True)
-  >>> schema({})
-  Traceback (most recent call last):
-  ...
-  InvalidList: required key not provided @ data[1]
-  >>> schema({1: 2})
-  {1: 2}
-  >>> schema({1: 2, 4: 5})
-  Traceback (most recent call last):
-  ...
-  InvalidList: extra keys not allowed @ data[4]
-  >>> schema({1: 2, 3: 4})
-  {1: 2, 3: 4}
-
-Error reporting
----------------
-Validators must throw an ``Invalid`` exception if invalid data is passed to
-them. All other exceptions are treated as errors in the validator and will not
-be caught.
-
-Each ``Invalid`` exception has an associated ``path`` attribute representing
-the path in the data structure to our currently validating value. This is used
-during error reporting, but also during matching to determine whether an error
-should be reported to the user or if the next match should be attempted. This
-is determined by comparing the depth of the path where the check is, to the
-depth of the path where the error occurred. If the error is more than one level
-deeper, it is reported.
-
-The upshot of this is that *matching is depth-first and fail-fast*.
-
-To illustrate this, here is an example schema::
-
-  >>> schema = Schema([[2, 3], 6])
-
-Each value in the top-level list is matched depth-first in-order. Given input
-data of ``[[6]]``, the inner list will match the first element of the schema,
-but the literal ``6`` will not match any of the elements of that list. This
-error will be reported back to the user immediately. No backtracking is
-attempted::
-
-  >>> schema([[6]])
-  Traceback (most recent call last):
-  ...
-  InvalidList: invalid list value @ data[0][0]
-
-If we pass the data ``[6]``, the ``6`` is not a list type and so will not
-recurse into the first element of the schema. Matching will continue on to the
-second element in the schema, and succeed::
-
-  >>> schema([6])
-  [6]
+    $ hg clone ssh://hg@bitbucket.org/Ludia/onctuous
+    $ pip install nose nosexcover coverage mock
+    $ python setup.py develop
+    $ nosetests
 
 Why use Onctuous over another validation library?
--------------------------------------------------
+=================================================
 
 It's:
 
   Types in the schema are checked as types. Values are compared as values.
   Callables are called to validate. Simple.
 
+
+Example usage
+=============
+
+Validate a scalar
+-----------------
+
+::
+
+    from onctuous import Schema
+
+    validate_is_int = Schema(int)
+
+    # Validate 42 (this will run fine)
+    validated = validate_is_int(42)
+
+    # Validate "toto" (this will raise ``InvalidList`` containing a list of errors)
+    validated = validate_is_int("toto")
+
+
+Validate a list
+---------------
+
+Using the same idea, you can validate a list of ``int``
+
+::
+
+    from onctuous import Schema
+
+    validate_is_int_list = Schema([int])
+
+    # This will run fine
+    validated = validate_is_int_list([42, 2, 7])
+
+    # This will raise ``InvalidList`` containing a list of errors
+    validated = validate_is_int_list([2, 7, "toto"])
+
+
+But we can also use on of the bundled validators and check the URL looks to
+be valid for example and even supply a custom error message!
+
+::
+
+    from onctuous import Schema, Url
+
+    validate_is_urls = Schema([Url(msg="Ooops, this is *not* a valid URL")])
+
+    # This will run fine
+    validated = validate_is_urls(["www.example.com", "ftp://user:pass@ftp.example.com:42/toto?weird/path"])
+
+    # This will raise ``InvalidList`` containing a list of errors
+    validated = validate_is_urls([2, 7, "toto"])
+
+
+Validate a dictionary
+---------------------
+
+Again, this is the same concept with some more niceties. For example, here is a
+basic user schema:
+
+::
+
+    from onctuous import Schema, Url
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': int,
+        'website': Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+But wait, I don't want megative ages, do I ?
+
+::
+
+    from onctuous import Schema, Url, InRange, All
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        'website': Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+Have you noticed how this uses ``All`` to specify that both ``int`` and ``range``
+conditions must ne met ?
+
+What if I want to make the "Website" field optional ? Let me introduce ``Markers``
+
+::
+
+    from onctuous import Schema, Url, InRange, All, Optional
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        Optional('website'): Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+You could also have used the 'Required' Marker with a default value. This is very
+usefull if you do not want to spend your whole time writing ``if key in data...``.
+
+::
+
+    from onctuous import Schema, Url, InRange, All, Required
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        Required('website', "#"): Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+
+It is worth noting that that the provided default value does *not* need to pass
+validations. You can use it as a "Marker" further in you application.
+
+Nested and advanced validations
+-------------------------------
+
+You can nest shemas. You actually did it in the previous example where scalars
+are nested into a dict or a list. But you can arbitrarily nest lists into dict
+and the other way around, as you need.
+
+For example, let's say you are writing a blog post which obviously has an author
+and maybe some tags whose len are between 3 and 20 chars included.
+
+::
+
+    from onctuous import Schema, All, Required, Length, InRange
+
+    # Same schema as user above. I just removed the Schema instanciation but
+    # could have kept it. It's just more natural
+    user = {
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        Required('website', "#"): Url(msg="Ooops, this is *not* a valid URL"),
+    }
+
+    validate_post = Schema({
+        'title': unicode,
+        'body': unicode,
+        'author': user,  # look how you can split a schema into re-usable chunks!
+        Optional('tags'): [All(unicode, Length(min=3, max=20))],
+        Required('website', "#"): Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+That's all for nesting.
+
+You could also use the ``Extra`` special key to allow extra fields to be present
+while still being valid.
+
+When instanciating the schema, there are also a global ``required`` and ``extra``
+parameters that can optionally be set. They both default to ``False``
+
+Going further
+=============
+
+There are tons of bundled validators, see the full API documentation here: TODO
+
+Requirements
+============
+
+ - Python 2.7.x
+ - nose, nosexcover, coverage, mock for the tests
+
+Related Links
+=============
+
+onctuous
+--------
+
+- **Full documentation**: https://onctuous.readthedocs.org/en/latest
+- **Report bugs**: https://bitbucket.org/Ludia/onctuous/issues
+- **Download**: http://pypi.python.org/pypi/onctuous
+
+# 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) .
+# 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 <target>' where <target> 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/dynamodb-mapper.qhcp"
+	@echo "To view the help file:"
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/dynamodb-mapper.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/dynamodb-mapper"
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/dynamodb-mapper"
+	@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."

docs/_include/intro.rst

+**Onctuous** is a fluid and pleasing to use validation tool you will love to
+use. Originally based on `Voluptuous <https://github.com/alecthomas/voluptuous>`_
+code by Alec Thomas <alec@swapoff.org>, we first fixed long outstanding issues
+like Python builtins collision and added support for default values.
+
+The goal of **Onctuous** is to make it simple and smooth.
+ - You *can* write your own validators
+ - You *can* specify defaults. The best ? They are *not* required to pass validation themselves
+ - You *can* write readable code. This is not based on json schema specification, on purpose
+
+You can use Onctuous to validate ``list``, ``scalar`` (regular variables) or
+``dict``. For this purpose, you will need to define a so-called ``Schema`` and
+call the Schema with the input to validate. In case of success, it will return
+the validated input, possibly filtered or edited according to your rules

docs/api/errors.rst

+######
+Errors
+######
+
+.. currentmodule:: onctuous.errors
+
+=================
+SchemaError class
+=================
+
+.. autoclass:: SchemaError
+
+=============
+Invalid class
+=============
+
+.. autoclass:: Invalid
+
+=================
+InvalidList class
+=================
+
+
+Class definition
+----------------
+
+.. autoclass:: InvalidList
+
+Public API
+**********
+
+__init__
+^^^^^^^^
+
+.. automethod:: InvalidList.__init__
+
+add
+^^^
+
+.. automethod:: InvalidList.add

docs/api/schema.rst

+############
+Schema class
+############
+
+.. currentmodule:: onctuous.schema
+
+Class definition
+================
+
+.. autoclass:: Schema
+
+Public API
+----------
+
+__init__
+^^^^^^^^
+
+.. automethod:: Schema.__init__
+
+__call__
+^^^^^^^^
+
+.. automethod:: Schema.__call__
+
+validate
+^^^^^^^^
+
+.. automethod:: Schema.validate

docs/api/validators.rst

+#############################
+Schema validators and markers
+#############################
+
+.. currentmodule:: onctuous.validators
+.. _validator-list:
+
+=======
+Markers
+=======
+
+Marker base class
+-----------------
+
+.. autoclass:: Marker
+
+Optional Class
+--------------
+
+.. autoclass:: Optional
+
+Required Class
+--------------
+
+.. autoclass:: Required
+
+Extra Method
+------------
+
+.. autofunction:: Extra
+
+==========
+Validators
+==========
+
+Msg
+---
+
+.. autofunction:: Msg
+
+Coerce
+------
+
+.. autofunction:: Coerce
+
+IsTrue
+------
+
+.. autofunction:: IsTrue
+
+IsFalse
+-------
+
+.. autofunction:: IsFalse
+
+Boolean
+-------
+
+.. autofunction:: Boolean
+
+Any
+---
+
+.. autofunction:: Any
+
+All
+---
+
+.. autofunction:: All
+
+Match
+-----
+
+.. autofunction:: Match
+
+Sub
+---
+
+.. autofunction:: Sub
+
+Url
+---
+
+.. autofunction:: Url
+
+IsFile
+------
+
+.. autofunction:: IsFile
+
+IsDir
+-----
+
+.. autofunction:: IsDir
+
+PathExists
+----------
+
+.. autofunction:: PathExists
+
+InRange
+-------
+
+.. autofunction:: InRange
+
+Clamp
+-----
+
+.. autofunction:: Clamp
+
+Length
+------
+
+.. autofunction:: Length
+
+ToLower
+-------
+
+.. autofunction:: ToLower
+
+ToUpper
+-------
+
+.. autofunction:: ToUpper
+
+Capitalize
+----------
+
+.. autofunction:: Capitalize
+
+Title
+-----
+
+.. autofunction:: Title
+
+# -*- coding: utf-8 -*-
+#
+# ddbmock documentation build configuration file, created by
+# sphinx-quickstart on Fri Aug  3 10:48:56 2012.
+#
+# 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, 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('..'))
+
+# -- 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.todo', 'sphinx.ext.coverage']
+
+# 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 = u'Onctuous'
+copyright = u'2012, Ludia Inc.'
+
+# 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.
+version = '0.5'
+# The full version, including alpha/beta/rc tags.
+release = '0.5.1.dev'
+
+# 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', '_include']
+
+# 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 = 'default'
+
+# 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.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> 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 = []
+
+# 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 <link> 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 = 'onctuous_doc'
+
+
+# -- 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', 'onctuous.tex', u'Onctuous Documentation',
+   u'Jean-Tiare Le Bigot', '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', 'onctuous', u'Onctuous Documentation',
+     [u'Jean-Tiare Le Bigot'], 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', 'onctuous', u'Onctuous Documentation',
+   u'Jean-Tiare Le Bigot', 'onctuous', 'Python data validation library.',
+   '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'
+
+
+# -- Options for Epub output ---------------------------------------------------
+
+# Bibliographic Dublin Core info.
+epub_title = u'Onctuous Documentation'
+epub_author = u'Jean-Tiare Le Bigot'
+epub_publisher = u'Jean-Tiare Le Bigot'
+epub_copyright = u'2012, Ludia Inc.'
+
+# The language of the text. It defaults to the language option
+# or en if the language is not set.
+#epub_language = ''
+
+# The scheme of the identifier. Typical schemes are ISBN or URL.
+#epub_scheme = ''
+
+# The unique identifier of the text. This can be a ISBN number
+# or the project homepage.
+#epub_identifier = ''
+
+# A unique identification for the text.
+#epub_uid = ''
+
+# A tuple containing the cover image and cover page html template filenames.
+#epub_cover = ()
+
+# HTML files that should be inserted before the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_pre_files = []
+
+# HTML files shat should be inserted after the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_post_files = []
+
+# A list of files that should not be packed into the epub file.
+#epub_exclude_files = []
+
+# The depth of the table of contents in toc.ncx.
+#epub_tocdepth = 3
+
+# Allow duplicate toc entries.
+#epub_tocdup = True
+############################
+DynamoDB-mock documentation.
+############################
+
+Overview
+========
+
+.. include:: _include/intro.rst
+
+Documentation
+=============
+
+User guide
+----------
+
+.. toctree::
+   :maxdepth: 3
+
+   pages/getting_started
+   pages/extending
+
+   pages/changelog
+
+
+Api reference
+-------------
+
+.. toctree::
+   :maxdepth: 2
+   :glob:
+
+   api/*
+
+Indices and tables
+------------------
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
+Contribute
+==========
+
+Want to contribute, report a but of request a feature ? The development goes on
+BitBucket:
+
+- **Download**: http://pypi.python.org/pypi/onctuous
+- **Report bugs**: https://bitbucket.org/Ludia/onctuous/issues
+- **Fork the code**: https://bitbucket.org/Ludia/onctuous/overview
+@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 ^<target^>` where ^<target^> 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\dynamodb-mapper.qhcp
+    echo.To view the help file:
+    echo.^> assistant -collectionFile %BUILDDIR%\qthelp\dynamodb-mapper.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

docs/pages/changelog.rst

+#############################
+Change log - Migration guide.
+#############################
+
+.. include:: ../../CHANGES.rst

docs/pages/extending.rst

+#######################
+Extending DynamoDB-mock
+#######################
+
+Folder structure
+================
+
+::
+
+    Onctuous
+    +-- onctuous            => the real code
+    |   +-- tests
+    |       +-- unit        => all individual validators and low level logic
+    |       `-- functional  => global behovior
+    +-- docs
+        `-- pages           => what you are reading
+
+
+Adding a custom validator
+=========================
+
+If you want to contribute to ``Onctuous`` (we would love it btw), you will need
+to add your custom validator into ``ddmock.validators`` module. Otherwise, put it
+wherever you want, there are no restrictions.
+
+Technically speaking, any callable can be a validator.
+
+All validators will look like this:
+
+::
+
+    # Parent function: loads the parameters
+    def ValidatorName(param1, param2, ..., msg=None):
+        # this 'inner' function does the real job and is called by ``Onctuous``
+        def f(v):
+            if some condition:
+                return v  # All changes done to the value will be reflected in the validated object
+            raise Invalid(msg or 'Ooops: "Some Condition" was not met!')
+        return f
+
+For example, here is the ``Url`` validator:
+
+
+::
+
+    def Url(msg=None):
+        """Verify that the value is a URL."""
+        def f(v):
+            try:
+                urlparse.urlparse(v)
+                return v
+            except:
+                raise Invalid(msg or 'expected a URL')
+        return f
+
+That's all tou need to do!
+
+Adding a custom marker
+======================
+
+Sadly, this is quite more invasive to do and will probably require you to patch
+the hearth of ``Onctuous``.
+
+Markers lives in the same module as Validators: ``ddmock.validators`` and are
+also callable.
+
+The most simple Marker you can do is the "Optional" marker:
+
+::
+
+    class Optional(Marker):
+        """Mark a node in the schema as optional."""
+
+But you could override ``__init__`` or ``__call__`` for instance.
+
+Then, Marker presence is detected in ``Schema._validate_dict`` in module
+``ddmock.schema``, that is to say, the heart of ``Onctuous``

docs/pages/getting_started.rst

+#############################
+Getting started with Onctuous
+#############################
+
+.. include:: ../_include/intro.rst
+
+Installation
+============
+
+::
+
+    $ pip install onctuous
+
+
+Example usage
+=============
+
+Validate a scalar
+-----------------
+
+::
+
+    from onctuous import Schema
+
+    validate_is_int = Schema(int)
+
+    # Validate 42 (this will run fine)
+    validated = validate_is_int(42)
+
+    # Validate "toto" (this will raise ``InvalidList`` containing a list of errors)
+    validated = validate_is_int("toto")
+
+
+Validate a list
+---------------
+
+Using the same idea, you can validate a list of ``int``
+
+::
+
+    from onctuous import Schema
+
+    validate_is_int_list = Schema([int])
+
+    # This will run fine
+    validated = validate_is_int_list([42, 2, 7])
+
+    # This will raise ``InvalidList`` containing a list of errors
+    validated = validate_is_int_list([2, 7, "toto"])
+
+
+But we can also use on of the bundled validators and check the URL looks to
+be valid for example and even supply a custom error message!
+
+::
+
+    from onctuous import Schema, Url
+
+    validate_is_urls = Schema([Url(msg="Ooops, this is *not* a valid URL")])
+
+    # This will run fine
+    validated = validate_is_urls(["www.example.com", "ftp://user:pass@ftp.example.com:42/toto?weird/path"])
+
+    # This will raise ``InvalidList`` containing a list of errors
+    validated = validate_is_urls([2, 7, "toto"])
+
+
+Validate a dictionary
+---------------------
+
+Again, this is the same concept with some more niceties. For example, here is a
+basic user schema:
+
+::
+
+    from onctuous import Schema, Url
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': int,
+        'website': Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+But wait, I don't want megative ages, do I ?
+
+::
+
+    from onctuous import Schema, Url, InRange, All
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        'website': Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+Have you noticed how this uses ``All`` to specify that both ``int`` and ``range``
+conditions must ne met ?
+
+What if I want to make the "Website" field optional ? Let me introduce ``Markers``
+
+::
+
+    from onctuous import Schema, Url, InRange, All, Optional
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        Optional('website'): Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+You could also have used the 'Required' Marker with a default value. This is very
+usefull if you do not want to spend your whole time writing ``if key in data...``.
+
+::
+
+    from onctuous import Schema, Url, InRange, All, Required
+
+    validate_user = Schema({
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        Required('website', "#"): Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+
+It is worth noting that that the provided default value does *not* need to pass
+validations. You can use it as a "Marker" further in you application.
+
+Nested and advanced validations
+-------------------------------
+
+You can nest shemas. You actually did it in the previous example where scalars
+are nested into a dict or a list. But you can arbitrarily nest lists into dict
+and the other way around, as you need.
+
+For example, let's say you are writing a blog post which obviously has an author
+and maybe some tags whose len are between 3 and 20 chars included.
+
+::
+
+    from onctuous import Schema, All, Required, Length, InRange
+
+    # Same schema as user above. I just removed the Schema instanciation but
+    # could have kept it. It's just more natural
+    user = {
+        'firstname': unicode,
+        'lastname': unicode,
+        'age': All(int, InRange(min=0, msg="Uh, ages can not be negative...")),
+        Required('website', "#"): Url(msg="Ooops, this is *not* a valid URL"),
+    }
+
+    validate_post = Schema({
+        'title': unicode,
+        'body': unicode,
+        'author': user,  # look how you can split a schema into re-usable chunks!
+        Optional('tags'): [All(unicode, Length(min=3, max=20))],
+        Required('website', "#"): Url(msg="Ooops, this is *not* a valid URL"),
+    })
+
+    # use it...
+
+That's all for nesting.
+
+You could also use the ``Extra`` special key to allow extra fields to be present
+while still being valid.
+
+When instanciating the schema, there are also a global ``required`` and ``extra``
+parameters that can optionally be set. They both default to ``False``
+
+Going further
+=============
+
+There are tons of bundled validators, :ref:`see the full API documentation <validator-list>`.

onctuous/errors.py

 # Maintainers: Jean-Tiare Le Bigot <jtlebigot@socialludia.com>,
 
 class Undefined(object):
+    """ Simple class to represent an undefined value (internal usage)
+    """
     def __nonzero__(self):
         return False
 
 
 
 class InvalidList(Invalid):
+    """ List of captures errors for reporting to the end user.
+
+    :attr errors: Array of errors
+    :attr msg: Message associated with the first reported error
+    :attr path: Path associated with the first reported error
+    """
+    # FIXME: why keeping a list if we onlt return values about the *first* eror ?
     def __init__(self, errors):
+        """ Create a new list of errors.
+
+        :param errors: list of errors to add initially
+        """
         if not errors:
             raise ValueError("'errors' array can *not* be empty")
         self.errors = errors[:]
         return self.errors[0].path
 
     def add(self, error):
+        """Push an error to the internal list"""
         self.errors.append(error)
 
     def __str__(self):

onctuous/schema.py

     def __init__(self, schema, required=False, extra=False):
         """Create a new Schema.
 
-        :param schema: Validation schema. See :module:`onctuous` for details.
+        :param schema: Validation schema.
         :param required: Keys defined in the schema must be in the data.
         :param extra: Keys in the data need not have keys in the schema.
         """
         self.extra = extra
 
     def __call__(self, data):
-        """Validate data against this schema."""
+        """Validate data against ``self.schema``. This simply is a shortcut for
+        ``validate`` method.
+
+        :param data: input data to validate
+        :return: validated input
+        :raise: :py:class:`~.InvalidList`
+        """
         return self.validate([], self.schema, data)
 
     def validate(self, path, schema, data):
+        """Validate data against this ``schema``.
+
+        :param path: (list) current path in the object, Starts as ``[]``
+        :param schema: schema to validate agains
+        :param data: input data to validate
+        :return: validated input
+        :raise: :py:class:`~.InvalidList`
+        """
         try:
             if isinstance(schema, dict):
                 return self._validate_dict(path, schema, data)
     'nosexcover',
     'coverage',
     'mock',
-    'webtest',
 ]
 
 setup(
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.