initial commit
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# run unit tests under nose if available,
|
||||
# optionally with coverage
|
||||
#
|
||||
# test.sh [cover [gluon.rewrite]]
|
||||
#
|
||||
# easy_install nose
|
||||
# easy_install coverage
|
||||
#
|
||||
NOSETESTS=nosetests
|
||||
COVER=gluon # change to (eg) gluon.rewrite to collect coverage stats on a single module
|
||||
PROCESSES=4
|
||||
|
||||
WHICH=`which $NOSETESTS`
|
||||
if [ "$WHICH" == "" ]; then
|
||||
# if nose isn't available, run the tests directly
|
||||
for testmod in test_*.py; do
|
||||
python $testmod
|
||||
done
|
||||
else
|
||||
if [ "$1" = "cover" ]; then
|
||||
# note: coverage doesn't handle multiple processes
|
||||
if [ "$2" != "" ]; then
|
||||
COVER=$2
|
||||
fi
|
||||
$NOSETESTS --with-coverage --cover-package=$COVER --cover-erase
|
||||
elif [ "$1" = "doctest" ]; then
|
||||
# this has to run in gluon's parent; needs work
|
||||
#
|
||||
# the problem is that doctests run this way have a very different environment,
|
||||
# apparently due to imports that don't happen in the normal course of running
|
||||
# doctest via __main__.
|
||||
#
|
||||
echo doctest not supported >&2
|
||||
exit 1
|
||||
if [ ! -d gluon ]; then
|
||||
cd ../..
|
||||
fi
|
||||
$NOSETESTS --with-doctest
|
||||
else
|
||||
$NOSETESTS --processes=$PROCESSES
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Unit tests for gluon.cache
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon'))
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../'))
|
||||
|
||||
import unittest
|
||||
from storage import Storage
|
||||
from cache import CacheInRam, CacheOnDisk
|
||||
|
||||
oldcwd = None
|
||||
|
||||
def setUpModule():
|
||||
global oldcwd
|
||||
if oldcwd is None:
|
||||
oldcwd = os.getcwd()
|
||||
if not os.path.isdir('gluon'):
|
||||
os.chdir(os.path.realpath('../../'))
|
||||
|
||||
def tearDownModule():
|
||||
global oldcwd
|
||||
if oldcwd:
|
||||
os.chdir(oldcwd)
|
||||
oldcwd = None
|
||||
|
||||
class TestCache(unittest.TestCase):
|
||||
|
||||
def testCacheInRam(self):
|
||||
|
||||
# defaults to mode='http'
|
||||
|
||||
cache = CacheInRam()
|
||||
self.assertEqual(cache('a', lambda: 1, 0), 1)
|
||||
self.assertEqual(cache('a', lambda: 2, 100), 1)
|
||||
cache.clear('b')
|
||||
self.assertEqual(cache('a', lambda: 2, 100), 1)
|
||||
cache.clear('a')
|
||||
self.assertEqual(cache('a', lambda: 2, 100), 2)
|
||||
cache.clear()
|
||||
self.assertEqual(cache('a', lambda: 3, 100), 3)
|
||||
self.assertEqual(cache('a', lambda: 4, 0), 4)
|
||||
|
||||
def testCacheOnDisk(self):
|
||||
|
||||
# defaults to mode='http'
|
||||
|
||||
s = Storage({'application': 'admin',
|
||||
'folder': 'applications/admin'})
|
||||
cache = CacheOnDisk(s)
|
||||
self.assertEqual(cache('a', lambda: 1, 0), 1)
|
||||
self.assertEqual(cache('a', lambda: 2, 100), 1)
|
||||
cache.clear('b')
|
||||
self.assertEqual(cache('a', lambda: 2, 100), 1)
|
||||
cache.clear('a')
|
||||
self.assertEqual(cache('a', lambda: 2, 100), 2)
|
||||
cache.clear()
|
||||
self.assertEqual(cache('a', lambda: 3, 100), 3)
|
||||
self.assertEqual(cache('a', lambda: 4, 0), 4)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
setUpModule() # pre-python-2.7
|
||||
unittest.main()
|
||||
tearDownModule()
|
||||
@@ -0,0 +1,486 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Unit tests for gluon.sql
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon'))
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../'))
|
||||
|
||||
import unittest
|
||||
import datetime
|
||||
from dal import DAL, Field, Table, SQLALL
|
||||
|
||||
ALLOWED_DATATYPES = [
|
||||
'string',
|
||||
'text',
|
||||
'integer',
|
||||
'boolean',
|
||||
'double',
|
||||
'blob',
|
||||
'date',
|
||||
'time',
|
||||
'datetime',
|
||||
'upload',
|
||||
'password',
|
||||
]
|
||||
|
||||
|
||||
def setUpModule():
|
||||
pass
|
||||
|
||||
def tearDownModule():
|
||||
if os.path.isfile('sql.log'):
|
||||
os.unlink('sql.log')
|
||||
|
||||
|
||||
class TestFields(unittest.TestCase):
|
||||
|
||||
def testFieldName(self):
|
||||
|
||||
# Check that Fields cannot start with underscores
|
||||
self.assertRaises(SyntaxError, Field, '_abc', 'string')
|
||||
|
||||
# Check that Fields cannot contain punctuation other than underscores
|
||||
self.assertRaises(SyntaxError, Field, 'a.bc', 'string')
|
||||
|
||||
# Check that Fields cannot be a name of a method or property of Table
|
||||
for x in ['drop', 'on', 'truncate']:
|
||||
self.assertRaises(SyntaxError, Field, x, 'string')
|
||||
|
||||
# Check that Fields allows underscores in the body of a field name.
|
||||
self.assert_(Field('a_bc', 'string'),
|
||||
"Field isn't allowing underscores in fieldnames. It should.")
|
||||
|
||||
def testFieldTypes(self):
|
||||
|
||||
# Check that string, text, and password default length is 512
|
||||
for typ in ['string', 'password']:
|
||||
self.assert_(Field('abc', typ).length == 512,
|
||||
"Default length for type '%s' is not 512 or 255" % typ)
|
||||
|
||||
# Check that upload default length is 512
|
||||
self.assert_(Field('abc', 'upload').length == 512,
|
||||
"Default length for type 'upload' is not 128")
|
||||
|
||||
# Check that Tables passed in the type creates a reference
|
||||
self.assert_(Field('abc', Table(None, 'temp')).type
|
||||
== 'reference temp',
|
||||
'Passing an Table does not result in a reference type.')
|
||||
|
||||
def testFieldLabels(self):
|
||||
|
||||
# Check that a label is successfully built from the supplied fieldname
|
||||
self.assert_(Field('abc', 'string').label == 'Abc',
|
||||
'Label built is incorrect')
|
||||
self.assert_(Field('abc_def', 'string').label == 'Abc Def',
|
||||
'Label built is incorrect')
|
||||
|
||||
def testFieldFormatters(self): # Formatter should be called Validator
|
||||
|
||||
# Test the default formatters
|
||||
for typ in ALLOWED_DATATYPES:
|
||||
f = Field('abc', typ)
|
||||
if typ not in ['date', 'time', 'datetime']:
|
||||
isinstance(f.formatter('test'), str)
|
||||
else:
|
||||
isinstance(f.formatter(datetime.datetime.now()), str)
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
for ft in ['string', 'text', 'password', 'upload', 'blob']:
|
||||
db.define_table('t', Field('a', ft, default=''))
|
||||
self.assertEqual(db.t.insert(a='x'), 1)
|
||||
self.assertEqual(db().select(db.t.a)[0].a, 'x')
|
||||
db.t.drop()
|
||||
db.define_table('t', Field('a', 'integer', default=1))
|
||||
self.assertEqual(db.t.insert(a=3), 1)
|
||||
self.assertEqual(db().select(db.t.a)[0].a, 3)
|
||||
db.t.drop()
|
||||
db.define_table('t', Field('a', 'double', default=1))
|
||||
self.assertEqual(db.t.insert(a=3.1), 1)
|
||||
self.assertEqual(db().select(db.t.a)[0].a, 3.1)
|
||||
db.t.drop()
|
||||
db.define_table('t', Field('a', 'boolean', default=True))
|
||||
self.assertEqual(db.t.insert(a=True), 1)
|
||||
self.assertEqual(db().select(db.t.a)[0].a, True)
|
||||
db.t.drop()
|
||||
db.define_table('t', Field('a', 'date',
|
||||
default=datetime.date.today()))
|
||||
t0 = datetime.date.today()
|
||||
self.assertEqual(db.t.insert(a=t0), 1)
|
||||
self.assertEqual(db().select(db.t.a)[0].a, t0)
|
||||
db.t.drop()
|
||||
db.define_table('t', Field('a', 'datetime',
|
||||
default=datetime.datetime.today()))
|
||||
t0 = datetime.datetime(
|
||||
1971,
|
||||
12,
|
||||
21,
|
||||
10,
|
||||
30,
|
||||
55,
|
||||
0,
|
||||
)
|
||||
self.assertEqual(db.t.insert(a=t0), 1)
|
||||
self.assertEqual(db().select(db.t.a)[0].a, t0)
|
||||
db.t.drop()
|
||||
db.define_table('t', Field('a', 'time', default='11:30'))
|
||||
t0 = datetime.time(10, 30, 55)
|
||||
self.assertEqual(db.t.insert(a=t0), 1)
|
||||
self.assertEqual(db().select(db.t.a)[0].a, t0)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
class TestAll(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.pt = Table(None,'PseudoTable',Field('name'),Field('birthdate'))
|
||||
|
||||
def testSQLALL(self):
|
||||
ans = 'PseudoTable.id, PseudoTable.name, PseudoTable.birthdate'
|
||||
self.assertEqual(str(SQLALL(self.pt)), ans)
|
||||
|
||||
|
||||
class TestTable(unittest.TestCase):
|
||||
|
||||
def testTableCreation(self):
|
||||
|
||||
# Check for error when not passing type other than Field or Table
|
||||
|
||||
self.assertRaises(SyntaxError, Table, None, 'test', None)
|
||||
|
||||
persons = Table(None, 'persons',
|
||||
Field('firstname','string'),
|
||||
Field('lastname', 'string'))
|
||||
|
||||
# Does it have the correct fields?
|
||||
|
||||
self.assert_(set(persons.fields).issuperset(set(['firstname',
|
||||
'lastname'])))
|
||||
|
||||
# ALL is set correctly
|
||||
|
||||
self.assert_('persons.firstname, persons.lastname'
|
||||
in str(persons.ALL))
|
||||
|
||||
def testTableAlias(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
persons = Table(db, 'persons', Field('firstname',
|
||||
'string'), Field('lastname', 'string'))
|
||||
aliens = persons.with_alias('aliens')
|
||||
|
||||
# Are the different table instances with the same fields
|
||||
|
||||
self.assert_(persons is not aliens)
|
||||
self.assert_(set(persons.fields) == set(aliens.fields))
|
||||
|
||||
def testTableInheritance(self):
|
||||
persons = Table(None, 'persons', Field('firstname',
|
||||
'string'), Field('lastname', 'string'))
|
||||
customers = Table(None, 'customers',
|
||||
Field('items_purchased', 'integer'),
|
||||
persons)
|
||||
self.assert_(set(customers.fields).issuperset(set(
|
||||
['items_purchased', 'firstname', 'lastname'])))
|
||||
|
||||
|
||||
class TestInsert(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a'))
|
||||
self.assertEqual(db.t.insert(a='1'), 1)
|
||||
self.assertEqual(db.t.insert(a='1'), 2)
|
||||
self.assertEqual(db.t.insert(a='1'), 3)
|
||||
self.assertEqual(db(db.t.a == '1').count(), 3)
|
||||
self.assertEqual(db(db.t.a == '1').update(a='2'), 3)
|
||||
self.assertEqual(db(db.t.a == '2').count(), 3)
|
||||
self.assertEqual(db(db.t.a == '2').delete(), 3)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
class TestSelect(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a'))
|
||||
self.assertEqual(db.t.insert(a='1'), 1)
|
||||
self.assertEqual(db.t.insert(a='2'), 2)
|
||||
self.assertEqual(db.t.insert(a='3'), 3)
|
||||
self.assertEqual(len(db(db.t.id > 0).select()), 3)
|
||||
self.assertEqual(db(db.t.id > 0).select(orderby=~db.t.a
|
||||
| db.t.id)[0].a, '3')
|
||||
self.assertEqual(len(db(db.t.id > 0).select(limitby=(1, 2))), 1)
|
||||
self.assertEqual(db(db.t.id > 0).select(limitby=(1, 2))[0].a,
|
||||
'2')
|
||||
self.assertEqual(len(db().select(db.t.ALL)), 3)
|
||||
self.assertEqual(len(db(db.t.a == None).select()), 0)
|
||||
self.assertEqual(len(db(db.t.a != None).select()), 3)
|
||||
self.assertEqual(len(db(db.t.a > '1').select()), 2)
|
||||
self.assertEqual(len(db(db.t.a >= '1').select()), 3)
|
||||
self.assertEqual(len(db(db.t.a == '1').select()), 1)
|
||||
self.assertEqual(len(db(db.t.a != '1').select()), 2)
|
||||
self.assertEqual(len(db(db.t.a < '3').select()), 2)
|
||||
self.assertEqual(len(db(db.t.a <= '3').select()), 3)
|
||||
self.assertEqual(len(db(db.t.a > '1')(db.t.a < '3').select()), 1)
|
||||
self.assertEqual(len(db((db.t.a > '1') & (db.t.a < '3')).select()), 1)
|
||||
self.assertEqual(len(db((db.t.a > '1') | (db.t.a < '3')).select()), 3)
|
||||
self.assertEqual(len(db((db.t.a > '1') & ~(db.t.a > '2')).select()), 1)
|
||||
self.assertEqual(len(db(~(db.t.a > '1') & (db.t.a > '2')).select()), 0)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
class TestBelongs(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a'))
|
||||
self.assertEqual(db.t.insert(a='1'), 1)
|
||||
self.assertEqual(db.t.insert(a='2'), 2)
|
||||
self.assertEqual(db.t.insert(a='3'), 3)
|
||||
self.assertEqual(len(db(db.t.a.belongs(('1', '3'))).select()),
|
||||
2)
|
||||
self.assertEqual(len(db(db.t.a.belongs(db(db.t.id
|
||||
> 2)._select(db.t.a))).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.belongs(db(db.t.a.belongs(('1',
|
||||
'3')))._select(db.t.a))).select()), 2)
|
||||
self.assertEqual(len(db(db.t.a.belongs(db(db.t.a.belongs(db
|
||||
(db.t.a.belongs(('1', '3')))._select(db.t.a)))._select(
|
||||
db.t.a))).select()),
|
||||
2)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
class TestLike(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a'))
|
||||
self.assertEqual(db.t.insert(a='abc'), 1)
|
||||
self.assertEqual(len(db(db.t.a.like('a%')).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.like('%b%')).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.like('%c')).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.like('%d%')).select()), 0)
|
||||
self.assertEqual(len(db(db.t.a.lower().like('A%')).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.lower().like('%B%')).select()),
|
||||
1)
|
||||
self.assertEqual(len(db(db.t.a.lower().like('%C')).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.upper().like('A%')).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.upper().like('%B%')).select()),
|
||||
1)
|
||||
self.assertEqual(len(db(db.t.a.upper().like('%C')).select()), 1)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
class TestDatetime(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a', 'datetime'))
|
||||
self.assertEqual(db.t.insert(a=datetime.datetime(1971, 12, 21,
|
||||
11, 30)), 1)
|
||||
self.assertEqual(db.t.insert(a=datetime.datetime(1971, 11, 21,
|
||||
10, 30)), 2)
|
||||
self.assertEqual(db.t.insert(a=datetime.datetime(1970, 12, 21,
|
||||
9, 30)), 3)
|
||||
self.assertEqual(len(db(db.t.a == datetime.datetime(1971, 12,
|
||||
21, 11, 30)).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.year() == 1971).select()), 2)
|
||||
self.assertEqual(len(db(db.t.a.month() == 12).select()), 2)
|
||||
self.assertEqual(len(db(db.t.a.day() == 21).select()), 3)
|
||||
self.assertEqual(len(db(db.t.a.hour() == 11).select()), 1)
|
||||
self.assertEqual(len(db(db.t.a.minutes() == 30).select()), 3)
|
||||
self.assertEqual(len(db(db.t.a.seconds() == 0).select()), 3)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
class TestExpressions(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a', 'integer'))
|
||||
self.assertEqual(db.t.insert(a=1), 1)
|
||||
self.assertEqual(db.t.insert(a=2), 2)
|
||||
self.assertEqual(db.t.insert(a=3), 3)
|
||||
self.assertEqual(db(db.t.a == 3).update(a=db.t.a + 1), 1)
|
||||
self.assertEqual(len(db(db.t.a == 4).select()), 1)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
class TestJoin(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t1', Field('a'))
|
||||
db.define_table('t2', Field('a'), Field('b', db.t1))
|
||||
i1 = db.t1.insert(a='1')
|
||||
i2 = db.t1.insert(a='2')
|
||||
i3 = db.t1.insert(a='3')
|
||||
db.t2.insert(a='4', b=i1)
|
||||
db.t2.insert(a='5', b=i2)
|
||||
db.t2.insert(a='6', b=i2)
|
||||
self.assertEqual(len(db(db.t1.id
|
||||
== db.t2.b).select(orderby=db.t1.a
|
||||
| db.t2.a)), 3)
|
||||
self.assertEqual(db(db.t1.id == db.t2.b).select(orderby=db.t1.a
|
||||
| db.t2.a)[2].t1.a, '2')
|
||||
self.assertEqual(db(db.t1.id == db.t2.b).select(orderby=db.t1.a
|
||||
| db.t2.a)[2].t2.a, '6')
|
||||
self.assertEqual(len(db().select(db.t1.ALL, db.t2.ALL,
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a)), 4)
|
||||
self.assertEqual(db().select(db.t1.ALL, db.t2.ALL,
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a)[2].t1.a, '2')
|
||||
self.assertEqual(db().select(db.t1.ALL, db.t2.ALL,
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a)[2].t2.a, '6')
|
||||
self.assertEqual(db().select(db.t1.ALL, db.t2.ALL,
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a)[3].t1.a, '3')
|
||||
self.assertEqual(db().select(db.t1.ALL, db.t2.ALL,
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a)[3].t2.a, None)
|
||||
self.assertEqual(len(db().select(db.t1.ALL, db.t2.id.count(),
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a, groupby=db.t1.a)),
|
||||
3)
|
||||
self.assertEqual(db().select(db.t1.ALL, db.t2.id.count(),
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a,
|
||||
groupby=db.t1.a)[0]._extra[db.t2.id.count()],
|
||||
1)
|
||||
self.assertEqual(db().select(db.t1.ALL, db.t2.id.count(),
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a,
|
||||
groupby=db.t1.a)[1]._extra[db.t2.id.count()],
|
||||
2)
|
||||
self.assertEqual(db().select(db.t1.ALL, db.t2.id.count(),
|
||||
left=db.t2.on(db.t1.id == db.t2.b),
|
||||
orderby=db.t1.a | db.t2.a,
|
||||
groupby=db.t1.a)[2]._extra[db.t2.id.count()],
|
||||
0)
|
||||
db.t1.drop()
|
||||
db.t2.drop()
|
||||
|
||||
|
||||
class TestMinMaxSum(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a', 'integer'))
|
||||
self.assertEqual(db.t.insert(a=1), 1)
|
||||
self.assertEqual(db.t.insert(a=2), 2)
|
||||
self.assertEqual(db.t.insert(a=3), 3)
|
||||
s = db.t.a.min()
|
||||
self.assertEqual(db(db.t.id > 0).select(s)[0]._extra[s], 1)
|
||||
s = db.t.a.max()
|
||||
self.assertEqual(db(db.t.id > 0).select(s)[0]._extra[s], 3)
|
||||
s = db.t.a.sum()
|
||||
self.assertEqual(db(db.t.id > 0).select(s)[0]._extra[s], 6)
|
||||
s = db.t.a.count()
|
||||
self.assertEqual(db(db.t.id > 0).select(s)[0]._extra[s], 3)
|
||||
db.t.drop()
|
||||
|
||||
|
||||
#class TestCache(unittest.
|
||||
# def testRun(self):
|
||||
# cache = cache.ram
|
||||
# db = DAL('sqlite:memory:')
|
||||
# db.define_table('t', Field('a'))
|
||||
# db.t.insert(a='1')
|
||||
# r1 = db().select(db.t.ALL, cache=(cache, 1000))
|
||||
# db.t.insert(a='1')
|
||||
# r2 = db().select(db.t.ALL, cache=(cache, 1000))
|
||||
# self.assertEqual(r1.response, r2.response)
|
||||
# db.t.drop()
|
||||
|
||||
|
||||
class TestMigrations(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite://.storage.db')
|
||||
db.define_table('t', Field('a'), migrate='.storage.table')
|
||||
db.commit()
|
||||
db = DAL('sqlite://.storage.db')
|
||||
db.define_table('t', Field('a'), Field('b'),
|
||||
migrate='.storage.table')
|
||||
db.commit()
|
||||
db = DAL('sqlite://.storage.db')
|
||||
db.define_table('t', Field('a'), Field('b', 'text'),
|
||||
migrate='.storage.table')
|
||||
db.commit()
|
||||
db = DAL('sqlite://.storage.db')
|
||||
db.define_table('t', Field('a'), migrate='.storage.table')
|
||||
db.t.drop()
|
||||
db.commit()
|
||||
|
||||
def tearDown(self):
|
||||
os.unlink('.storage.db')
|
||||
|
||||
class TestReferece(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('name'), Field('a','reference t'))
|
||||
db.commit()
|
||||
x = db.t.insert(name='max')
|
||||
assert x.id == 1
|
||||
assert x['id'] == 1
|
||||
x.a = x
|
||||
assert x.a == 1
|
||||
x.update_record()
|
||||
y = db.t[1]
|
||||
assert y.a == 1
|
||||
assert y.a.a.a.a.a.a.name == 'max'
|
||||
z=db.t.insert(name='xxx', a = y)
|
||||
assert z.a == y.id
|
||||
db.t.drop()
|
||||
db.commit()
|
||||
|
||||
class TestClientLevelOps(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a'))
|
||||
db.commit()
|
||||
db.t.insert(a="test")
|
||||
rows1 = db(db.t.id>0).select()
|
||||
rows2 = db(db.t.id>0).select()
|
||||
rows3 = rows1 & rows2
|
||||
assert len(rows3) == 2
|
||||
rows4 = rows1 | rows2
|
||||
assert len(rows4) == 1
|
||||
rows5 = rows1.find(lambda row: row.a=="test")
|
||||
assert len(rows5) == 1
|
||||
rows6 = rows2.exclude(lambda row: row.a=="test")
|
||||
assert len(rows6) == 1
|
||||
rows7 = rows5.sort(lambda row: row.a)
|
||||
assert len(rows7) == 1
|
||||
db.t.drop()
|
||||
db.commit()
|
||||
|
||||
|
||||
class TestVirtualFields(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
db = DAL('sqlite:memory:')
|
||||
db.define_table('t', Field('a'))
|
||||
db.commit()
|
||||
db.t.insert(a="test")
|
||||
class Compute:
|
||||
def a_upper(row): return row.t.a.upper()
|
||||
db.t.virtualfields.append(Compute())
|
||||
assert db(db.t.id>0).select().first().a_upper == 'TEST'
|
||||
db.t.drop()
|
||||
db.commit()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
tearDownModule()
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Unit tests for gluon.html
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon'))
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../'))
|
||||
|
||||
import unittest
|
||||
from html import *
|
||||
|
||||
|
||||
class TestBareHelpers(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
self.assertEqual(BR(_a='1', _b='2').xml(), '<br a="1" b="2" />')
|
||||
self.assertEqual(EMBED(_a='1', _b='2').xml(),
|
||||
'<embed a="1" b="2" />')
|
||||
self.assertEqual(HR(_a='1', _b='2').xml(), '<hr a="1" b="2" />')
|
||||
self.assertEqual(IMG(_a='1', _b='2').xml(),
|
||||
'<img a="1" b="2" />')
|
||||
self.assertEqual(INPUT(_a='1', _b='2').xml(),
|
||||
'<input a="1" b="2" type="text" />')
|
||||
self.assertEqual(LINK(_a='1', _b='2').xml(),
|
||||
'<link a="1" b="2" />')
|
||||
self.assertEqual(META(_a='1', _b='2').xml(),
|
||||
'<meta a="1" b="2" />')
|
||||
|
||||
self.assertEqual(A('<>', _a='1', _b='2').xml(),
|
||||
'<a a="1" b="2"><></a>')
|
||||
self.assertEqual(B('<>', _a='1', _b='2').xml(),
|
||||
'<b a="1" b="2"><></b>')
|
||||
self.assertEqual(BODY('<>', _a='1', _b='2').xml(),
|
||||
'<body a="1" b="2"><></body>')
|
||||
self.assertEqual(CENTER('<>', _a='1', _b='2').xml(),
|
||||
'<center a="1" b="2"><></center>')
|
||||
self.assertEqual(DIV('<>', _a='1', _b='2').xml(),
|
||||
'<div a="1" b="2"><></div>')
|
||||
self.assertEqual(EM('<>', _a='1', _b='2').xml(),
|
||||
'<em a="1" b="2"><></em>')
|
||||
self.assertEqual(FIELDSET('<>', _a='1', _b='2').xml(),
|
||||
'<fieldset a="1" b="2"><></fieldset>')
|
||||
self.assertEqual(FORM('<>', _a='1', _b='2').xml(),
|
||||
'<form a="1" action="" b="2" enctype="multipart/form-data" method="post"><></form>')
|
||||
self.assertEqual(H1('<>', _a='1', _b='2').xml(),
|
||||
'<h1 a="1" b="2"><></h1>')
|
||||
self.assertEqual(H2('<>', _a='1', _b='2').xml(),
|
||||
'<h2 a="1" b="2"><></h2>')
|
||||
self.assertEqual(H3('<>', _a='1', _b='2').xml(),
|
||||
'<h3 a="1" b="2"><></h3>')
|
||||
self.assertEqual(H4('<>', _a='1', _b='2').xml(),
|
||||
'<h4 a="1" b="2"><></h4>')
|
||||
self.assertEqual(H5('<>', _a='1', _b='2').xml(),
|
||||
'<h5 a="1" b="2"><></h5>')
|
||||
self.assertEqual(H6('<>', _a='1', _b='2').xml(),
|
||||
'<h6 a="1" b="2"><></h6>')
|
||||
self.assertEqual(HEAD('<>', _a='1', _b='2').xml(),
|
||||
'<head a="1" b="2"><></head>')
|
||||
self.assertEqual(HTML('<>', _a='1', _b='2').xml(),
|
||||
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n<html a="1" b="2" lang="en"><></html>')
|
||||
self.assertEqual(IFRAME('<>', _a='1', _b='2').xml(),
|
||||
'<iframe a="1" b="2"><></iframe>')
|
||||
self.assertEqual(LABEL('<>', _a='1', _b='2').xml(),
|
||||
'<label a="1" b="2"><></label>')
|
||||
self.assertEqual(LI('<>', _a='1', _b='2').xml(),
|
||||
'<li a="1" b="2"><></li>')
|
||||
self.assertEqual(OBJECT('<>', _a='1', _b='2').xml(),
|
||||
'<object a="1" b="2"><></object>')
|
||||
self.assertEqual(OL('<>', _a='1', _b='2').xml(),
|
||||
'<ol a="1" b="2"><li><></li></ol>')
|
||||
self.assertEqual(OPTION('<>', _a='1', _b='2').xml(),
|
||||
'<option a="1" b="2" value="<>"><>' + \
|
||||
'</option>')
|
||||
self.assertEqual(P('<>', _a='1', _b='2').xml(),
|
||||
'<p a="1" b="2"><></p>')
|
||||
self.assertEqual(PRE('<>', _a='1', _b='2').xml(),
|
||||
'<pre a="1" b="2"><></pre>')
|
||||
self.assertEqual(SCRIPT('<>', _a='1', _b='2').xml(),
|
||||
'''<script a="1" b="2"><!--
|
||||
<>
|
||||
//--></script>''')
|
||||
self.assertEqual(SELECT('<>', _a='1', _b='2').xml(),
|
||||
'<select a="1" b="2">'+ \
|
||||
'<option value="<>"><></option></select>')
|
||||
self.assertEqual(SPAN('<>', _a='1', _b='2').xml(),
|
||||
'<span a="1" b="2"><></span>')
|
||||
self.assertEqual(STYLE('<>', _a='1', _b='2').xml(),
|
||||
'<style a="1" b="2"><!--/*--><![CDATA[/*><!--*/\n<>\n/*]]>*/--></style>')
|
||||
self.assertEqual(TABLE('<>', _a='1', _b='2').xml(),
|
||||
'<table a="1" b="2"><tr><td><></td></tr>' + \
|
||||
'</table>')
|
||||
self.assertEqual(TBODY('<>', _a='1', _b='2').xml(),
|
||||
'<tbody a="1" b="2"><tr><td><></td></tr></tbody>')
|
||||
self.assertEqual(TD('<>', _a='1', _b='2').xml(),
|
||||
'<td a="1" b="2"><></td>')
|
||||
self.assertEqual(TEXTAREA('<>', _a='1', _b='2').xml(),
|
||||
'<textarea a="1" b="2" cols="40" rows="10"><>' + \
|
||||
'</textarea>')
|
||||
self.assertEqual(TFOOT('<>', _a='1', _b='2').xml(),
|
||||
'<tfoot a="1" b="2"><tr><td><></td></tr></tfoot>')
|
||||
self.assertEqual(TH('<>', _a='1', _b='2').xml(),
|
||||
'<th a="1" b="2"><></th>')
|
||||
self.assertEqual(THEAD('<>', _a='1', _b='2').xml(),
|
||||
'<thead a="1" b="2"><tr><td><></td></tr></thead>')
|
||||
self.assertEqual(TITLE('<>', _a='1', _b='2').xml(),
|
||||
'<title a="1" b="2"><></title>')
|
||||
self.assertEqual(TR('<>', _a='1', _b='2').xml(),
|
||||
'<tr a="1" b="2"><td><></td></tr>')
|
||||
self.assertEqual(TT('<>', _a='1', _b='2').xml(),
|
||||
'<tt a="1" b="2"><></tt>')
|
||||
self.assertEqual(UL('<>', _a='1', _b='2').xml(),
|
||||
'<ul a="1" b="2"><li><></li></ul>')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,644 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Unit tests for IS_URL()
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon'))
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../'))
|
||||
|
||||
import unittest
|
||||
from validators import IS_URL, IS_HTTP_URL, IS_GENERIC_URL, \
|
||||
unicode_to_ascii_authority
|
||||
|
||||
|
||||
class TestIsUrl(unittest.TestCase):
|
||||
|
||||
def testModeHttp(self):
|
||||
|
||||
# defaults to mode='http'
|
||||
|
||||
x = IS_URL()
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('google.ca'), ('http://google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('http://google.ca:80',
|
||||
None))
|
||||
self.assertEqual(x('unreal.blargg'), ('unreal.blargg',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('google..ca'), ('google..ca', 'enter a valid URL'))
|
||||
self.assertEqual(x('google.ca..'), ('google.ca..', 'enter a valid URL'))
|
||||
|
||||
# explicit use of 'http' mode
|
||||
|
||||
x = IS_URL(mode='http')
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('google.ca'), ('http://google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('http://google.ca:80',
|
||||
None))
|
||||
self.assertEqual(x('unreal.blargg'), ('unreal.blargg',
|
||||
'enter a valid URL'))
|
||||
|
||||
# prepends 'https' instead of 'http'
|
||||
|
||||
x = IS_URL(mode='http', prepend_scheme='https')
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('google.ca'), ('https://google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('https://google.ca:80',
|
||||
None))
|
||||
self.assertEqual(x('unreal.blargg'), ('unreal.blargg',
|
||||
'enter a valid URL'))
|
||||
|
||||
# prepending disabled
|
||||
|
||||
x = IS_URL(prepend_scheme=None)
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('google.ca'), ('google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('google.ca:80', None))
|
||||
self.assertEqual(x('unreal.blargg'), ('unreal.blargg',
|
||||
'enter a valid URL'))
|
||||
|
||||
# custom allowed_schemes
|
||||
|
||||
x = IS_URL(mode='http', allowed_schemes=[None, 'http'])
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('https://google.ca'), ('https://google.ca',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('google.ca'), ('http://google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('http://google.ca:80',
|
||||
None))
|
||||
self.assertEqual(x('unreal.blargg'), ('unreal.blargg',
|
||||
'enter a valid URL'))
|
||||
|
||||
# custom allowed_schemes, excluding None
|
||||
|
||||
x = IS_URL(allowed_schemes=['http'])
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('https://google.ca'), ('https://google.ca',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
self.assertEqual(x('google.ca:80'), ('google.ca:80',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('unreal.blargg'), ('unreal.blargg',
|
||||
'enter a valid URL'))
|
||||
|
||||
# custom allowed_schemes and prepend_scheme
|
||||
|
||||
x = IS_URL(allowed_schemes=[None, 'https'],
|
||||
prepend_scheme='https')
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('https://google.ca'), ('https://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('google.ca'), ('https://google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('https://google.ca:80',
|
||||
None))
|
||||
self.assertEqual(x('unreal.blargg'), ('unreal.blargg',
|
||||
'enter a valid URL'))
|
||||
|
||||
# Now any URL requiring prepending will fail, but prepending is still
|
||||
# enabled!
|
||||
|
||||
x = IS_URL(allowed_schemes=['http'])
|
||||
self.assertEqual(x('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
|
||||
def testModeGeneric(self):
|
||||
|
||||
# 'generic' mode
|
||||
|
||||
x = IS_URL(mode='generic')
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',None))
|
||||
self.assertEqual(x('google.ca'), ('google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('http://google.ca:80',None))
|
||||
self.assertEqual(x('blargg://unreal'), ('blargg://unreal',
|
||||
'enter a valid URL'))
|
||||
|
||||
# 'generic' mode with custom allowed_schemes that still includes
|
||||
# 'http' (the default for prepend_scheme)
|
||||
|
||||
x = IS_URL(mode='generic', allowed_schemes=['http', 'blargg'])
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('ftp://google.ca'), ('ftp://google.ca',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
self.assertEqual(x('google.ca:80'), ('google.ca:80',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('blargg://unreal'), ('blargg://unreal',
|
||||
None))
|
||||
|
||||
# 'generic' mode with overriden prepend_scheme
|
||||
|
||||
x = IS_URL(mode='generic', prepend_scheme='ftp')
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('ftp://google.ca'), ('ftp://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('google.ca'), ('google.ca', None))
|
||||
self.assertEqual(x('google.ca:80'), ('ftp://google.ca:80',
|
||||
None))
|
||||
self.assertEqual(x('blargg://unreal'), ('blargg://unreal',
|
||||
'enter a valid URL'))
|
||||
|
||||
# 'generic' mode with overriden allowed_schemes and prepend_scheme
|
||||
|
||||
x = IS_URL(mode='generic', allowed_schemes=[None, 'ftp', 'ftps'
|
||||
], prepend_scheme='ftp')
|
||||
self.assertEqual(x('http://google.ca'), ('http://google.ca',
|
||||
'enter a valid URL'))
|
||||
self.assertEqual(x('google.ca'), ('google.ca', None))
|
||||
self.assertEqual(x('ftp://google.ca'), ('ftp://google.ca',
|
||||
None))
|
||||
self.assertEqual(x('google.ca:80'), ('ftp://google.ca:80',
|
||||
None))
|
||||
self.assertEqual(x('blargg://unreal'), ('blargg://unreal',
|
||||
'enter a valid URL'))
|
||||
|
||||
# Now any URL requiring prepending will fail, but prepending is still
|
||||
# enabled!
|
||||
|
||||
x = IS_URL(mode='generic', allowed_schemes=['http'])
|
||||
self.assertEqual(x('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
|
||||
def testExceptionalUse(self):
|
||||
|
||||
# mode must be in set ['http', 'generic']
|
||||
|
||||
try:
|
||||
x = IS_URL(mode='ftp')
|
||||
x('http://www.google.ca')
|
||||
except Exception, e:
|
||||
if str(e) != "invalid mode 'ftp' in IS_URL":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid mode: 'ftp'")
|
||||
|
||||
# allowed_schemes in 'http' mode must be in set [None, 'http', 'https']
|
||||
|
||||
try:
|
||||
x = IS_URL(allowed_schemes=[None, 'ftp', 'ftps'],
|
||||
prepend_scheme='ftp')
|
||||
x('http://www.benn.ca') # we can only reasonably know about the
|
||||
# error at calling time
|
||||
except Exception, e:
|
||||
if str(e)\
|
||||
!= "allowed_scheme value 'ftp' is not in [None, 'http', 'https']":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid allowed_schemes: [None, 'ftp', 'ftps']")
|
||||
|
||||
# prepend_scheme's value must be in allowed_schemes (default for 'http'
|
||||
# mode is [None, 'http', 'https'])
|
||||
|
||||
try:
|
||||
x = IS_URL(prepend_scheme='ftp')
|
||||
x('http://www.benn.ca') # we can only reasonably know about the
|
||||
# error at calling time
|
||||
except Exception, e:
|
||||
if str(e)\
|
||||
!= "prepend_scheme='ftp' is not in allowed_schemes=[None, 'http', 'https']":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid prepend_scheme: 'ftp'")
|
||||
|
||||
# custom allowed_schemes that excludes 'http', so prepend_scheme must be
|
||||
# specified!
|
||||
|
||||
try:
|
||||
x = IS_URL(allowed_schemes=[None, 'https'])
|
||||
except Exception, e:
|
||||
if str(e)\
|
||||
!= "prepend_scheme='http' is not in allowed_schemes=[None, 'https']":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid prepend_scheme: 'http'")
|
||||
|
||||
# prepend_scheme must be in allowed_schemes
|
||||
|
||||
try:
|
||||
x = IS_URL(allowed_schemes=[None, 'http'],
|
||||
prepend_scheme='https')
|
||||
except Exception, e:
|
||||
if str(e)\
|
||||
!= "prepend_scheme='https' is not in allowed_schemes=[None, 'http']":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid prepend_scheme: 'https'")
|
||||
|
||||
# prepend_scheme's value (default is 'http') must be in allowed_schemes
|
||||
|
||||
try:
|
||||
x = IS_URL(mode='generic', allowed_schemes=[None, 'ftp',
|
||||
'ftps'])
|
||||
except Exception, e:
|
||||
if str(e)\
|
||||
!= "prepend_scheme='http' is not in allowed_schemes=[None, 'ftp', 'ftps']":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid prepend_scheme: 'http'")
|
||||
|
||||
# prepend_scheme's value must be in allowed_schemes, which by default
|
||||
# is all schemes that really exist
|
||||
|
||||
try:
|
||||
x = IS_URL(mode='generic', prepend_scheme='blargg')
|
||||
x('http://www.google.ca') # we can only reasonably know about the error at calling time
|
||||
except Exception, e:
|
||||
if not str(e).startswith(
|
||||
"prepend_scheme='blargg' is not in allowed_schemes="):
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid prepend_scheme: 'blargg'")
|
||||
|
||||
# prepend_scheme's value must be in allowed_schemes
|
||||
|
||||
try:
|
||||
x = IS_URL(mode='generic', allowed_schemes=[None, 'http'],
|
||||
prepend_scheme='blargg')
|
||||
except Exception, e:
|
||||
if str(e)\
|
||||
!= "prepend_scheme='blargg' is not in allowed_schemes=[None, 'http']":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Accepted invalid prepend_scheme: 'blargg'")
|
||||
|
||||
# Not inluding None in the allowed_schemes essentially disabled
|
||||
# prepending, so even though
|
||||
# prepend_scheme has the invalid value 'http', we don't care!
|
||||
|
||||
x = IS_URL(allowed_schemes=['https'], prepend_scheme='https')
|
||||
self.assertEqual(x('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
|
||||
# Not inluding None in the allowed_schemes essentially disabled prepending, so even though
|
||||
# prepend_scheme has the invalid value 'http', we don't care!
|
||||
|
||||
x = IS_URL(mode='generic', allowed_schemes=['https'],
|
||||
prepend_scheme='https')
|
||||
self.assertEqual(x('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
|
||||
|
||||
# ##############################################################################
|
||||
|
||||
|
||||
class TestIsGenericUrl(unittest.TestCase):
|
||||
|
||||
x = IS_GENERIC_URL()
|
||||
|
||||
def testInvalidUrls(self):
|
||||
urlsToCheckA = []
|
||||
for i in range(0, 32) + [127]:
|
||||
|
||||
# Control characters are disallowed in any part of a URL
|
||||
|
||||
urlsToCheckA.append('http://www.benn' + chr(i) + '.ca')
|
||||
|
||||
urlsToCheckB = [
|
||||
None,
|
||||
'',
|
||||
'http://www.no spaces allowed.com',
|
||||
'http://www.benn.ca/no spaces allowed/',
|
||||
'http://www.benn.ca/angle_<bracket/',
|
||||
'http://www.benn.ca/angle_>bracket/',
|
||||
'http://www.benn.ca/invalid%character',
|
||||
'http://www.benn.ca/illegal%%20use',
|
||||
'http://www.benn.ca/illegaluse%',
|
||||
'http://www.benn.ca/illegaluse%0',
|
||||
'http://www.benn.ca/illegaluse%x',
|
||||
'http://www.benn.ca/ill%egaluse%x',
|
||||
'http://www.benn.ca/double"quote/',
|
||||
'http://www.curly{brace.com',
|
||||
'http://www.benn.ca/curly}brace/',
|
||||
'http://www.benn.ca/or|symbol/',
|
||||
'http://www.benn.ca/back\slash',
|
||||
'http://www.benn.ca/the^carat',
|
||||
'http://left[bracket.me',
|
||||
'http://www.benn.ca/right]bracket',
|
||||
'http://www.benn.ca/angle`quote',
|
||||
'-ttp://www.benn.ca',
|
||||
'+ttp://www.benn.ca',
|
||||
'.ttp://www.benn.ca',
|
||||
'9ttp://www.benn.ca',
|
||||
'ht;tp://www.benn.ca',
|
||||
'ht@tp://www.benn.ca',
|
||||
'ht&tp://www.benn.ca',
|
||||
'ht=tp://www.benn.ca',
|
||||
'ht$tp://www.benn.ca',
|
||||
'ht,tp://www.benn.ca',
|
||||
'ht:tp://www.benn.ca',
|
||||
'htp://invalid_scheme.com',
|
||||
]
|
||||
|
||||
failures = []
|
||||
|
||||
for url in urlsToCheckA + urlsToCheckB:
|
||||
if self.x(url)[1] == None:
|
||||
failures.append('Incorrectly accepted: ' + str(url))
|
||||
|
||||
if len(failures) > 0:
|
||||
self.fail(failures)
|
||||
|
||||
def testValidUrls(self):
|
||||
urlsToCheck = [
|
||||
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
|
||||
'gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles',
|
||||
'http://www.math.uio.no/faq/compression-faq/part1.html',
|
||||
'mailto:mduerst@ifi.unizh.ch',
|
||||
'news:comp.infosystems.www.servers.unix',
|
||||
'telnet://melvyl.ucop.edu/',
|
||||
'hTTp://www.benn.ca',
|
||||
'%66%74%70://ftp.is.co.za/rfc/rfc1808.txt',
|
||||
'%46%74%70://ftp.is.co.za/rfc/rfc1808.txt',
|
||||
'/faq/compression-faq/part1.html',
|
||||
'google.com',
|
||||
'www.google.com:8080',
|
||||
'128.127.123.250:8080',
|
||||
'blargg:ping',
|
||||
'http://www.benn.ca',
|
||||
'http://benn.ca',
|
||||
'http://amazon.com/books/',
|
||||
'https://amazon.com/movies',
|
||||
'rtsp://idontknowthisprotocol',
|
||||
'HTTP://allcaps.com',
|
||||
'http://localhost',
|
||||
'http://localhost#fragment',
|
||||
'http://localhost/hello',
|
||||
'http://localhost/hello?query=True',
|
||||
'http://localhost/hello/',
|
||||
'http://localhost:8080',
|
||||
'http://localhost:8080/',
|
||||
'http://localhost:8080/hello',
|
||||
'http://localhost:8080/hello/',
|
||||
'file:///C:/Documents%20and%20Settings/Jonathan/Desktop/view.py'
|
||||
,
|
||||
]
|
||||
|
||||
failures = []
|
||||
|
||||
for url in urlsToCheck:
|
||||
if self.x(url)[1] != None:
|
||||
failures.append('Incorrectly rejected: ' + str(url))
|
||||
|
||||
if len(failures) > 0:
|
||||
self.fail(failures)
|
||||
|
||||
def testPrepending(self):
|
||||
# Does not prepend scheme for abbreviated domains
|
||||
self.assertEqual(self.x('google.ca'), ('google.ca', None))
|
||||
|
||||
# Does not prepend scheme for abbreviated domains
|
||||
self.assertEqual(self.x('google.ca:8080'), ('google.ca:8080', None))
|
||||
|
||||
# Does not prepend when scheme already exists
|
||||
self.assertEqual(self.x('https://google.ca'),
|
||||
('https://google.ca', None))
|
||||
|
||||
# Does not prepend if None type is not specified in allowed_scheme,
|
||||
# because a scheme is required
|
||||
|
||||
y = IS_GENERIC_URL(allowed_schemes=['http', 'blargg'],
|
||||
prepend_scheme='http')
|
||||
self.assertEqual(y('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
|
||||
|
||||
# ##############################################################################
|
||||
|
||||
|
||||
class TestIsHttpUrl(unittest.TestCase):
|
||||
|
||||
x = IS_HTTP_URL()
|
||||
|
||||
def testInvalidUrls(self):
|
||||
urlsToCheck = [
|
||||
None,
|
||||
'',
|
||||
'http://invalid' + chr(2) + '.com',
|
||||
'htp://invalid_scheme.com',
|
||||
'blargg://invalid_scheme.com',
|
||||
'http://-123.com',
|
||||
'http://abcd-.ca',
|
||||
'http://-abc123-.me',
|
||||
'http://www.dom&ain.com/',
|
||||
'http://www.dom=ain.com/',
|
||||
'http://www.benn.ca&',
|
||||
'http://%62%65%6E%6E%2E%63%61/path',
|
||||
'http://.domain.com',
|
||||
'http://.domain.com./path',
|
||||
'http://domain..com',
|
||||
'http://domain...at..com',
|
||||
'http://domain.com..',
|
||||
'http://domain.com../path',
|
||||
'http://domain.3m',
|
||||
'http://domain.-3m',
|
||||
'http://domain.3m-',
|
||||
'http://domain.-3m-',
|
||||
'http://domain.co&m',
|
||||
'http://domain.m3456',
|
||||
'http://domain.m-3/path#fragment',
|
||||
'http://domain.m---k/path?query=value',
|
||||
'http://23.32..',
|
||||
'http://23..32.56.0',
|
||||
'http://38997.222.999',
|
||||
'http://23.32.56.99.',
|
||||
'http://.23.32.56.99',
|
||||
'http://.23.32.56.99.',
|
||||
'http://w127.123.0.256:8080',
|
||||
'http://23.32.56.99:abcd',
|
||||
'http://23.32.56.99:23cd',
|
||||
'http://google.com:cd22',
|
||||
'http://23.32:1300.56.99',
|
||||
'http://www.yahoo:1600.com',
|
||||
'path/segment/without/starting/slash',
|
||||
'http://www.math.uio.no;param=3',
|
||||
'://ABC.com:/%7esmith/home.html',
|
||||
]
|
||||
|
||||
failures = []
|
||||
|
||||
for url in urlsToCheck:
|
||||
if self.x(url)[1] == None:
|
||||
failures.append('Incorrectly accepted: ' + str(url))
|
||||
|
||||
if len(failures) > 0:
|
||||
self.fail(failures)
|
||||
|
||||
def testValidUrls(self):
|
||||
|
||||
urlsToCheck = [
|
||||
'http://abc.com:80/~smith/home.html',
|
||||
'http://ABC.com/%7Esmith/home.html',
|
||||
'http://ABC.com:/%7esmith/home.html',
|
||||
'http://www.math.uio.no/faq/compression-faq/part1.html',
|
||||
'//google.ca/faq/compression-faq/part1.html',
|
||||
'//google.ca/faq;param=3',
|
||||
'//google.ca/faq/index.html?query=5',
|
||||
'//google.ca/faq/index.html;param=value?query=5',
|
||||
'/faq/compression-faq/part1.html',
|
||||
'/faq;param=3',
|
||||
'/faq/index.html?query=5',
|
||||
'/faq/index.html;param=value?query=5',
|
||||
'google.com',
|
||||
'benn.ca/init/default',
|
||||
'benn.ca/init;param=value/default?query=value',
|
||||
'http://host-name---with-dashes.me',
|
||||
'http://www.host-name---with-dashes.me',
|
||||
'http://a.com',
|
||||
'http://a.3.com',
|
||||
'http://a.bl-ck.com',
|
||||
'http://bl-e.b.com',
|
||||
'http://host123with456numbers.ca',
|
||||
'http://1234567890.com.',
|
||||
'http://1234567890.com./path',
|
||||
'http://google.com./path',
|
||||
'http://domain.xn--0zwm56d',
|
||||
'http://127.123.0.256',
|
||||
'http://127.123.0.256/document/drawer',
|
||||
'127.123.0.256/document/',
|
||||
'156.212.123.100',
|
||||
'http://www.google.com:180200',
|
||||
'http://www.google.com:8080/path',
|
||||
'http://www.google.com:8080',
|
||||
'//www.google.com:8080',
|
||||
'www.google.com:8080',
|
||||
'http://127.123.0.256:8080/path',
|
||||
'//127.123.0.256:8080',
|
||||
'127.123.0.256:8080',
|
||||
'http://example.me??query=value?',
|
||||
'http://a.com',
|
||||
'http://3.com',
|
||||
'http://www.benn.ca',
|
||||
'http://benn.ca',
|
||||
'http://amazon.com/books/',
|
||||
'https://amazon.com/movies',
|
||||
'hTTp://allcaps.com',
|
||||
'http://localhost',
|
||||
'HTTPS://localhost.',
|
||||
'http://localhost#fragment',
|
||||
'http://localhost/hello;param=value',
|
||||
'http://localhost/hello;param=value/hi;param2=value2;param3=value3'
|
||||
,
|
||||
'http://localhost/hello?query=True',
|
||||
'http://www.benn.ca/hello;param=value/hi;param2=value2;param3=value3/index.html?query=3',
|
||||
'http://localhost/hello/?query=1500&five=6',
|
||||
'http://localhost:8080',
|
||||
'http://localhost:8080/',
|
||||
'http://localhost:8080/hello',
|
||||
'http://localhost:8080/hello%20world/',
|
||||
'http://www.a.3.be-nn.5.ca',
|
||||
'http://www.amazon.COM',
|
||||
]
|
||||
|
||||
failures = []
|
||||
|
||||
for url in urlsToCheck:
|
||||
if self.x(url)[1] != None:
|
||||
failures.append('Incorrectly rejected: ' + str(url))
|
||||
|
||||
if len(failures) > 0:
|
||||
self.fail(failures)
|
||||
|
||||
def testPrepending(self):
|
||||
# prepends scheme for abbreviated domains
|
||||
self.assertEqual(self.x('google.ca'), ('http://google.ca', None))
|
||||
|
||||
# prepends scheme for abbreviated domains
|
||||
self.assertEqual(self.x('google.ca:8080'),
|
||||
('http://google.ca:8080', None))
|
||||
|
||||
# does not prepend when scheme already exists
|
||||
self.assertEqual(self.x('https://google.ca'),
|
||||
('https://google.ca', None))
|
||||
|
||||
y = IS_HTTP_URL(prepend_scheme='https', allowed_schemes=[None, 'https'])
|
||||
self.assertEqual(y('google.ca'), ('https://google.ca', None)) # prepends https if asked
|
||||
|
||||
z = IS_HTTP_URL(prepend_scheme=None)
|
||||
self.assertEqual(z('google.ca:8080'), ('google.ca:8080', None)) # prepending disabled
|
||||
|
||||
try:
|
||||
IS_HTTP_URL(prepend_scheme='mailto')
|
||||
except Exception, e:
|
||||
if str(e)\
|
||||
!= "prepend_scheme='mailto' is not in allowed_schemes=[None, 'http', 'https']":
|
||||
self.fail('Wrong exception: ' + str(e))
|
||||
else:
|
||||
self.fail("Got invalid prepend_scheme: 'mailto'")
|
||||
|
||||
# Does not prepend if None type is not specified in allowed_scheme, because a scheme is required
|
||||
|
||||
a = IS_HTTP_URL(allowed_schemes=['http'])
|
||||
self.assertEqual(a('google.ca'), ('google.ca', 'enter a valid URL'))
|
||||
self.assertEqual(a('google.ca:80'), ('google.ca:80',
|
||||
'enter a valid URL'))
|
||||
|
||||
class TestUnicode(unittest.TestCase):
|
||||
x = IS_URL()
|
||||
y = IS_URL(allowed_schemes=['https'], prepend_scheme='https') #excludes the option for abbreviated URLs with no scheme
|
||||
z = IS_URL(prepend_scheme=None) # disables prepending the scheme in the return value
|
||||
|
||||
|
||||
def testUnicodeToAsciiUrl(self):
|
||||
self.assertEquals(unicode_to_ascii_authority(u'www.Alliancefran\xe7aise.nu'), 'www.xn--alliancefranaise-npb.nu')
|
||||
self.assertEquals(unicode_to_ascii_authority(u'www.benn.ca'), 'www.benn.ca')
|
||||
self.assertRaises(UnicodeError, unicode_to_ascii_authority, u'\u4e2d'*1000) #label is too long
|
||||
|
||||
|
||||
def testValidUrls(self):
|
||||
self.assertEquals(self.x(u'www.Alliancefrancaise.nu'), ('http://www.Alliancefrancaise.nu', None))
|
||||
self.assertEquals(self.x(u'www.Alliancefran\xe7aise.nu'), ('http://www.xn--alliancefranaise-npb.nu', None))
|
||||
self.assertEquals(self.x(u'www.Alliancefran\xe7aise.nu:8080'), ('http://www.xn--alliancefranaise-npb.nu:8080', None))
|
||||
self.assertEquals(self.x(u'http://www.Alliancefran\xe7aise.nu'), ('http://www.xn--alliancefranaise-npb.nu', None))
|
||||
self.assertEquals(self.x(u'http://www.Alliancefran\xe7aise.nu/parnaise/blue'), ('http://www.xn--alliancefranaise-npb.nu/parnaise/blue', None))
|
||||
self.assertEquals(self.x(u'http://www.Alliancefran\xe7aise.nu/parnaise/blue#fragment'), ('http://www.xn--alliancefranaise-npb.nu/parnaise/blue#fragment', None))
|
||||
self.assertEquals(self.x(u'http://www.Alliancefran\xe7aise.nu/parnaise/blue?query=value#fragment'), ('http://www.xn--alliancefranaise-npb.nu/parnaise/blue?query=value#fragment', None))
|
||||
self.assertEquals(self.x(u'http://www.Alliancefran\xe7aise.nu:8080/parnaise/blue?query=value#fragment'), ('http://www.xn--alliancefranaise-npb.nu:8080/parnaise/blue?query=value#fragment', None))
|
||||
self.assertEquals(self.x(u'www.Alliancefran\xe7aise.nu/parnaise/blue?query=value#fragment'), ('http://www.xn--alliancefranaise-npb.nu/parnaise/blue?query=value#fragment', None))
|
||||
self.assertEquals(self.x(u'http://\u4e2d\u4fd4.com'), ('http://xn--fiq13b.com', None))
|
||||
self.assertEquals(self.x(u'http://\u4e2d\u4fd4.com/\u4e86'), ('http://xn--fiq13b.com/%4e%86', None))
|
||||
self.assertEquals(self.x(u'http://\u4e2d\u4fd4.com/\u4e86?query=\u4e86'), ('http://xn--fiq13b.com/%4e%86?query=%4e%86', None))
|
||||
self.assertEquals(self.x(u'http://\u4e2d\u4fd4.com/\u4e86?query=\u4e86#fragment'), ('http://xn--fiq13b.com/%4e%86?query=%4e%86#fragment', None))
|
||||
self.assertEquals(self.x(u'http://\u4e2d\u4fd4.com?query=\u4e86#fragment'), ('http://xn--fiq13b.com?query=%4e%86#fragment', None))
|
||||
self.assertEquals(self.x(u'http://B\xfccher.ch'), ('http://xn--bcher-kva.ch', None))
|
||||
self.assertEquals(self.x(u'http://\xe4\xf6\xfc\xdf.com'), ('http://xn--ss-uia6e4a.com', None))
|
||||
self.assertEquals(self.x(u'http://visegr\xe1d.com'), ('http://xn--visegrd-mwa.com', None))
|
||||
self.assertEquals(self.x(u'http://h\xe1zipatika.com'), ('http://xn--hzipatika-01a.com', None))
|
||||
self.assertEquals(self.x(u'http://www.\xe7ukurova.com'), ('http://www.xn--ukurova-txa.com', None))
|
||||
self.assertEquals(self.x(u'http://nixier\xf6hre.nixieclock-tube.com'), ('http://xn--nixierhre-57a.nixieclock-tube.com', None))
|
||||
self.assertEquals(self.x(u'google.ca.'), ('http://google.ca.', None))
|
||||
|
||||
self.assertEquals(self.y(u'https://google.ca'), ('https://google.ca', None))
|
||||
self.assertEquals(self.y(u'https://\u4e2d\u4fd4.com'), ('https://xn--fiq13b.com', None))
|
||||
|
||||
self.assertEquals(self.z(u'google.ca'), ('google.ca', None))
|
||||
|
||||
|
||||
def testInvalidUrls(self):
|
||||
self.assertEquals(self.x(u'://ABC.com'), (u'://ABC.com', 'enter a valid URL'))
|
||||
self.assertEquals(self.x(u'http://\u4e2d\u4fd4.dne'), (u'http://\u4e2d\u4fd4.dne', 'enter a valid URL'))
|
||||
self.assertEquals(self.x(u'https://google.dne'), (u'https://google.dne', 'enter a valid URL'))
|
||||
self.assertEquals(self.x(u'https://google..ca'), (u'https://google..ca', 'enter a valid URL'))
|
||||
self.assertEquals(self.x(u'google..ca'), (u'google..ca', 'enter a valid URL'))
|
||||
self.assertEquals(self.x(u'http://' + u'\u4e2d'*1000 + u'.com'), (u'http://' + u'\u4e2d'*1000 + u'.com', 'enter a valid URL'))
|
||||
|
||||
self.assertEquals(self.x(u'http://google.com#fragment_\u4e86'), (u'http://google.com#fragment_\u4e86', 'enter a valid URL'))
|
||||
self.assertEquals(self.x(u'http\u4e86://google.com'), (u'http\u4e86://google.com', 'enter a valid URL'))
|
||||
self.assertEquals(self.x(u'http\u4e86://google.com#fragment_\u4e86'), (u'http\u4e86://google.com#fragment_\u4e86', 'enter a valid URL'))
|
||||
|
||||
self.assertEquals(self.y(u'http://\u4e2d\u4fd4.com/\u4e86'), (u'http://\u4e2d\u4fd4.com/\u4e86', 'enter a valid URL'))
|
||||
#self.assertEquals(self.y(u'google.ca'), (u'google.ca', 'enter a valid URL'))
|
||||
|
||||
self.assertEquals(self.z(u'invalid.domain..com'), (u'invalid.domain..com', 'enter a valid URL'))
|
||||
self.assertEquals(self.z(u'invalid.\u4e2d\u4fd4.blargg'), (u'invalid.\u4e2d\u4fd4.blargg', 'enter a valid URL'))
|
||||
|
||||
# ##############################################################################
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,872 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""Unit tests for rewrite.py routers option"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import unittest
|
||||
import tempfile
|
||||
import logging
|
||||
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon')) # running from web2py base
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../')) # running from gluon/tests/
|
||||
|
||||
from rewrite import load, filter_url, filter_err, get_effective_router, map_url_out
|
||||
from html import URL
|
||||
from fileutils import abspath
|
||||
from settings import global_settings
|
||||
from http import HTTP
|
||||
from storage import Storage
|
||||
|
||||
logger = None
|
||||
oldcwd = None
|
||||
root = None
|
||||
|
||||
def setUpModule():
|
||||
def make_apptree():
|
||||
"build a temporary applications tree"
|
||||
# applications/
|
||||
os.mkdir(abspath('applications'))
|
||||
# applications/app/
|
||||
for app in ('admin', 'examples', 'welcome'):
|
||||
os.mkdir(abspath('applications', app))
|
||||
# applications/app/(controllers, static)
|
||||
for subdir in ('controllers', 'static'):
|
||||
os.mkdir(abspath('applications', app, subdir))
|
||||
# applications/admin/controllers/*.py
|
||||
for ctr in ('appadmin', 'default', 'gae', 'mercurial', 'shell', 'wizard'):
|
||||
open(abspath('applications', 'admin', 'controllers', '%s.py' % ctr), 'w').close()
|
||||
# applications/examples/controllers/*.py
|
||||
for ctr in ('ajax_examples', 'appadmin', 'default', 'global', 'spreadsheet'):
|
||||
open(abspath('applications', 'examples', 'controllers', '%s.py' % ctr), 'w').close()
|
||||
# applications/welcome/controllers/*.py
|
||||
for ctr in ('appadmin', 'default'):
|
||||
open(abspath('applications', 'welcome', 'controllers', '%s.py' % ctr), 'w').close()
|
||||
# create an app-specific routes.py for examples app
|
||||
routes = open(abspath('applications', 'examples', 'routes.py'), 'w')
|
||||
routes.write("routers=dict(examples=dict(default_function='exdef'))")
|
||||
routes.close()
|
||||
# create language files for examples app
|
||||
for lang in ('en', 'it'):
|
||||
os.mkdir(abspath('applications', 'examples', 'static', lang))
|
||||
open(abspath('applications', 'examples', 'static', lang, 'file'), 'w').close()
|
||||
|
||||
global oldcwd
|
||||
if oldcwd is None: # do this only once
|
||||
oldcwd = os.getcwd()
|
||||
if not os.path.isdir('gluon'):
|
||||
os.chdir(os.path.realpath('../../')) # run from web2py base directory
|
||||
import main # for initialization after chdir
|
||||
global logger
|
||||
logger = logging.getLogger('web2py.rewrite')
|
||||
global_settings.applications_parent = tempfile.mkdtemp()
|
||||
global root
|
||||
root = global_settings.applications_parent
|
||||
make_apptree()
|
||||
|
||||
def tearDownModule():
|
||||
global oldcwd
|
||||
if oldcwd is not None:
|
||||
os.chdir(oldcwd)
|
||||
oldcwd = None
|
||||
|
||||
|
||||
class TestRouter(unittest.TestCase):
|
||||
""" Tests the routers logic from gluon.rewrite """
|
||||
|
||||
def test_router_syntax(self):
|
||||
""" Test router syntax error """
|
||||
level = logger.getEffectiveLevel()
|
||||
logger.setLevel(logging.CRITICAL) # disable logging temporarily
|
||||
self.assertRaises(SyntaxError, load, data='x:y')
|
||||
self.assertRaises(SyntaxError, load, rdict=dict(BASE=dict(badkey="value")))
|
||||
self.assertRaises(SyntaxError, load, rdict=dict(BASE=dict(), app=dict(default_application="name")))
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(SyntaxError, "invalid syntax",
|
||||
load, data='x:y')
|
||||
self.assertRaisesRegexp(SyntaxError, "unknown key",
|
||||
load, rdict=dict(BASE=dict(badkey="value")))
|
||||
self.assertRaisesRegexp(SyntaxError, "BASE-only key",
|
||||
load, rdict=dict(BASE=dict(), app=dict(default_application="name")))
|
||||
except AttributeError:
|
||||
pass
|
||||
logger.setLevel(level)
|
||||
|
||||
def test_router_null(self):
|
||||
""" Tests the null router """
|
||||
load(rdict=dict())
|
||||
# app resolution
|
||||
self.assertEqual(filter_url('http://domain.com/welcome', app=True), 'welcome')
|
||||
self.assertEqual(filter_url('http://domain.com/', app=True), 'init')
|
||||
# incoming
|
||||
self.assertEqual(filter_url('http://domain.com/favicon.ico'), '%s/applications/init/static/favicon.ico' % root)
|
||||
self.assertEqual(filter_url('http://domain.com/abc'), '/init/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/index/abc'), "/init/default/index ['abc']")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def'), "/init/default/abc ['def']")
|
||||
self.assertEqual(filter_url('http://domain.com/index/a%20bc'), "/init/default/index ['a bc']")
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/path/to/static'), "%s/applications/welcome/static/path/to/static" % root)
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/welcome/static/bad/path/to/st~tic')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, "400.*invalid static file", filter_url, 'http://domain.com/welcome/static/bad/path/to/st~tic')
|
||||
except AttributeError:
|
||||
pass
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/index', out=True), '/')
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/index/arg1', out=True), '/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/abc', out=True), '/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/init/static/abc', out=True), '/init/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/init/appadmin/index', out=True), '/appadmin')
|
||||
self.assertEqual(filter_url('http://domain.com/init/appadmin/abc', out=True), '/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/init/admin/index', out=True), '/init/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/init/admin/abc', out=True), '/init/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
|
||||
def test_router_specific(self):
|
||||
"""
|
||||
Test app-specific routes.py
|
||||
|
||||
Note that make_apptree above created applications/examples/routes.py with a default_function.
|
||||
"""
|
||||
load(rdict=dict())
|
||||
self.assertEqual(filter_url('http://domain.com/welcome'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/examples'), '/examples/default/exdef')
|
||||
|
||||
def test_router_defapp(self):
|
||||
""" Test the default-application function """
|
||||
routers = dict(BASE=dict(default_application='welcome'))
|
||||
load(rdict=routers)
|
||||
# app resolution
|
||||
self.assertEqual(filter_url('http://domain.com/welcome', app=True), 'welcome')
|
||||
self.assertEqual(filter_url('http://domain.com/', app=True), 'welcome')
|
||||
# incoming
|
||||
self.assertEqual(filter_url('http://domain.com'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/appadmin'), '/welcome/appadmin/index')
|
||||
self.assertEqual(filter_url('http://domain.com/abc'), '/welcome/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/index/abc'), "/welcome/default/index ['abc']")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def'), "/welcome/default/abc ['def']")
|
||||
self.assertEqual(filter_url('http://domain.com/favicon.ico'), '%s/applications/welcome/static/favicon.ico' % root)
|
||||
self.assertEqual(filter_url('http://domain.com/static/abc'), '%s/applications/welcome/static/abc' % root)
|
||||
self.assertEqual(filter_url('http://domain.com/static/path/to/static'), "%s/applications/welcome/static/path/to/static" % root)
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index', out=True), '/')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/arg1', out=True), '/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/abc', out=True), '/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/admin', out=True), '/default/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc', out=True),
|
||||
'/welcome/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/index', out=True), '/appadmin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/abc', out=True), '/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/index', out=True), '/welcome/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/abc', out=True), '/welcome/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
|
||||
def test_router_nodef(self):
|
||||
""" Test no-default functions """
|
||||
routers = dict(
|
||||
BASE=dict(default_application='welcome'),
|
||||
welcome=dict(controllers=None),
|
||||
)
|
||||
load(rdict=routers)
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index', out=True), '/default')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/arg1', out=True), '/default/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/abc', out=True), '/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc', out=True),
|
||||
'/welcome/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/index', out=True), '/appadmin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/abc', out=True), '/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/index', out=True), '/welcome/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/abc', out=True), '/welcome/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
# incoming
|
||||
self.assertEqual(filter_url('http://domain.com'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/appadmin'), '/welcome/appadmin/index')
|
||||
self.assertEqual(filter_url('http://domain.com/abc'), '/welcome/abc/index')
|
||||
self.assertEqual(filter_url('http://domain.com/index/abc'), "/welcome/index/abc")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def'), "/welcome/abc/def")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def/ghi'), "/welcome/abc/def ['ghi']")
|
||||
|
||||
routers = dict(
|
||||
BASE=dict(default_application=None),
|
||||
)
|
||||
load(rdict=routers)
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index', out=True), '/welcome')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/arg1', out=True), '/welcome/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/abc', out=True), '/welcome/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc', out=True), '/welcome/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/index', out=True), '/welcome/appadmin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/abc', out=True), '/welcome/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/index', out=True), '/welcome/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/abc', out=True), '/welcome/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
# incoming
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/appadmin')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, "400.*invalid application", filter_url, 'http://domain.com')
|
||||
self.assertRaisesRegexp(HTTP, "400.*invalid application", filter_url, 'http://domain.com/appadmin')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
routers = dict(
|
||||
BASE=dict(default_application='welcome', applications=None),
|
||||
)
|
||||
load(rdict=routers)
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index', out=True), '/welcome')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/arg1', out=True), '/welcome/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/abc', out=True), '/welcome/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc', out=True), '/welcome/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/index', out=True), '/welcome/appadmin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/abc', out=True), '/welcome/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/index', out=True), '/welcome/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/abc', out=True), '/welcome/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
# incoming
|
||||
self.assertEqual(filter_url('http://domain.com'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/'), '/welcome/default/index')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/appadmin')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, "400.*unknown application: 'appadmin'", filter_url, 'http://domain.com/appadmin')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
routers = dict(
|
||||
BASE=dict(default_application='welcome', applications=None),
|
||||
welcome=dict(controllers=None),
|
||||
)
|
||||
load(rdict=routers)
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index', out=True), '/welcome/default')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/arg1', out=True), '/welcome/default/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/abc', out=True), '/welcome/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc', out=True), '/welcome/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/index', out=True), '/welcome/appadmin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/abc', out=True), '/welcome/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/index', out=True), '/welcome/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/abc', out=True), '/welcome/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
# incoming
|
||||
self.assertEqual(filter_url('http://domain.com'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/'), '/welcome/default/index')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/appadmin')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, "400.*unknown application: 'appadmin'", filter_url, 'http://domain.com/appadmin')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
routers = dict(
|
||||
BASE=dict(default_application='welcome', applications=None),
|
||||
welcome=dict(default_controller=None),
|
||||
)
|
||||
load(rdict=routers)
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index', out=True), '/welcome/default')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/arg1', out=True), '/welcome/default/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/abc', out=True), '/welcome/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc', out=True), '/welcome/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/index', out=True), '/welcome/appadmin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/abc', out=True), '/welcome/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/index', out=True), '/welcome/admin')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/abc', out=True), '/welcome/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
# incoming
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/appadmin')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, "400.*invalid controller", filter_url, 'http://domain.com')
|
||||
self.assertRaisesRegexp(HTTP, "400.*unknown application: 'appadmin'", filter_url, 'http://domain.com/appadmin')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
routers = dict(
|
||||
BASE=dict(default_application='welcome', applications=None),
|
||||
welcome=dict(controllers=None, default_function=None),
|
||||
)
|
||||
load(rdict=routers)
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index', out=True), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/arg1', out=True), '/welcome/default/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/abc', out=True), '/welcome/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc', out=True), '/welcome/static/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/index', out=True), '/welcome/appadmin/index')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/appadmin/abc', out=True), '/welcome/appadmin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/index', out=True), '/welcome/admin/index')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/admin/abc', out=True), '/welcome/admin/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/admin/default/abc', out=True), '/admin/abc')
|
||||
# incoming
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/appadmin')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, "400.*invalid function", filter_url, 'http://domain.com')
|
||||
self.assertRaisesRegexp(HTTP, "400.*unknown application: 'appadmin'", filter_url, 'http://domain.com/appadmin')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def test_router_app(self):
|
||||
""" Tests the doctest router app resolution"""
|
||||
routers = dict(
|
||||
BASE = dict(
|
||||
domains = {
|
||||
"domain1.com" : "app1",
|
||||
"www.domain1.com" : "app1",
|
||||
"domain2.com" : "app2",
|
||||
},
|
||||
),
|
||||
app1 = dict(),
|
||||
app2 = dict(),
|
||||
goodapp = dict(),
|
||||
)
|
||||
routers['bad!app'] = dict()
|
||||
load(rdict=routers)
|
||||
self.assertEqual(filter_url('http://domain.com/welcome', app=True), 'welcome')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/', app=True), 'welcome')
|
||||
self.assertEqual(filter_url('http://domain.com', app=True), 'init')
|
||||
self.assertEqual(filter_url('http://domain.com/', app=True), 'init')
|
||||
self.assertEqual(filter_url('http://domain.com/abc', app=True), 'init')
|
||||
self.assertEqual(filter_url('http://domain1.com/abc', app=True), 'app1')
|
||||
self.assertEqual(filter_url('http://www.domain1.com/abc', app=True), 'app1')
|
||||
self.assertEqual(filter_url('http://domain2.com/abc', app=True), 'app2')
|
||||
self.assertEqual(filter_url('http://domain2.com/admin', app=True), 'app2')
|
||||
|
||||
self.assertEqual(filter_url('http://domain.com/goodapp', app=True), 'goodapp')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/bad!app', app=True)
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, '400.*invalid application', filter_url, 'http://domain.com/bad!app')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
routers['BASE']['domains']['domain3.com'] = 'app3'
|
||||
self.assertRaises(SyntaxError, load, rdict=routers)
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(SyntaxError, "unknown.*app3", load, rdict=routers)
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def test_router_domains(self):
|
||||
'''
|
||||
Test URLs that map domains
|
||||
'''
|
||||
routers = dict(
|
||||
BASE = dict(
|
||||
applications = ['app1', 'app2', 'app2A', 'app3', 'app4', 'app5', 'app6'],
|
||||
domains = {
|
||||
# two domains to the same app
|
||||
"domain1.com" : "app1",
|
||||
"www.domain1.com" : "app1",
|
||||
# same domain, two ports, to two apps
|
||||
"domain2.com" : "app2a",
|
||||
"domain2.com:8080" : "app2b",
|
||||
# two domains, same app, two controllers
|
||||
"domain3a.com" : "app3/c3a",
|
||||
"domain3b.com" : "app3/c3b",
|
||||
# two domains, same app & controller, two functions
|
||||
"domain4a.com" : "app4/c4/f4a",
|
||||
"domain4b.com" : "app4/c4/f4b",
|
||||
# http vs https
|
||||
"domain6.com:80" : "app6",
|
||||
"domain6.com:443" : "app6s",
|
||||
},
|
||||
),
|
||||
app1 = dict( default_controller = 'c1', default_function = 'f1', controllers = ['c1'], exclusive_domain=True, ),
|
||||
app2a = dict( default_controller = 'c2a', default_function = 'f2a', controllers = ['c2a'], ),
|
||||
app2b = dict( default_controller = 'c2b', default_function = 'f2b', controllers = ['c2b'], ),
|
||||
app3 = dict( controllers = ['c3a', 'c3b'], ),
|
||||
app4 = dict( default_controller = 'c4', controllers = ['c4']),
|
||||
app5 = dict( default_controller = 'c5', controllers = ['c5'], domain = 'localhost' ),
|
||||
app6 = dict( default_controller = 'c6', default_function = 'f6', controllers = ['c6'], ),
|
||||
app6s = dict( default_controller = 'c6s', default_function = 'f6s', controllers = ['c6s'], ),
|
||||
)
|
||||
|
||||
load(rdict=routers)
|
||||
self.assertEqual(filter_url('http://domain1.com/abc'), '/app1/c1/abc')
|
||||
self.assertEqual(filter_url('http://domain1.com/c1/abc'), '/app1/c1/abc')
|
||||
self.assertEqual(filter_url('http://domain1.com/abc.html'), '/app1/c1/abc')
|
||||
self.assertEqual(filter_url('http://domain1.com/abc.css'), '/app1/c1/abc.css')
|
||||
self.assertEqual(filter_url('http://domain1.com/index/abc'), "/app1/c1/index ['abc']")
|
||||
self.assertEqual(filter_url('http://domain2.com/app1'), "/app2a/c2a/app1")
|
||||
|
||||
self.assertEqual(filter_url('https://domain1.com/app1/ctr/fcn', domain=('app1',None), out=True), "/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://www.domain1.com/app1/ctr/fcn', domain=('app1',None), out=True), "/ctr/fcn")
|
||||
|
||||
self.assertEqual(filter_url('http://domain2.com/abc'), '/app2a/c2a/abc')
|
||||
self.assertEqual(filter_url('http://domain2.com:8080/abc'), '/app2b/c2b/abc')
|
||||
|
||||
self.assertEqual(filter_url('http://domain2.com/app2a/ctr/fcn', domain=('app2a',None), out=True), "/ctr/fcn")
|
||||
self.assertEqual(filter_url('http://domain2.com/app2a/ctr/f2a', domain=('app2a',None), out=True), "/ctr")
|
||||
self.assertEqual(filter_url('http://domain2.com/app2a/c2a/f2a', domain=('app2a',None), out=True), "/")
|
||||
self.assertEqual(filter_url('http://domain2.com/app2a/c2a/fcn', domain=('app2a',None), out=True), "/fcn")
|
||||
self.assertEqual(filter_url('http://domain2.com/app2a/ctr/fcn', domain=('app2b',None), out=True), "/app2a/ctr/fcn")
|
||||
self.assertEqual(filter_url('http://domain2.com/app2a/ctr/f2a', domain=('app2b',None), out=True), "/app2a/ctr")
|
||||
self.assertEqual(filter_url('http://domain2.com/app2a/c2a/f2a', domain=('app2b',None), out=True), "/app2a")
|
||||
|
||||
self.assertEqual(filter_url('http://domain3a.com/'), '/app3/c3a/index')
|
||||
self.assertEqual(filter_url('http://domain3a.com/abc'), '/app3/c3a/abc')
|
||||
self.assertEqual(filter_url('http://domain3a.com/c3b'), '/app3/c3b/index')
|
||||
self.assertEqual(filter_url('http://domain3b.com/abc'), '/app3/c3b/abc')
|
||||
|
||||
self.assertEqual(filter_url('http://domain3a.com/app3/c3a/fcn', domain=('app3','c3a'), out=True), "/fcn")
|
||||
self.assertEqual(filter_url('http://domain3a.com/app3/c3a/fcn', domain=('app3','c3b'), out=True), "/c3a/fcn")
|
||||
self.assertEqual(filter_url('http://domain3a.com/app3/c3a/fcn', domain=('app1',None), out=True), "/app3/c3a/fcn")
|
||||
|
||||
self.assertEqual(filter_url('http://domain4a.com/abc'), '/app4/c4/abc')
|
||||
self.assertEqual(filter_url('https://domain4a.com/app4/c4/fcn', domain=('app4',None), out=True), "/fcn")
|
||||
|
||||
self.assertEqual(filter_url('http://domain4a.com'), '/app4/c4/f4a')
|
||||
self.assertEqual(filter_url('http://domain4b.com'), '/app4/c4/f4b')
|
||||
|
||||
self.assertEqual(filter_url('http://localhost/abc'), '/app5/c5/abc')
|
||||
self.assertEqual(filter_url('http:///abc'), '/app5/c5/abc') # test null host => localhost
|
||||
self.assertEqual(filter_url('https://localhost/app5/c5/fcn', domain=('app5',None), out=True), "/fcn")
|
||||
|
||||
self.assertEqual(filter_url('http://domain6.com'), '/app6/c6/f6')
|
||||
self.assertEqual(filter_url('https://domain6.com'), '/app6s/c6s/f6s')
|
||||
|
||||
self.assertEqual(filter_url('http://domain2.com/app3/c3a/f3', domain=('app2b',None), out=True), "/app3/c3a/f3")
|
||||
self.assertRaises(SyntaxError, filter_url, 'http://domain1.com/app1/c1/f1', domain=('app2b',None), out=True)
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(SyntaxError, 'cross-domain conflict', filter_url, 'http://domain1.com/app1/c1/f1', domain=('app2b',None), out=True)
|
||||
except AttributeError:
|
||||
pass
|
||||
self.assertEqual(filter_url('http://domain1.com/app1/c1/f1', domain=('app2b',None), host='domain2.com', out=True), "/app1")
|
||||
|
||||
def test_router_raise(self):
|
||||
'''
|
||||
Test URLs that raise exceptions
|
||||
'''
|
||||
# test non-exception variants
|
||||
router_raise = dict(
|
||||
init = dict(
|
||||
controllers = [],
|
||||
),
|
||||
welcome = dict(
|
||||
map_hyphen = False,
|
||||
),
|
||||
)
|
||||
load(rdict=router_raise)
|
||||
self.assertEqual(filter_url('http://domain.com/ctl'), "/init/ctl/index")
|
||||
self.assertEqual(filter_url('http://domain.com/default/fcn'), "/init/default/fcn")
|
||||
self.assertEqual(filter_url('http://domain.com/default/fcn.ext'), "/init/default/fcn.ext")
|
||||
self.assertEqual(filter_url('http://domain.com/default/fcn/arg'), "/init/default/fcn ['arg']")
|
||||
# now raise-HTTP variants
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/bad!ctl')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/ctl/bad!fcn')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/ctl/fcn.bad!ext')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/ctl/fcn/bad!arg')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, '400.*invalid controller', filter_url, 'http://domain.com/init/bad!ctl')
|
||||
self.assertRaisesRegexp(HTTP, '400.*invalid function', filter_url, 'http://domain.com/init/ctlr/bad!fcn')
|
||||
self.assertRaisesRegexp(HTTP, '400.*invalid extension', filter_url, 'http://domain.com/init/ctlr/fcn.bad!ext')
|
||||
self.assertRaisesRegexp(HTTP, '400.*invalid arg', filter_url, 'http://domain.com/appc/init/fcn/bad!arg')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/fcn_1'), "/welcome/default/fcn_1")
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/welcome/default/fcn-1')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, '400.*invalid function', filter_url, 'http://domain.com/welcome/default/fcn-1')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def test_router_out(self):
|
||||
'''
|
||||
Test basic outgoing routing
|
||||
'''
|
||||
router_out = dict(
|
||||
BASE = dict(),
|
||||
init = dict( controllers = ['default', 'ctr'], ),
|
||||
app = dict(),
|
||||
)
|
||||
load(rdict=router_out)
|
||||
self.assertEqual(filter_url('https://domain.com/app/ctr/fcn', out=True), "/app/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/init/ctr/fcn', out=True), "/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/init/ctr/fcn', out=True), "/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/init/static/file', out=True), "/init/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/init/static/index', out=True), "/init/static/index")
|
||||
self.assertEqual(filter_url('https://domain.com/init/default/index', out=True), "/")
|
||||
self.assertEqual(filter_url('https://domain.com/init/ctr/index', out=True), "/ctr")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/fcn?query', out=True), "/fcn?query")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/fcn#anchor', out=True), "/fcn#anchor")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/fcn?query#anchor', out=True),
|
||||
"/fcn?query#anchor")
|
||||
|
||||
router_out['BASE']['map_static'] = True
|
||||
load(rdict=router_out)
|
||||
self.assertEqual(filter_url('https://domain.com/init/static/file', out=True), "/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/init/static/index', out=True), "/static/index")
|
||||
|
||||
router_out['init']['map_static'] = False
|
||||
load(rdict=router_out)
|
||||
self.assertEqual(filter_url('https://domain.com/init/static/file', out=True), "/init/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/init/static/index', out=True), "/init/static/index")
|
||||
|
||||
def test_router_functions(self):
|
||||
'''
|
||||
Test function-omission with functions=[something]
|
||||
'''
|
||||
router_functions = dict(
|
||||
BASE = dict(
|
||||
applications = ['init', 'app', 'app2'],
|
||||
default_application = 'app',
|
||||
),
|
||||
init = dict(
|
||||
controllers = ['default'],
|
||||
),
|
||||
app = dict(
|
||||
controllers = ['default', 'ctr'],
|
||||
functions = dict(
|
||||
default=['index', 'user', 'help'],
|
||||
ctr=['ctrf1', 'ctrf2', 'ctrf3'],
|
||||
),
|
||||
default_function = dict(
|
||||
default='index',
|
||||
ctr='ctrf1',
|
||||
),
|
||||
),
|
||||
app2 = dict(
|
||||
controllers = ['default', 'ctr'],
|
||||
functions = ['index', 'user', 'help'],
|
||||
),
|
||||
)
|
||||
load(rdict=router_functions)
|
||||
|
||||
# outbound
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', args=['arg1'])), "/init/f/arg1")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index', args=['arg1'])), "/init/index/arg1")
|
||||
|
||||
self.assertEqual(str(URL(a='app', c='default', f='index', args=['arg1'])), "/arg1")
|
||||
self.assertEqual(str(URL(a='app', c='default', f='user', args=['arg1'])), "/user/arg1")
|
||||
self.assertEqual(str(URL(a='app', c='default', f='user', args=['index'])), "/user/index")
|
||||
self.assertEqual(str(URL(a='app', c='default', f='index', args=['index'])), "/index/index")
|
||||
self.assertEqual(str(URL(a='app', c='default', f='index', args=['init'])), "/index/init")
|
||||
self.assertEqual(str(URL(a='app', c='default', f='index', args=['ctr'])), "/index/ctr")
|
||||
self.assertEqual(str(URL(a='app', c='ctr', f='index', args=['arg'])), "/ctr/index/arg")
|
||||
self.assertEqual(str(URL(a='app', c='ctr', f='ctrf1', args=['arg'])), "/ctr/arg")
|
||||
self.assertEqual(str(URL(a='app', c='ctr', f='ctrf1', args=['ctrf2'])), "/ctr/ctrf1/ctrf2")
|
||||
|
||||
self.assertEqual(str(URL(a='app2', c='default', f='index', args=['arg1'])), "/app2/arg1")
|
||||
self.assertEqual(str(URL(a='app2', c='default', f='user', args=['arg1'])), "/app2/user/arg1")
|
||||
self.assertEqual(str(URL(a='app2', c='default', f='user', args=['index'])), "/app2/user/index")
|
||||
self.assertEqual(str(URL(a='app2', c='default', f='index', args=['index'])), "/app2/index/index")
|
||||
self.assertEqual(str(URL(a='app2', c='default', f='index', args=['init'])), "/app2/index/init")
|
||||
self.assertEqual(str(URL(a='app2', c='default', f='index', args=['ctr'])), "/app2/index/ctr")
|
||||
|
||||
# inbound
|
||||
self.assertEqual(filter_url('http://d.com/arg'), "/app/default/index ['arg']")
|
||||
self.assertEqual(filter_url('http://d.com/user'), "/app/default/user")
|
||||
self.assertEqual(filter_url('http://d.com/user/arg'), "/app/default/user ['arg']")
|
||||
self.assertEqual(filter_url('http://d.com/ctr'), "/app/ctr/ctrf1")
|
||||
self.assertEqual(filter_url('http://d.com/ctr/arg'), "/app/ctr/ctrf1 ['arg']")
|
||||
|
||||
self.assertEqual(filter_url('http://d.com/app2/arg'), "/app2/default/index ['arg']")
|
||||
self.assertEqual(filter_url('http://d.com/app2/user'), "/app2/default/user")
|
||||
self.assertEqual(filter_url('http://d.com/app2/user/arg'), "/app2/default/user ['arg']")
|
||||
self.assertEqual(filter_url('http://d.com/app2/ctr'), "/app2/ctr/index")
|
||||
self.assertEqual(filter_url('http://d.com/app2/ctr/index/arg'), "/app2/ctr/index ['arg']")
|
||||
self.assertEqual(filter_url('http://d.com/app2/ctr/arg'), "/app2/ctr/arg")
|
||||
|
||||
def test_router_hyphen(self):
|
||||
'''
|
||||
Test hyphen conversion
|
||||
'''
|
||||
router_hyphen = dict(
|
||||
BASE = dict(
|
||||
applications = ['init', 'app1', 'app2'],
|
||||
),
|
||||
init = dict(
|
||||
controllers = ['default'],
|
||||
),
|
||||
app1 = dict(
|
||||
controllers = ['default'],
|
||||
map_hyphen = True,
|
||||
),
|
||||
app2 = dict(
|
||||
controllers = ['default'],
|
||||
map_hyphen = False,
|
||||
),
|
||||
)
|
||||
load(rdict=router_hyphen)
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/fcn_1', out=True), "/fcn_1")
|
||||
self.assertEqual(filter_url('http://domain.com/static/filename-with_underscore'),
|
||||
"%s/applications/init/static/filename-with_underscore" % root)
|
||||
self.assertEqual(filter_url('http://domain.com/init/static/filename-with_underscore', out=True),
|
||||
"/init/static/filename-with_underscore")
|
||||
|
||||
self.assertEqual(filter_url('http://domain.com/app2/fcn_1'),
|
||||
"/app2/default/fcn_1")
|
||||
self.assertEqual(filter_url('http://domain.com/app2/ctr/fcn_1', domain=('app2',None), out=True),
|
||||
"/ctr/fcn_1")
|
||||
self.assertEqual(filter_url('http://domain.com/app2/static/filename-with_underscore', domain=('app2',None), out=True),
|
||||
"/app2/static/filename-with_underscore")
|
||||
self.assertEqual(filter_url('http://domain.com/app2/static/filename-with_underscore'),
|
||||
"%s/applications/app2/static/filename-with_underscore" % root)
|
||||
|
||||
self.assertEqual(str(URL(a='init', c='default', f='a_b')), "/a_b")
|
||||
self.assertEqual(str(URL(a='app1', c='default', f='a_b')), "/app1/a-b")
|
||||
self.assertEqual(str(URL(a='app2', c='default', f='a_b')), "/app2/a_b")
|
||||
self.assertEqual(str(URL(a='app1', c='static', f='a/b_c')), "/app1/static/a/b_c")
|
||||
self.assertEqual(str(URL(a='app1', c='static/a', f='b_c')), "/app1/static/a/b_c")
|
||||
self.assertEqual(str(URL(a='app2', c='static', f='a/b_c')), "/app2/static/a/b_c")
|
||||
self.assertEqual(str(URL(a='app2', c='static/a', f='b_c')), "/app2/static/a/b_c")
|
||||
|
||||
|
||||
def test_router_lang(self):
|
||||
'''
|
||||
Test language specifications
|
||||
'''
|
||||
router_lang = dict(
|
||||
BASE = dict(default_application = 'admin'),
|
||||
welcome = dict(),
|
||||
admin = dict(
|
||||
controllers = ['default', 'ctr'],
|
||||
languages = ['en', 'it', 'it-it'], default_language = 'en',
|
||||
),
|
||||
examples = dict(
|
||||
languages = ['en', 'it', 'it-it'], default_language = 'en',
|
||||
),
|
||||
)
|
||||
load(rdict=router_lang)
|
||||
self.assertEqual(filter_url('http://domain.com/index/abc'), "/admin/default/index ['abc'] (en)")
|
||||
self.assertEqual(filter_url('http://domain.com/en/abc/def'), "/admin/default/abc ['def'] (en)")
|
||||
self.assertEqual(filter_url('http://domain.com/it/abc/def'), "/admin/default/abc ['def'] (it)")
|
||||
self.assertEqual(filter_url('http://domain.com/it-it/abc/def'), "/admin/default/abc ['def'] (it-it)")
|
||||
self.assertEqual(filter_url('http://domain.com/index/a%20bc'), "/admin/default/index ['a bc'] (en)")
|
||||
self.assertEqual(filter_url('http://domain.com/static/file'), "%s/applications/admin/static/file" % root)
|
||||
self.assertEqual(filter_url('http://domain.com/en/static/file'), "%s/applications/admin/static/file" % root)
|
||||
self.assertEqual(filter_url('http://domain.com/examples/en/static/file'), "%s/applications/examples/static/en/file" % root)
|
||||
self.assertEqual(filter_url('http://domain.com/examples/static/file'), "%s/applications/examples/static/en/file" % root)
|
||||
self.assertEqual(filter_url('http://domain.com/examples/it/static/file'), "%s/applications/examples/static/it/file" % root)
|
||||
self.assertEqual(filter_url('http://domain.com/examples/it-it/static/file'), "%s/applications/examples/static/file" % root)
|
||||
|
||||
self.assertEqual(filter_url('https://domain.com/admin/ctr/fcn', lang='en', out=True), "/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/ctr/fcn', lang='it', out=True), "/it/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/ctr/fcn', lang='it-it', out=True), "/it-it/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/static/file', lang='en', out=True), "/admin/en/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/static/file', lang='it', out=True), "/admin/it/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/static/file', lang='it-it', out=True), "/admin/it-it/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/welcome/ctr/fcn', lang='it', out=True), "/welcome/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/welcome/ctr/fcn', lang='es', out=True), "/welcome/ctr/fcn")
|
||||
|
||||
router_lang['admin']['map_static'] = True
|
||||
load(rdict=router_lang)
|
||||
self.assertEqual(filter_url('https://domain.com/admin/ctr/fcn', lang='en', out=True), "/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/ctr/fcn', lang='it', out=True), "/it/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/ctr/fcn', lang='it-it', out=True), "/it-it/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/static/file', lang='en', out=True), "/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/static/file', lang='it', out=True), "/it/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/admin/static/file', lang='it-it', out=True), "/it-it/static/file")
|
||||
self.assertEqual(filter_url('https://domain.com/welcome/ctr/fcn', lang='it', out=True), "/welcome/ctr/fcn")
|
||||
self.assertEqual(filter_url('https://domain.com/welcome/ctr/fcn', lang='es', out=True), "/welcome/ctr/fcn")
|
||||
|
||||
def test_router_get_effective(self):
|
||||
'''
|
||||
Test get_effective_router
|
||||
'''
|
||||
router_get_effective = dict(
|
||||
BASE = dict(
|
||||
default_application = 'a1',
|
||||
applications = ['a1', 'a2'],
|
||||
),
|
||||
a1 = dict(
|
||||
controllers = ['c1a', 'c1b', 'default'],
|
||||
),
|
||||
a2 = dict(
|
||||
default_controller = 'c2',
|
||||
controllers = [],
|
||||
),
|
||||
a3 = dict(
|
||||
default_controller = 'c2',
|
||||
controllers = ['c1'],
|
||||
),
|
||||
a4 = dict(
|
||||
default_function = 'f1',
|
||||
functions = ['f2'],
|
||||
),
|
||||
)
|
||||
load(rdict=router_get_effective)
|
||||
self.assertEqual(get_effective_router('BASE').applications, set(['a1','a2']))
|
||||
self.assertEqual(get_effective_router('BASE').default_application, 'a1')
|
||||
self.assertEqual(get_effective_router('BASE').domains, {})
|
||||
self.assertEqual(get_effective_router('a1').applications, None)
|
||||
self.assertEqual(get_effective_router('a1').default_application, None)
|
||||
self.assertEqual(get_effective_router('a1').domains, None)
|
||||
self.assertEqual(get_effective_router('a1').default_controller, "default")
|
||||
self.assertEqual(get_effective_router('a2').default_application, None)
|
||||
self.assertEqual(get_effective_router('a2').default_controller, "c2")
|
||||
self.assertEqual(get_effective_router('a1').controllers, set(['c1a', 'c1b', 'default', 'static']))
|
||||
self.assertEqual(get_effective_router('a2').controllers, set())
|
||||
self.assertEqual(get_effective_router('a3').controllers, set(['c1', 'c2', 'static']))
|
||||
self.assertEqual(get_effective_router('a4').functions, dict(default=set(['f1', 'f2'])))
|
||||
self.assertEqual(get_effective_router('xx'), None)
|
||||
|
||||
def test_router_error(self):
|
||||
'''
|
||||
Test rewrite of HTTP errors
|
||||
'''
|
||||
router_err = dict()
|
||||
load(rdict=router_err)
|
||||
self.assertEqual(filter_err(200), 200)
|
||||
self.assertEqual(filter_err(399), 399)
|
||||
self.assertEqual(filter_err(400), 400)
|
||||
|
||||
def test_router_args(self):
|
||||
'''
|
||||
Test URL args parsing/generation
|
||||
'''
|
||||
load(rdict=dict())
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/f/arg1'),
|
||||
"/init/default/f ['arg1']")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/f/arg1/'),
|
||||
"/init/default/f ['arg1']")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/f/arg1//'),
|
||||
"/init/default/f ['arg1', '']")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/f//arg1'),
|
||||
"/init/default/f ['', 'arg1']")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/f/arg1/arg2'),
|
||||
"/init/default/f ['arg1', 'arg2']")
|
||||
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/f', out=True), "/f")
|
||||
self.assertEqual(map_url_out(None, None, 'init', 'default', 'f', None, None, None, None, None), "/f")
|
||||
self.assertEqual(map_url_out(None, None, 'init', 'default', 'f', [], None, None, None, None), "/f")
|
||||
self.assertEqual(map_url_out(None, None, 'init', 'default', 'f', ['arg1'], None, None, None, None), "/f")
|
||||
self.assertEqual(map_url_out(None, None, 'init', 'default', 'f', ['arg1', ''], None, None, None, None), "/f")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', args=None)), "/f")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', args=['arg1'])), "/f/arg1")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', args=['arg1', ''])), "/f/arg1//")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', args=['arg1', '', 'arg3'])), "/f/arg1//arg3")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', args=['ar g'])), "/f/ar%20g")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', args=['årg'])), "/f/%C3%A5rg")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='fünc')), "/f\xc3\xbcnc")
|
||||
|
||||
def test_routes_anchor(self):
|
||||
'''
|
||||
Test URL with anchor
|
||||
'''
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', anchor='anchor')), "/a/c/f#anchor")
|
||||
load(rdict=dict())
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', anchor='anchor')), "/a/c/f#anchor")
|
||||
args = ['a1', 'a2']
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', args=args, anchor='anchor')),
|
||||
"/a/c/f/a1/a2#anchor")
|
||||
vars = dict(v1=1, v2=2)
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', vars=vars, anchor='anchor')),
|
||||
"/a/c/f?v1=1&v2=2#anchor")
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', args=args, vars=vars, anchor='anchor')),
|
||||
"/a/c/f/a1/a2?v1=1&v2=2#anchor")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index')),
|
||||
"/")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f')),
|
||||
"/f")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index', anchor='anchor')),
|
||||
"/#anchor")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='f', anchor='anchor')),
|
||||
"/f#anchor")
|
||||
|
||||
def test_router_prefix(self):
|
||||
'''
|
||||
Test path_prefix
|
||||
'''
|
||||
router_path_prefix = dict(
|
||||
BASE = dict(
|
||||
default_application = 'a1',
|
||||
applications = ['a1', 'a2'],
|
||||
path_prefix = '/path/to/apps',
|
||||
),
|
||||
a1 = dict(
|
||||
controllers = ['c1a', 'c1b', 'default'],
|
||||
),
|
||||
a2 = dict(
|
||||
default_controller = 'c2',
|
||||
controllers = [],
|
||||
),
|
||||
)
|
||||
load(rdict=router_path_prefix)
|
||||
self.assertEqual(str(URL(a='a1', c='c1a', f='f')),
|
||||
"/path/to/apps/c1a/f")
|
||||
self.assertEqual(str(URL(a='a2', c='c', f='f')),
|
||||
"/path/to/apps/a2/c/f")
|
||||
self.assertEqual(str(URL(a='a2', c='c2', f='f')),
|
||||
"/path/to/apps/a2/c2/f")
|
||||
self.assertEqual(filter_url('http://domain.com/a1/'), "/a1/default/index")
|
||||
self.assertEqual(filter_url('http://domain.com/path/to/apps/a1/'), "/a1/default/index")
|
||||
self.assertEqual(filter_url('http://domain.com/path/to/a1/'), "/a1/default/path ['to', 'a1']")
|
||||
|
||||
def test_router_absolute(self):
|
||||
'''
|
||||
Test absolute URL
|
||||
'''
|
||||
load(rdict=dict())
|
||||
r = Storage()
|
||||
r.env = Storage()
|
||||
r.env.http_host = 'domain.com'
|
||||
r.env.WSGI_URL_SCHEME = 'httpx' # distinguish incoming scheme
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f')), "/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', host=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', host='host.com')),
|
||||
"httpx://host.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=False)),
|
||||
"/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='https')),
|
||||
"https://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='wss')),
|
||||
"wss://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True, host=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='https', host=True)),
|
||||
"https://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=False, host=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True, host='host.com')),
|
||||
"httpx://host.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=False, host='host.com')),
|
||||
"httpx://host.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', port=1234)),
|
||||
"httpx://domain.com:1234/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True, port=1234)),
|
||||
"httpx://domain.com:1234/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', host='host.com', port=1234)),
|
||||
"httpx://host.com:1234/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='wss', host='host.com', port=1234)),
|
||||
"wss://host.com:1234/a/c/f")
|
||||
|
||||
def test_request_uri(self):
|
||||
'''
|
||||
Test REQUEST_URI in env
|
||||
'''
|
||||
load(rdict=dict())
|
||||
self.assertEqual(filter_url('http://domain.com/abc', env=True).request_uri,
|
||||
'/init/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/abc?def', env=True).request_uri,
|
||||
'/init/default/abc?def')
|
||||
self.assertEqual(filter_url('http://domain.com/index/abc', env=True).request_uri,
|
||||
"/init/default/index/abc")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def', env=True).request_uri,
|
||||
"/init/default/abc/def")
|
||||
self.assertEqual(filter_url('http://domain.com/index/a%20bc', env=True).request_uri,
|
||||
"/init/default/index/a%20bc")
|
||||
|
||||
if __name__ == '__main__':
|
||||
setUpModule() # pre-2.7
|
||||
unittest.main()
|
||||
tearDownModule()
|
||||
@@ -0,0 +1,363 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""Unit tests for rewrite.py regex routing option"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import unittest
|
||||
import tempfile
|
||||
import logging
|
||||
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon')) # running from web2py base
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../')) # running from gluon/tests/
|
||||
|
||||
from rewrite import load, filter_url, filter_err, get_effective_router, regex_filter_out, regex_select
|
||||
from html import URL
|
||||
from fileutils import abspath
|
||||
from settings import global_settings
|
||||
from http import HTTP
|
||||
from storage import Storage
|
||||
|
||||
logger = None
|
||||
oldcwd = None
|
||||
root = None
|
||||
|
||||
def setUpModule():
|
||||
def make_apptree():
|
||||
"build a temporary applications tree"
|
||||
# applications/
|
||||
os.mkdir(abspath('applications'))
|
||||
# applications/app/
|
||||
for app in ('admin', 'examples', 'welcome'):
|
||||
os.mkdir(abspath('applications', app))
|
||||
# applications/app/(controllers, static)
|
||||
for subdir in ('controllers', 'static'):
|
||||
os.mkdir(abspath('applications', app, subdir))
|
||||
# applications/admin/controllers/*.py
|
||||
for ctr in ('appadmin', 'default', 'gae', 'mercurial', 'shell', 'wizard'):
|
||||
open(abspath('applications', 'admin', 'controllers', '%s.py' % ctr), 'w').close()
|
||||
# applications/examples/controllers/*.py
|
||||
for ctr in ('ajax_examples', 'appadmin', 'default', 'global', 'spreadsheet'):
|
||||
open(abspath('applications', 'examples', 'controllers', '%s.py' % ctr), 'w').close()
|
||||
# applications/welcome/controllers/*.py
|
||||
for ctr in ('appadmin', 'default'):
|
||||
open(abspath('applications', 'welcome', 'controllers', '%s.py' % ctr), 'w').close()
|
||||
# create an app-specific routes.py for examples app
|
||||
routes = open(abspath('applications', 'examples', 'routes.py'), 'w')
|
||||
routes.write("default_function='exdef'\n")
|
||||
routes.close()
|
||||
|
||||
global oldcwd
|
||||
if oldcwd is None: # do this only once
|
||||
oldcwd = os.getcwd()
|
||||
if not os.path.isdir('gluon'):
|
||||
os.chdir(os.path.realpath('../../')) # run from web2py base directory
|
||||
import main # for initialization after chdir
|
||||
global logger
|
||||
logger = logging.getLogger('web2py.rewrite')
|
||||
global_settings.applications_parent = tempfile.mkdtemp()
|
||||
global root
|
||||
root = global_settings.applications_parent
|
||||
make_apptree()
|
||||
|
||||
def tearDownModule():
|
||||
global oldcwd
|
||||
if oldcwd is not None:
|
||||
os.chdir(oldcwd)
|
||||
oldcwd = None
|
||||
|
||||
|
||||
class TestRoutes(unittest.TestCase):
|
||||
""" Tests the regex routing logic from gluon.rewrite """
|
||||
|
||||
def test_routes_null(self):
|
||||
""" Tests a null routes table """
|
||||
load(data='')
|
||||
# incoming
|
||||
self.assertEqual(filter_url('http://domain.com'), '/init/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/'), '/init/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/abc'), '/abc/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/abc/'), '/abc/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def'), "/abc/def/index")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def/'), "/abc/def/index")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def/ghi'), "/abc/def/ghi")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def/ghi/'), "/abc/def/ghi")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def/ghi/jkl'), "/abc/def/ghi ['jkl']")
|
||||
self.assertEqual(filter_url('http://domain.com/abc/def/ghi/j%20kl'), "/abc/def/ghi ['j_kl']")
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/path/to/static'), "%s/applications/welcome/static/path/to/static" % root)
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/welcome/static/bad/path/to/st~tic')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, "400.*BAD REQUEST \[invalid path\]", filter_url, 'http://domain.com/welcome/static/bad/path/to/st~tic')
|
||||
except AttributeError:
|
||||
pass
|
||||
# outgoing
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/index', out=True), '/init/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/index/arg1', out=True), '/init/default/index/arg1')
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/abc', out=True), '/init/default/abc')
|
||||
|
||||
def test_routes_query(self):
|
||||
""" Test query appending """
|
||||
data = r'''
|
||||
routes_in = (
|
||||
('/service/$model/create', '/app/default/call/json/create?model=$model'),
|
||||
)
|
||||
'''
|
||||
load(data=data)
|
||||
self.assertEqual(filter_url('http://localhost:8000/service/person/create'), "/app/default/call ['json', 'create'] ?model=person")
|
||||
self.assertEqual(filter_url('http://localhost:8000/service/person/create?var1=val1'), "/app/default/call ['json', 'create'] ?model=person&var1=val1")
|
||||
|
||||
def test_routes_specific(self):
|
||||
"""
|
||||
Test app-specific routes.py
|
||||
|
||||
Note that make_apptree above created applications/examples/routes.py with a default_function.
|
||||
"""
|
||||
data = r'''
|
||||
routes_app = [
|
||||
(r'/(?P<app>welcome|admin|examples)\b.*', r'\g<app>'),
|
||||
(r'$anything', r'welcome'),
|
||||
(r'/?$anything', r'welcome'),
|
||||
]
|
||||
'''
|
||||
load(data=data)
|
||||
self.assertEqual(filter_url('http://domain.com/welcome'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/examples'), '/examples/default/exdef')
|
||||
|
||||
def test_routes_defapp(self):
|
||||
""" Test the default-application function """
|
||||
data = r'''
|
||||
default_application = 'defapp'
|
||||
'''
|
||||
load(data=data)
|
||||
# incoming
|
||||
self.assertEqual(filter_url('http://domain.com'), '/defapp/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/'), '/defapp/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome'), '/welcome/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/app'), '/app/default/index')
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/index/abc'), "/welcome/default/index ['abc']")
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/static/abc'), '%s/applications/welcome/static/abc' % root)
|
||||
self.assertEqual(filter_url('http://domain.com/defapp/static/path/to/static'), "%s/applications/defapp/static/path/to/static" % root)
|
||||
|
||||
def test_routes_raise(self):
|
||||
'''
|
||||
Test URLs that raise exceptions
|
||||
'''
|
||||
# test non-exception variants
|
||||
load(data='')
|
||||
self.assertEqual(filter_url('http://domain.com/init'), "/init/default/index")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default'), "/init/default/index")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/fcn.ext'), "/init/default/fcn.ext")
|
||||
self.assertEqual(filter_url('http://domain.com/init/default/fcn/arg'), "/init/default/fcn ['arg']")
|
||||
# now raise-HTTP variants
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/bad!ctl')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/ctl/bad!fcn')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/ctl/fcn.bad!ext')
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/ctl/fcn/bad!arg')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, '400 BAD REQUEST \[invalid path\]', filter_url, 'http://domain.com/init/bad!ctl')
|
||||
self.assertRaisesRegexp(HTTP, '400 BAD REQUEST \[invalid path\]', filter_url, 'http://domain.com/init/ctlr/bad!fcn')
|
||||
self.assertRaisesRegexp(HTTP, '400 BAD REQUEST \[invalid path\]', filter_url, 'http://domain.com/init/ctlr/fcn.bad!ext')
|
||||
self.assertRaisesRegexp(HTTP, '400 BAD REQUEST \[invalid path \(args\)\]', filter_url, 'http://domain.com/appc/init/fcn/bad!arg')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/fcn_1'), "/welcome/default/fcn_1")
|
||||
self.assertRaises(HTTP, filter_url, 'http://domain.com/welcome/default/fcn-1')
|
||||
try:
|
||||
# 2.7+ only
|
||||
self.assertRaisesRegexp(HTTP, '400 BAD REQUEST \[invalid path\]', filter_url, 'http://domain.com/welcome/default/fcn-1')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def test_routes_error(self):
|
||||
'''
|
||||
Test rewrite of HTTP errors
|
||||
'''
|
||||
router_err = dict()
|
||||
load(rdict=router_err)
|
||||
self.assertEqual(filter_err(200), 200)
|
||||
self.assertEqual(filter_err(399), 399)
|
||||
self.assertEqual(filter_err(400), 400)
|
||||
|
||||
def test_routes_args(self):
|
||||
'''
|
||||
Test URL args parsing/generation
|
||||
'''
|
||||
data = r'''routes_in = [
|
||||
('/robots.txt', '/welcome/static/robots.txt'),
|
||||
('/favicon.ico', '/welcome/static/favicon.ico'),
|
||||
('/admin$anything', '/admin$anything'),
|
||||
('.*:https?://(.*\\.)?domain1.com:$method /', '/app1/default'),
|
||||
('.*:https?://(.*\\.)?domain1.com:$method /static/$anything', '/app1/static/$anything'),
|
||||
('.*:https?://(.*\\.)?domain1.com:$method /appadmin/$anything', '/app1/appadmin/$anything'),
|
||||
('.*:https?://(.*\\.)?domain1.com:$method /$anything', '/app1/default/$anything'),
|
||||
('.*:https?://(.*\\.)?domain2.com:$method /', '/app2/default'),
|
||||
('.*:https?://(.*\\.)?domain2.com:$method /static/$anything', '/app2/static/$anything'),
|
||||
('.*:https?://(.*\\.)?domain2.com:$method /appadmin/$anything', '/app2/appadmin/$anything'),
|
||||
('.*:https?://(.*\\.)?domain2.com:$method /$anything', '/app2/default/$anything'),
|
||||
('.*:https?://(.*\\.)?domain3.com:$method /', '/app3/defcon3'),
|
||||
('.*:https?://(.*\\.)?domain3.com:$method /static/$anything', '/app3/static/$anything'),
|
||||
('.*:https?://(.*\\.)?domain3.com:$method /appadmin/$anything', '/app3/appadmin/$anything'),
|
||||
('.*:https?://(.*\\.)?domain3.com:$method /$anything', '/app3/defcon3/$anything'),
|
||||
('/', '/welcome/default'),
|
||||
('/welcome/default/$anything', '/welcome/default/$anything'),
|
||||
('/welcome/$anything', '/welcome/default/$anything'),
|
||||
('/static/$anything', '/welcome/static/$anything'),
|
||||
('/appadmin/$anything', '/welcome/appadmin/$anything'),
|
||||
('/$anything', '/welcome/default/$anything'),
|
||||
]
|
||||
routes_out = [
|
||||
('/welcome/static/$anything', '/static/$anything'),
|
||||
('/welcome/appadmin/$anything', '/appadmin/$anything'),
|
||||
('/welcome/default/$anything', '/$anything'),
|
||||
('/app1/static/$anything', '/static/$anything'),
|
||||
('/app1/appadmin/$anything', '/appadmin/$anything'),
|
||||
('/app1/default/$anything', '/$anything'),
|
||||
('/app2/static/$anything', '/static/$anything'),
|
||||
('/app2/appadmin/$anything', '/appadmin/$anything'),
|
||||
('/app2/default/$anything', '/$anything'),
|
||||
('/app3/static/$anything', '/static/$anything'),
|
||||
('/app3/appadmin/$anything', '/appadmin/$anything'),
|
||||
('/app3/defcon3/$anything', '/$anything')
|
||||
]
|
||||
'''
|
||||
load(data=data)
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/f/arg1'),
|
||||
"/welcome/default/f ['arg1']")
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/f/arg1/'),
|
||||
"/welcome/default/f ['arg1']")
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/f/arg1//'),
|
||||
"/welcome/default/f ['arg1', '']")
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/f//arg1'),
|
||||
"/welcome/default/f ['', 'arg1']")
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/f/arg1/arg2'),
|
||||
"/welcome/default/f ['arg1', 'arg2']")
|
||||
|
||||
self.assertEqual(filter_url('http://domain.com/welcome/default/f', out=True), "/f")
|
||||
self.assertEqual(regex_filter_out('/welcome/default/f'), "/f")
|
||||
self.assertEqual(str(URL(a='welcome', c='default', f='f', args=None)), "/f")
|
||||
self.assertEqual(str(URL(a='welcome', c='default', f='f', args=['arg1'])), "/f/arg1")
|
||||
self.assertEqual(str(URL(a='welcome', c='default', f='f', args=['arg1', ''])), "/f/arg1//")
|
||||
self.assertEqual(str(URL(a='welcome', c='default', f='f', args=['arg1', '', 'arg3'])), "/f/arg1//arg3")
|
||||
self.assertEqual(str(URL(a='welcome', c='default', f='f', args=['ar g'])), "/f/ar%20g")
|
||||
self.assertEqual(str(URL(a='welcome', c='default', f='f', args=['årg'])), "/f/%C3%A5rg")
|
||||
self.assertEqual(str(URL(a='welcome', c='default', f='fünc')), "/f\xc3\xbcnc")
|
||||
|
||||
def test_routes_anchor(self):
|
||||
'''
|
||||
Test URL with anchor
|
||||
'''
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', anchor='anchor')), "/a/c/f#anchor")
|
||||
load(data='')
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', anchor='anchor')), "/a/c/f#anchor")
|
||||
args = ['a1', 'a2']
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', args=args, anchor='anchor')),
|
||||
"/a/c/f/a1/a2#anchor")
|
||||
vars = dict(v1=1, v2=2)
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', vars=vars, anchor='anchor')),
|
||||
"/a/c/f?v1=1&v2=2#anchor")
|
||||
self.assertEqual(str(URL(a='a', c='c', f='f', args=args, vars=vars, anchor='anchor')),
|
||||
"/a/c/f/a1/a2?v1=1&v2=2#anchor")
|
||||
|
||||
data = r'''routes_out = [
|
||||
('/init/default/index', '/'),
|
||||
]'''
|
||||
load(data=data)
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index')),
|
||||
"/")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index', anchor='anchor')),
|
||||
"/init/default/index#anchor")
|
||||
|
||||
data = r'''routes_out = [
|
||||
(r'/init/default/index(?P<anchor>(#.*)?)', r'/\g<anchor>'),
|
||||
]'''
|
||||
load(data=data)
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index')),
|
||||
"/")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index', anchor='anchor')),
|
||||
"/#anchor")
|
||||
|
||||
data = r'''routes_out = [
|
||||
(r'/init/default/index(?P<qa>([?#].*)?)', r'/\g<qa>'),
|
||||
]'''
|
||||
load(data=data)
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index')),
|
||||
"/")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index', anchor='anchor')),
|
||||
"/#anchor")
|
||||
query = dict(var='abc')
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index', vars=query)),
|
||||
"/?var=abc")
|
||||
self.assertEqual(str(URL(a='init', c='default', f='index', vars=query, anchor='anchor')),
|
||||
"/?var=abc#anchor")
|
||||
|
||||
def test_routes_absolute(self):
|
||||
'''
|
||||
Test absolute URL
|
||||
'''
|
||||
load(data='')
|
||||
r = Storage()
|
||||
r.env = Storage()
|
||||
r.env.http_host = 'domain.com'
|
||||
r.env.WSGI_URL_SCHEME = 'httpx' # distinguish incoming scheme
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f')), "/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', host=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', host='host.com')),
|
||||
"httpx://host.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=False)),
|
||||
"/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='https')),
|
||||
"https://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='wss')),
|
||||
"wss://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True, host=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='https', host=True)),
|
||||
"https://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=False, host=True)),
|
||||
"httpx://domain.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True, host='host.com')),
|
||||
"httpx://host.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=False, host='host.com')),
|
||||
"httpx://host.com/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', port=1234)),
|
||||
"httpx://domain.com:1234/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme=True, port=1234)),
|
||||
"httpx://domain.com:1234/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', host='host.com', port=1234)),
|
||||
"httpx://host.com:1234/a/c/f")
|
||||
self.assertEqual(str(URL(r=r, a='a', c='c', f='f', scheme='wss', host='host.com', port=1234)),
|
||||
"wss://host.com:1234/a/c/f")
|
||||
|
||||
def test_request_uri(self):
|
||||
'''
|
||||
Test REQUEST_URI in env
|
||||
'''
|
||||
data = r'''routes_in = [
|
||||
('/abc', '/init/default/abc'),
|
||||
('/index/$anything', '/init/default/index/$anything'),
|
||||
]
|
||||
'''
|
||||
load(data=data)
|
||||
self.assertEqual(filter_url('http://domain.com/abc', env=True).request_uri,
|
||||
'/init/default/abc')
|
||||
self.assertEqual(filter_url('http://domain.com/abc?def', env=True).request_uri,
|
||||
'/init/default/abc?def')
|
||||
self.assertEqual(filter_url('http://domain.com/index/abc', env=True).request_uri,
|
||||
"/init/default/index/abc")
|
||||
self.assertEqual(filter_url('http://domain.com/index/a%20bc', env=True).request_uri,
|
||||
"/init/default/index/a bc")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
setUpModule() # pre-2.7
|
||||
unittest.main()
|
||||
tearDownModule()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
""" Unit tests for storage.py """
|
||||
|
||||
import sys
|
||||
import os
|
||||
import unittest
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon'))
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../'))
|
||||
|
||||
from storage import Storage
|
||||
|
||||
|
||||
class TestStorage(unittest.TestCase):
|
||||
""" Tests storage.Storage """
|
||||
|
||||
def test_attribute(self):
|
||||
""" Tests Storage attribute handling """
|
||||
|
||||
s = Storage(a=1)
|
||||
|
||||
self.assertEqual(s.a, 1)
|
||||
self.assertEqual(s['a'], 1)
|
||||
self.assertEqual(s.b, None)
|
||||
|
||||
s.b = 2
|
||||
self.assertEqual(s.a, 1)
|
||||
self.assertEqual(s['a'], 1)
|
||||
self.assertEqual(s.b, 2)
|
||||
self.assertEqual(s['b'], 2)
|
||||
|
||||
s['c'] = 3
|
||||
self.assertEqual(s.c, 3)
|
||||
self.assertEqual(s['c'], 3)
|
||||
|
||||
s.d = list()
|
||||
self.assertTrue(s.d is s['d'])
|
||||
|
||||
|
||||
def test_store_none(self):
|
||||
""" Test Storage store-None handling
|
||||
s.key = None deletes an item
|
||||
s['key'] = None sets the item to None
|
||||
"""
|
||||
|
||||
s = Storage(a=1)
|
||||
|
||||
self.assertTrue('a' in s)
|
||||
self.assertFalse('b' in s)
|
||||
s.a = None
|
||||
self.assertFalse('a' in s)
|
||||
|
||||
s.a = 1
|
||||
self.assertTrue('a' in s)
|
||||
s['a'] = None
|
||||
self.assertTrue('a' in s)
|
||||
self.assertTrue(s.a is None)
|
||||
|
||||
|
||||
def test_item(self):
|
||||
""" Tests Storage item handling """
|
||||
|
||||
s = Storage()
|
||||
|
||||
self.assertEqual(s.d, None)
|
||||
self.assertEqual(s['d'], None)
|
||||
#self.assertRaises(KeyError, lambda x: s[x], 'd') # old Storage
|
||||
s.a = 1
|
||||
s['a'] = None
|
||||
self.assertEquals(s.a, None)
|
||||
self.assertEquals(s['a'], None)
|
||||
self.assertTrue('a' in s)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Unit tests for gluon.template
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon'))
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../'))
|
||||
|
||||
import unittest
|
||||
from template import render
|
||||
|
||||
class TestVirtualFields(unittest.TestCase):
|
||||
|
||||
def testRun(self):
|
||||
self.assertEqual(render(content='{{for i in range(n):}}{{=i}}{{pass}}',
|
||||
context=dict(n=3)), '012')
|
||||
self.assertEqual(render(content='{{if n>2:}}ok{{pass}}',
|
||||
context=dict(n=3)), 'ok')
|
||||
self.assertEqual(render(content='{{try:}}{{n/0}}{{except:}}fail{{pass}}',
|
||||
context=dict(n=3)), 'fail')
|
||||
self.assertEqual(render(content='{{="<&>"}}'), '<&>')
|
||||
self.assertEqual(render(content='"abc"'), '"abc"')
|
||||
self.assertEqual(render(content='"a\'bc"'), '"a\'bc"')
|
||||
self.assertEqual(render(content='"a\"bc"'), '"a\"bc"')
|
||||
self.assertEqual(render(content=r'''"a\"bc"'''), r'"a\"bc"')
|
||||
self.assertEqual(render(content=r'''"""abc\""""'''), r'"""abc\""""')
|
||||
|
||||
def testEqualWrite(self):
|
||||
"test generation of response.write from ="
|
||||
self.assertEqual(render(content='{{="abc"}}'), 'abc')
|
||||
# whitespace is stripped
|
||||
self.assertEqual(render(content='{{ ="abc"}}'), 'abc')
|
||||
self.assertEqual(render(content='{{ ="abc" }}'), 'abc')
|
||||
self.assertEqual(render(content='{{pass\n="abc" }}'), 'abc')
|
||||
# = recognized only at the beginning of a physical line
|
||||
self.assertEqual(render(content='{{xyz = "xyz"\n="abc"\n="def"\n=xyz }}'), 'abcdefxyz')
|
||||
# = in python blocks
|
||||
self.assertEqual(render(content='{{if True:\n="abc"\npass }}'), 'abc')
|
||||
self.assertEqual(render(content='{{if True:\n="abc"\npass\n="def" }}'), 'abcdef')
|
||||
self.assertEqual(render(content='{{if False:\n="abc"\npass\n="def" }}'), 'def')
|
||||
self.assertEqual(render(content='{{if True:\n="abc"\nelse:\n="def"\npass }}'), 'abc')
|
||||
self.assertEqual(render(content='{{if False:\n="abc"\nelse:\n="def"\npass }}'), 'def')
|
||||
# codeblock-leading = handles internal newlines, escaped or not
|
||||
self.assertEqual(render(content='{{=list((1,2,3))}}'), '[1, 2, 3]')
|
||||
self.assertEqual(render(content='{{=list((1,2,\\\n3))}}'), '[1, 2, 3]')
|
||||
self.assertEqual(render(content='{{=list((1,2,\n3))}}'), '[1, 2, 3]')
|
||||
# ...but that means no more = operators in the codeblock
|
||||
self.assertRaises(SyntaxError, render, content='{{="abc"\n="def" }}')
|
||||
# = embedded in codeblock won't handle newlines in its argument
|
||||
self.assertEqual(render(content='{{pass\n=list((1,2,\\\n3))}}'), '[1, 2, 3]')
|
||||
self.assertRaises(SyntaxError, render, content='{{pass\n=list((1,2,\n3))}}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
""" Unit tests for utils.py """
|
||||
|
||||
import sys
|
||||
import os
|
||||
import unittest
|
||||
if os.path.isdir('gluon'):
|
||||
sys.path.append(os.path.realpath('gluon'))
|
||||
else:
|
||||
sys.path.append(os.path.realpath('../'))
|
||||
|
||||
from utils import md5_hash
|
||||
|
||||
|
||||
class TestUtils(unittest.TestCase):
|
||||
""" Tests the utils.py module """
|
||||
|
||||
def test_md5_hash(self):
|
||||
""" Tests the md5_hash function """
|
||||
|
||||
data = md5_hash("web2py rocks")
|
||||
self.assertEqual(data, '79509f3246a2824dee64635303e99204')
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user