from pyramid.config import Configurator
+def parse_assignments(lines):
+ '''Return a list of key/value tuples from the lines of a setting
+ '''
+ result = []
+ for line in lines.split('\n'):
+ if '=' in line:
+ key, val = line.split('=')
+ result.append((key.rstrip(), val.lstrip()))
+ return result
+
+
+def add_routes(config, settings):
+ '''Add routes found in pgwui.routes setting
+ '''
+ if 'pgwui.routes' in settings:
+ routes = parse_assignments(settings['pgwui.routes'])
+ for route_entry in routes:
+ name, route = route_entry
+ config.add_route(name, route)
+
+
def pgwui_server_config(settings):
+ '''Configure pyramid
+ '''
rp = settings.get('pgwui.route_prefix')
with Configurator(settings=settings, route_prefix=rp) as config:
config.include('pgwui_common')
+ add_routes(config, settings)
return config
pass
+class MockConfig():
+ def __init__(self):
+ self.add_route_called = 0
+
+ def add_route(self, *args):
+ self.add_route_called += 1
+
+
# Unit tests
+# parse_assignments()
+
+def test_parse_assignments():
+ '''Returns key/value tuples and ignores lines without an "="'''
+ lines = ('key1 = value1\n' # whitespace around = is ignored
+ '\n'
+ 'ignored\n'
+ 'key2=value2\n' # missing whitespace is fine
+ )
+ result = pgwui_server_init.parse_assignments(lines)
+ assert result == [('key1', 'value1'),
+ ('key2', 'value2')]
+
+
+# add_routes()
+
+def test_add_routes_empty():
+ '''When there is no pgwui.routes setting nothing gets added'''
+ config = MockConfig()
+ pgwui_server_init.add_routes(config, {})
+ assert config.add_route_called == 0
+
+
+def test_add_routes_notempty(monkeypatch):
+ '''When there is a pgwui.routes setting config.add_route() is called
+ for each route'''
+ config = MockConfig()
+ monkeypatch.setattr(pgwui_server_init, 'parse_assignments',
+ lambda *args: [('name1', 'route1'),
+ ('name2', 'route2')])
+ pgwui_server_init.add_routes(config, {'pgwui.routes': ''})
+ assert config.add_route_called == 2
+
# pgwui_server_config()
def test_pgwui_server_config(monkeypatch):
'''Returns a configuration'''
monkeypatch.setattr(pgwui_server_init, 'Configurator', MockConfigurator)
+ monkeypatch.setattr(pgwui_server_init, 'add_routes',
+ lambda *args: None)
result = pgwui_server_init.pgwui_server_config({})
assert isinstance(result, MockConfigurator)