Skip to content

Commit

Permalink
Add tests, code and docs for pyramid inclusion
Browse files Browse the repository at this point in the history
Still needs some integration tests for it
  • Loading branch information
Javex committed Apr 2, 2014
1 parent e40e04f commit e9c03fc
Show file tree
Hide file tree
Showing 8 changed files with 263 additions and 12 deletions.
1 change: 1 addition & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ refer there to see how your goal can be realized in pratice.

.. toctree::

usage/configuration
usage/views
usage/forms
usage/templates
Expand Down
56 changes: 56 additions & 0 deletions docs/usage/configuration.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
.. _configuration:

=============
Configuration
=============

There are several global settings with which you can configure the behavior of
this library. All settings use the prefix ``crud.``

.. _template_renderer:

Template Renderer
-----------------

This setting specifies the template renderer to use or if none should be used.
It supports the following settings:

* ``mako`` to use the `Mako`_ templates provided with this library. This
is the default.
* ``None`` if no default templates should be used. Use this if you want to
completely roll your own templates.

.. _Mako: http://www.makotemplates.org/

In essence, this setting sets up additional lookup paths for the templates and
adds a configurable static view for CSS files etc (see
:ref:`static_url_prefix`)

+-----------------------------+
| Config File Setting Name |
+=============================+
| ``crud.template_renderer`` |
+-----------------------------+

.. _static_url_prefix:

Static View URL Prefix
----------------------

The application needs to serve static assets to display the default templates
properly (specifically, it uses `Bootstrap`_). These assets need their own
prefix to avoid routing conflicts with your other static files. Thus, this
setting allows you to define a custom prefix. By default, it is
``/static/crud`` which should be fine for most applications (as ``static`` is a
very commong name, you can have all your CSS and JS files under this). However,
if this does not fit your use case, use this setting to change it. Note that it
only takes effect when using the templates provided with the library
(see :ref:`template_renderer`).

+-----------------------------+
| Config File Setting Name |
+=============================+
| ``crud.static_url_prefix`` |
+-----------------------------+

.. _Bootstrap: http://getbootstrap.com/
60 changes: 54 additions & 6 deletions pyramid_crud/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,60 @@
import os
from pyramid.exceptions import ConfigurationError
from pyramid.compat import is_nonstr_iter
from pyramid.settings import aslist
from pyramid.interfaces import ISessionFactory

__version__ = '0.1.2'


def parse_options_from_settings(settings, settings_prefix):
"""Parse out options."""
def sget(name, default=None):
return settings.get(settings_prefix + name, default)

template_renderer = sget('template_renderer', 'mako')
if template_renderer == 'None':
template_renderer = None
if template_renderer not in (None, 'mako'):
raise ConfigurationError("Template Renderer '%s' is not supported"
% template_renderer)

static_url_prefix = sget('static_url_prefix', '/static/crud')

return dict(
template_renderer=template_renderer,
static_url_prefix=static_url_prefix,
)


def check_session(config):
if config.registry.queryUtility(ISessionFactory) is None:
raise ConfigurationError(
"No session factory registered. You must register a session "
"factory for this module to work")


def includeme(config):
here = os.path.abspath(os.path.dirname(__file__))
template_dir = os.path.join(here, 'templates')
config.add_settings({'mako.directories': template_dir})
# TODO: Add setting for which static path to use and add that static path
# using config.add_static_view
raise NotImplementedError("Check for existing session!")
settings = config.get_settings()
opts = parse_options_from_settings(settings, 'crud.')

if opts['template_renderer'] == 'mako':
mako_dirs = settings.get('mako.directories', [])
# Copied from pyramid_mako
if not is_nonstr_iter(mako_dirs):
# Since we parse a value that comes from an .ini config,
# we treat whitespaces and newline characters equally as list item
# separators.
mako_dirs = aslist(mako_dirs, flatten=True)
mako_dirs.append('pyramid_crud:templates')
config.add_settings({'mako.directories': mako_dirs})

# This option only makes sense when templates are in use
config.add_static_view(opts['static_url_prefix'],
'pyramid_crud:static')
else:
pass

# order=1 to be executed **after** session_factory register callback.
config.action(('pyramid_crud', 'check_session'),
lambda: check_session(config), order=1)
2 changes: 1 addition & 1 deletion pyramid_crud/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import logging
try:
from collections import OrderedDict
except:
except ImportError: # pragma: no cover
from ordereddict import OrderedDict


Expand Down
2 changes: 1 addition & 1 deletion pyramid_crud/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from sqlalchemy import inspect
try:
from collections import OrderedDict
except:
except ImportError: # pragma: no cover
from ordereddict import OrderedDict


Expand Down
9 changes: 5 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,12 @@ def session(pyramid_request):
return session


@pytest.fixture
@pytest.yield_fixture
def config(pyramid_request, request):
cfg = testing.setUp(request=pyramid_request)
request.addfinalizer(testing.tearDown)
return cfg
cfg = testing.setUp(request=pyramid_request, autocommit=False)
yield cfg
cfg.commit()
testing.tearDown()


