Bugfixes and tests

Changes:

* ported tests from web2py, except for validation ones (in TODOs)
* ported latest changes by @ilvalle (https://github.com/web2py/web2py/pull/552, https://github.com/web2py/web2py/pull/550)
* several bugfixes