@pytest.fixture
Expand Down
144 changes: 144 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import pyramid_crud
import pytest
from pyramid.exceptions import ConfigurationError
from pyramid.interfaces import ISessionFactory


@pytest.fixture
def mako_renderer(config, no_renderer):
"Add mako renderer as configuration to settings."
config.add_settings({'crud.template_renderer': 'mako'})


@pytest.fixture
def no_renderer(config):
"Disable templates."
config.add_settings({'crud.template_renderer': 'None'})


@pytest.fixture(params=['mako'])
def any_renderer(config, request):
"""Enable any renderer. Will use one of all available renderers in each
iteration."""
config.add_settings({'crud.template_renderer': request.param})


@pytest.fixture
def static_prefix(config):
"Add a static URL prefix with the name '/testprefix'"
config.add_settings({'crud.static_url_prefix': '/testprefix'})


@pytest.fixture
def custom_settings(no_renderer, static_prefix):
"A fixture that uses custom settings."


@pytest.fixture
def session_factory(config):
f = lambda: None
config.registry.registerUtility(f, ISessionFactory)


def test_check_session_no_factory(config):
with pytest.raises(ConfigurationError):
pyramid_crud.check_session(config)


@pytest.mark.usefixtures("session_factory")
def test_check_session_factory(config):
pyramid_crud.check_session(config)


@pytest.mark.usefixtures("custom_settings", "static_prefix")
def test_parse_options_from_settings(config):
settings = config.get_settings()
ref_settings = {'template_renderer': None,
'static_url_prefix': '/testprefix',
}
settings = pyramid_crud.parse_options_from_settings(settings, 'crud.')
assert settings == ref_settings


def test_parse_options_from_settings_defaults():
settings = pyramid_crud.parse_options_from_settings({}, 'crud.')
ref_settings = {'template_renderer': 'mako',
'static_url_prefix': '/static/crud',
}
assert settings == ref_settings


def test_parse_options_from_settings_no_renderer():
settings = {'crud.template_renderer': None}
settings = pyramid_crud.parse_options_from_settings(settings, 'crud.')
assert settings['template_renderer'] is None


def test_parse_options_from_settings_no_renderer_str():
settings = {'crud.template_renderer': 'None'}
settings = pyramid_crud.parse_options_from_settings(settings, 'crud.')
assert settings['template_renderer'] is None


@pytest.mark.usefixtures("custom_settings")
def test_parse_options_from_settings_invalid_renderer():
settings = {'crud.template_renderer': 'invalid'}
with pytest.raises(ConfigurationError):
pyramid_crud.parse_options_from_settings(settings, 'crud.')


@pytest.mark.usefixtures("custom_settings", "session_factory", "mako_renderer")
def test_includeme_mako(config):
pyramid_crud.includeme(config)
settings = config.get_settings()
mako_dirs = settings['mako.directories']
assert mako_dirs == ['pyramid_crud:templates']


@pytest.mark.usefixtures("session_factory")
def test_includeme_no_template(config):
config.add_settings({'crud.template_renderer': 'None'})
pyramid_crud.includeme(config)
settings = config.get_settings()
assert 'mako.directories' not in settings


def test_includeme_no_session(config):
pyramid_crud.includeme(config)
with pytest.raises(ConfigurationError):
config.commit()


def test_includeme_session_correct_order(config):
def register():
f = lambda: None
config.registry.registerUtility(f, ISessionFactory)
config.action(('pyramid_crud', 'session_test'), register)
pyramid_crud.includeme(config)
config.commit()


def test_includeme_session_wrong_order(config):
def register():
f = lambda: None
config.registry.registerUtility(f, ISessionFactory)
config.action(('pyramid_crud', 'session_test'), register, order=2)
pyramid_crud.includeme(config)
with pytest.raises(ConfigurationError):
config.commit()


@pytest.mark.usefixtures("custom_settings", "session_factory", "any_renderer")
def test_includeme_static_view(config, pyramid_request):
pyramid_crud.includeme(config)
config.commit()
url = pyramid_request.static_url('pyramid_crud:static/test.png')
assert url == 'http://example.com/testprefix/test.png'


@pytest.mark.usefixtures("session_factory", "any_renderer")
def test_includeme_static_view_default(config, pyramid_request):
pyramid_crud.includeme(config)
config.commit()
url = pyramid_request.static_url('pyramid_crud:static/test.png')
assert url == 'http://example.com/static/crud/test.png'
1 change: 1 addition & 0 deletions tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def route_setup(config):
config.add_route(basename + "edit", '/test/{id}')
config.add_route(basename + "delete", '/test/delete/{id}')
config.add_route(basename + "new", '/test/new')
config.commit()


@pytest.fixture
Expand Down

0 comments on commit e9c03fc

Please sign in to comment.