Esempio n. 1
0
 def test_IS_IN_DB(self):
     from gluon.dal import DAL, Field
     db = DAL('sqlite:memory')
     db.define_table('person', Field('name'))
     george_id = db.person.insert(name='george')
     costanza_id = db.person.insert(name='costanza')
     rtn = IS_IN_DB(db, 'person.id', '%(name)s')(george_id)
     self.assertEqual(rtn, (george_id, None))
     rtn = IS_IN_DB(db, 'person.id', '%(name)s',
                    error_message='oops')(george_id + costanza_id)
     self.assertEqual(rtn, (george_id + costanza_id, 'oops'))
     rtn = IS_IN_DB(db, db.person.id, '%(name)s')(george_id)
     self.assertEqual(rtn, (george_id, None))
     rtn = IS_IN_DB(db, db.person.id, '%(name)s',
                    error_message='oops')(george_id + costanza_id)
     self.assertEqual(rtn, (george_id + costanza_id, 'oops'))
     rtn = IS_IN_DB(db, 'person.id', '%(name)s',
                    multiple=True)([george_id, costanza_id])
     self.assertEqual(rtn, ([george_id, costanza_id], None))
     rtn = IS_IN_DB(db,
                    'person.id',
                    '%(name)s',
                    multiple=True,
                    delimiter=',')('%d,%d' % (george_id, costanza_id))
     self.assertEqual(rtn, (('%d,%d' %
                             (george_id, costanza_id)).split(','), None))
     rtn = IS_IN_DB(db, db.person.id, '%(name)s',
                    error_message='oops').options(zero=False)
     self.assertEqual(sorted(rtn), [('%d' % george_id, 'george'),
                                    ('%d' % costanza_id, 'costanza')])
     db.person.drop()
Esempio n. 2
0
class TestSQLTABLE(unittest.TestCase):
    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt'), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(first_name='Bart',
                                 last_name='Simpson',
                                 username='******',
                                 email='*****@*****.**',
                                 password='******',
                                 registration_key=None,
                                 registration_id=None)

        self.db.commit()
Esempio n. 3
0
 def testDALcache(self):
     s = Storage({'application': 'admin', 'folder': 'applications/admin'})
     cache = Cache(s)
     db = DAL(check_reserved=['all'])
     db.define_table('t_a', Field('f_a'))
     db.t_a.insert(f_a='test')
     db.commit()
     a = db(db.t_a.id > 0).select(cache=(cache.ram, 60), cacheable=True)
     b = db(db.t_a.id > 0).select(cache=(cache.ram, 60), cacheable=True)
     self.assertEqual(a.as_csv(), b.as_csv())
     c = db(db.t_a.id > 0).select(cache=(cache.disk, 60), cacheable=True)
     d = db(db.t_a.id > 0).select(cache=(cache.disk, 60), cacheable=True)
     self.assertEqual(c.as_csv(), d.as_csv())
     self.assertEqual(a.as_csv(), c.as_csv())
     self.assertEqual(b.as_csv(), d.as_csv())
     e = db(db.t_a.id > 0).select(cache=(cache.disk, 60))
     f = db(db.t_a.id > 0).select(cache=(cache.disk, 60))
     self.assertEqual(e.as_csv(), f.as_csv())
     self.assertEqual(a.as_csv(), f.as_csv())
     g = db(db.t_a.id > 0).select(cache=(cache.ram, 60))
     h = db(db.t_a.id > 0).select(cache=(cache.ram, 60))
     self.assertEqual(g.as_csv(), h.as_csv())
     self.assertEqual(a.as_csv(), h.as_csv())
     db.t_a.drop()
     db.close()
Esempio n. 4
0
 def testSerialization(self):
     import pickle
     db = DAL(check_reserved=['all'])
     db.define_table('t_a', Field('f_a'))
     db.t_a.insert(f_a='test')
     a = db(db.t_a.id > 0).select(cacheable=True)
     s = pickle.dumps(a)
     b = pickle.loads(s)
     self.assertEqual(a.db, b.db)
Esempio n. 5
0
 def test_IS_NOT_IN_DB(self):
     from gluon.dal import DAL, Field
     db = DAL('sqlite:memory')
     db.define_table('person', Field('name'))
     db.person.insert(name='george')
     rtn = IS_NOT_IN_DB(db, 'person.name', error_message='oops')('george')
     self.assertEqual(rtn, ('george', 'oops'))
     rtn = IS_NOT_IN_DB(db, 'person.name')('jerry')
     self.assertEqual(rtn, ('jerry', None))
     db.person.drop()
Esempio n. 6
0
 def testSerialization(self):
     from gluon._compat import pickle
     db = DAL('sqlite:memory', check_reserved=['all'])
     db.define_table('t_a', Field('f_a'))
     db.t_a.insert(f_a='test')
     a = db(db.t_a.id > 0).select(cacheable=True)
     s = pickle.dumps(a)
     b = pickle.loads(s)
     self.assertEqual(a.db, b.db)
     db.t_a.drop()
     db.close()
Esempio n. 7
0
    def testRun(self):
        # setup
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        db = DAL(DEFAULT_URI, check_reserved=['all'])
        auth = Auth(db)
        auth.define_tables(username=True, signature=False)
        self.assertTrue('auth_user' in db)
        self.assertTrue('auth_group' in db)
        self.assertTrue('auth_membership' in db)
        self.assertTrue('auth_permission' in db)
        self.assertTrue('auth_event' in db)
        db.define_table('t0', Field('tt'), auth.signature)
        auth.enable_record_versioning(db)
        self.assertTrue('t0_archive' in db)
        for f in [
                'login', 'register', 'retrieve_password', 'retrieve_username'
        ]:
            html_form = getattr(auth, f)().xml()
            self.assertTrue('name="_formkey"' in html_form)

        for f in [
                'logout', 'verify_email', 'reset_password', 'change_password',
                'profile', 'groups'
        ]:
            self.assertRaisesRegexp(HTTP, "303*", getattr(auth, f))

        self.assertRaisesRegexp(HTTP, "401*", auth.impersonate)

        try:
            for t in [
                    't0_archive', 't0', 'auth_cas', 'auth_event',
                    'auth_membership', 'auth_permission', 'auth_group',
                    'auth_user'
            ]:
                db[t].drop()
        except SyntaxError as e:
            # GAE doesn't support drop
            pass
        return
 def setUp(self):
     from gluon.globals import Request, Response, Session, current
     from gluon.html import A, DIV, FORM, MENU, TABLE, TR, INPUT, URL, XML
     from gluon.html import ASSIGNJS
     from gluon.validators import IS_NOT_EMPTY
     from gluon.compileapp import LOAD
     from gluon.http import HTTP, redirect
     from gluon.tools import Auth
     from gluon.sql import SQLDB
     from gluon.sqlhtml import SQLTABLE, SQLFORM
     self.original_check_credentials = fileutils.check_credentials
     fileutils.check_credentials = fake_check_credentials
     request = Request(env={})
     request.application = 'welcome'
     request.controller = 'appadmin'
     request.function = self._testMethodName.split('_')[1]
     request.folder = 'applications/welcome'
     request.env.http_host = '127.0.0.1:8000'
     request.env.remote_addr = '127.0.0.1'
     response = Response()
     session = Session()
     T = translator('', 'en')
     session.connect(request, response)
     current.request = request
     current.response = response
     current.session = session
     current.T = T
     db = DAL(DEFAULT_URI, check_reserved=['all'])
     auth = Auth(db)
     auth.define_tables(username=True, signature=False)
     db.define_table('t0', Field('tt'), auth.signature)
     # Create a user
     db.auth_user.insert(first_name='Bart',
                         last_name='Simpson',
                         username='******',
                         email='*****@*****.**',
                         password='******',
                         registration_key=None,
                         registration_id=None)
     self.env = locals()
Esempio n. 9
0
class TestSQLTABLE(unittest.TestCase):
    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt'), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(first_name='Bart',
                                 last_name='Simpson',
                                 username='******',
                                 email='*****@*****.**',
                                 password='******',
                                 registration_key=None,
                                 registration_id=None)

        self.db.commit()

    def test_SQLTABLE(self):
        rows = self.db(self.db.auth_user.id > 0).select(self.db.auth_user.ALL)
        sqltable = SQLTABLE(rows)
        self.assertEqual(
            sqltable.xml(),
            '<table><thead><tr><th>auth_user.id</th><th>auth_user.first_name</th><th>auth_user.last_name</th><th>auth_user.email</th><th>auth_user.username</th><th>auth_user.password</th><th>auth_user.registration_key</th><th>auth_user.reset_password_key</th><th>auth_user.registration_id</th></tr></thead><tbody><tr class="w2p_odd odd"><td>1</td><td>Bart</td><td>Simpson</td><td>[email protected]</td><td>user1</td><td>password_123</td><td>None</td><td></td><td>None</td></tr></tbody></table>'
        )
Esempio n. 10
0
class Dal(object):
    def __init__(self, table=None, pool_size=8):
        self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
        if table == 'World':
            self.db.define_table('World', Field('randomNumber', 'integer'))
        elif table == 'Fortune':
            self.db.define_table('Fortune', Field('message'))

    def get_world(self, wid):
        # Setting `cacheable=True` improves performance by foregoing the creation
        # of some non-essential attributes. It does *not* actually cache the
        # database results (it simply produces a Rows object that *could be* cached).
        return self.db(self.db.World.id == wid).select(
            cacheable=True)[0].as_dict()

    def update_world(self, wid, randomNumber):
        self.db(self.db.World.id == wid).update(randomNumber=randomNumber)

    def get_fortunes(self, new_message):
        fortunes = self.db(self.db.Fortune).select(cacheable=True)
        fortunes.records.append(Row(new_message))
        return fortunes.sort(itemgetter('message'))
Esempio n. 11
0
# import web2py (change the path!)
sys.path.append(r"/home/reingart/web2py")
from gluon.dal import DAL, Field
from gluon.sqlhtml import SQLFORM
from gluon.html import INPUT, FORM, TABLE, TR, TD
from gluon.validators import IS_NOT_EMPTY, IS_EXPR, IS_NOT_IN_DB, IS_IN_SET
from gluon.storage import Storage

# create DAL connection (and create DB if not exists)
db = DAL('sqlite://guitest.sqlite', folder=None)

# define a table 'person' (create/aster as necessary)
person = db.define_table(
    'person',
    Field('name', 'string', length=100),
    Field('sex', 'string', length=1),
    Field('active', 'boolean', comment="check!"),
    Field('bio', 'text', comment="resume (CV)"),
)

# set sample validator (do not allow empty nor duplicate names)
db.person.name.requires = [IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'person.name')]

db.person.sex.requires = IS_IN_SET({'M': 'Male', 'F': 'Female'})

# create the wxPython GUI application instance:
app = wx.App(False)

# create a testing frame (wx "window"):
f = wx.Frame(None, title="web2py/gui2py sample app")
Esempio n. 12
0
auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = True
auth.settings.reset_password_requires_verification = True

#
# MODELO:
# pais, provincia, poblacion
# Sede, Almacen, Alimento, Estanteria, Cierre
# Colaborador, Beneficiario
# CabeceraAlmacen, LineaAlmacen, CabeceraEntrada, LineaEntrada, CabeceraSalida, LineaEntrada


db.define_table(
    'Alimento',
    Field('Codigo', 'integer', label='Código'),
    Field('Descripcion', label='Descripción'),
    Field('Conservacion', label='Conservación', default=T('Calor')),
    Field('Unidades', default='Kg.'),
    format='%(Codigo)s - %(Descripcion)s',
)
db.Alimento.Conservacion.requires = IS_IN_SET((T('Calor'), T('Frío')))
db.Alimento.Unidades.requires = IS_IN_SET(('Kg.', 'L.'))

# after defining tables, uncomment below to enable auditing
# auth.enable_record_versioning(db)

# Lista de paises, obtenida de
# http://dmnet.bitacoras.com/archivos/inclasificable/lista-de-paises-en-sql.php

# id: ID numérico según la ISO 3166-1 y la División Estadística de las Naciones Unidas
# iso2: código de dos letras según la ISO 3166-1
# iso3: código de tres letras según la ISO 3166-1
Esempio n. 13
0
class TestSQLFORM(unittest.TestCase):
    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt'), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(first_name='Bart',
                                 last_name='Simpson',
                                 username='******',
                                 email='*****@*****.**',
                                 password='******',
                                 registration_key=None,
                                 registration_id=None)

        self.db.commit()

    def test_SQLFORM(self):
        form = SQLFORM(self.db.auth_user)
        self.assertEqual(
            form.xml(),
            '<form action="#" enctype="multipart/form-data" method="post"><table><tr id="auth_user_first_name__row"><td class="w2p_fl"><label class="" for="auth_user_first_name" id="auth_user_first_name__label">First name: </label></td><td class="w2p_fw"><input class="string" id="auth_user_first_name" name="first_name" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="auth_user_last_name__row"><td class="w2p_fl"><label class="" for="auth_user_last_name" id="auth_user_last_name__label">Last name: </label></td><td class="w2p_fw"><input class="string" id="auth_user_last_name" name="last_name" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="auth_user_email__row"><td class="w2p_fl"><label class="" for="auth_user_email" id="auth_user_email__label">E-mail: </label></td><td class="w2p_fw"><input class="string" id="auth_user_email" name="email" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="auth_user_username__row"><td class="w2p_fl"><label class="" for="auth_user_username" id="auth_user_username__label">Username: </label></td><td class="w2p_fw"><input class="string" id="auth_user_username" name="username" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="auth_user_password__row"><td class="w2p_fl"><label class="" for="auth_user_password" id="auth_user_password__label">Password: </label></td><td class="w2p_fw"><input class="password" id="auth_user_password" name="password" type="password" value="" /></td><td class="w2p_fc"></td></tr><tr id="submit_record__row"><td class="w2p_fl"></td><td class="w2p_fw"><input type="submit" value="Submit" /></td><td class="w2p_fc"></td></tr></table></form>'
        )

    # def test_assert_status(self):
    #     pass

    #  def test_createform(self):
    #     pass

    #  def test_accepts(self):
    #     pass

    #  def test_dictform(self):
    #     pass

    #  def test_smartdictform(self):
    #     pass

    def test_factory(self):
        factory_form = SQLFORM.factory(
            Field('field_one', 'string', IS_NOT_EMPTY()),
            Field('field_two', 'string'))
        self.assertEqual(
            factory_form.xml(),
            '<form action="#" enctype="multipart/form-data" method="post"><table><tr id="no_table_field_one__row"><td class="w2p_fl"><label class="" for="no_table_field_one" id="no_table_field_one__label">Field One: </label></td><td class="w2p_fw"><input class="string" id="no_table_field_one" name="field_one" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="no_table_field_two__row"><td class="w2p_fl"><label class="" for="no_table_field_two" id="no_table_field_two__label">Field Two: </label></td><td class="w2p_fw"><input class="string" id="no_table_field_two" name="field_two" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="submit_record__row"><td class="w2p_fl"></td><td class="w2p_fw"><input type="submit" value="Submit" /></td><td class="w2p_fc"></td></tr></table></form>'
        )

    #  def test_build_query(self):
    #     pass

    #  def test_search_menu(self):
    #     pass

    def test_grid(self):
        grid_form = SQLFORM.grid(self.db.auth_user)
        self.assertEqual(
            grid_form.xml(),
            '<div class="web2py_grid "><div class="web2py_console  "><form action="/a/c/f" enctype="multipart/form-data" method="GET"><input class="form-control" id="w2p_keywords" name="keywords" onfocus="jQuery(&#x27;#w2p_query_fields&#x27;).change();jQuery(&#x27;#w2p_query_panel&#x27;).slideDown();" type="text" value="" /><input class="btn btn-default" type="submit" value="Search" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_keywords&#x27;).val(&#x27;&#x27;);" type="submit" value="Clear" /></form><div id="w2p_query_panel" style="display:none;"><select class="form-control" id="w2p_query_fields" onchange="jQuery(&#x27;.w2p_query_row&#x27;).hide();jQuery(&#x27;#w2p_field_&#x27;+jQuery(&#x27;#w2p_query_fields&#x27;).val().replace(&#x27;.&#x27;,&#x27;-&#x27;)).show();" style="float:left"><option value="auth_user.id">Id</option><option value="auth_user.first_name">First name</option><option value="auth_user.last_name">Last name</option><option value="auth_user.email">E-mail</option><option value="auth_user.username">Username</option></select><div class="w2p_query_row" id="w2p_field_auth_user-id" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="in">in</option><option value="not in">not in</option></select><input class="id form-control" id="w2p_value_auth_user-id" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.id&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.id&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.id&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-first_name" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-first_name" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.first_name&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.first_name&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.first_name&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-last_name" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-last_name" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.last_name&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.last_name&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.last_name&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-email" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-email" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.email&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.email&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.email&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-username" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-username" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.username&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.username&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.username&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div></div><script><!--\n\n        jQuery(\'#w2p_query_fields input,#w2p_query_fields select\').css(\n            \'width\',\'auto\');\n        jQuery(function(){web2py_ajax_fields(\'#w2p_query_fields\');});\n        function w2p_build_query(aggregator,a) {\n          var b=a.replace(\'.\',\'-\');\n          var option = jQuery(\'#w2p_field_\'+b+\' select\').val();\n          var value;\n          var $value_item = jQuery(\'#w2p_value_\'+b);\n          if ($value_item.is(\':checkbox\')){\n            if  ($value_item.is(\':checked\'))\n                    value = \'True\';\n            else  value = \'False\';\n          }\n          else\n          { value = $value_item.val().replace(\'"\',\'\\\\"\')}\n          var s=a+\' \'+option+\' "\'+value+\'"\';\n          var k=jQuery(\'#w2p_keywords\');\n          var v=k.val();\n          if(aggregator==\'new\') k.val(s); else k.val((v?(v+\' \'+ aggregator +\' \'):\'\')+s);\n        }\n        \n//--></script><div class="web2py_counter">1 records found</div></div><div class="web2py_table"><div class="web2py_htmltable" style="width:100%;overflow-x:auto;-ms-overflow-x:scroll"><table><colgroup><col data-column="1" id="auth_user-id" /><col data-column="2" id="auth_user-first_name" /><col data-column="3" id="auth_user-last_name" /><col data-column="4" id="auth_user-email" /><col data-column="5" id="auth_user-username" /><col data-column="6" /></colgroup><thead><tr class=""><th class=""><a href="/a/c/f?keywords=&amp;order=auth_user.id">Id</a></th><th class=""><a href="/a/c/f?keywords=&amp;order=auth_user.first_name">First name</a></th><th class=""><a href="/a/c/f?keywords=&amp;order=auth_user.last_name">Last name</a></th><th class=""><a href="/a/c/f?keywords=&amp;order=auth_user.email">E-mail</a></th><th class=""><a href="/a/c/f?keywords=&amp;order=auth_user.username">Username</a></th><th class=""></th></tr></thead><tbody><tr class="w2p_odd odd with_id" id="1"><td>1</td><td>Bart</td><td>Simpson</td><td>[email protected]</td><td>user1</td><td class="row_buttons" nowrap="nowrap"><a class="button btn btn-default" href="/a/c/f/view/auth_user/1"><span class="icon magnifier icon-zoom-in glyphicon glyphicon-zoom-in"></span> <span class="buttontext button" title="View">View</span></a></td></tr></tbody></table></div></div><div class="w2p_export_menu">Export:<a class="btn btn-default" href="/a/c/f?_export_type=csv&amp;keywords=&amp;order=" title="Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows">CSV</a><a class="btn btn-default" href="/a/c/f?_export_type=csv_with_hidden_cols&amp;keywords=&amp;order=" title="Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export">CSV (hidden cols)</a><a class="btn btn-default" href="/a/c/f?_export_type=html&amp;keywords=&amp;order=" title="HTML export of visible columns">HTML</a><a class="btn btn-default" href="/a/c/f?_export_type=json&amp;keywords=&amp;order=" title="JSON export of visible columns">JSON</a><a class="btn btn-default" href="/a/c/f?_export_type=tsv&amp;keywords=&amp;order=" title="Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.">TSV (Spreadsheets)</a><a class="btn btn-default" href="/a/c/f?_export_type=tsv_with_hidden_cols&amp;keywords=&amp;order=" title="Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow">TSV (Spreadsheets, hidden cols)</a><a class="btn btn-default" href="/a/c/f?_export_type=xml&amp;keywords=&amp;order=" title="XML export of columns shown">XML</a></div></div>'
        )

    def test_smartgrid(self):
        smartgrid_form = SQLFORM.smartgrid(self.db.auth_user)
        self.assertEqual(
            smartgrid_form.xml(),
            '<div class="web2py_grid "><div class="web2py_breadcrumbs"><ul class=""><li class="active w2p_grid_breadcrumb_elem"><a href="/a/c/f/auth_user">Auth users</a></li></ul></div><div class="web2py_console  "><form action="/a/c/f/auth_user" enctype="multipart/form-data" method="GET"><input class="form-control" id="w2p_keywords" name="keywords" onfocus="jQuery(&#x27;#w2p_query_fields&#x27;).change();jQuery(&#x27;#w2p_query_panel&#x27;).slideDown();" type="text" value="" /><input class="btn btn-default" type="submit" value="Search" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_keywords&#x27;).val(&#x27;&#x27;);" type="submit" value="Clear" /></form><div id="w2p_query_panel" style="display:none;"><select class="form-control" id="w2p_query_fields" onchange="jQuery(&#x27;.w2p_query_row&#x27;).hide();jQuery(&#x27;#w2p_field_&#x27;+jQuery(&#x27;#w2p_query_fields&#x27;).val().replace(&#x27;.&#x27;,&#x27;-&#x27;)).show();" style="float:left"><option value="auth_user.id">Id</option><option value="auth_user.first_name">First name</option><option value="auth_user.last_name">Last name</option><option value="auth_user.email">E-mail</option><option value="auth_user.username">Username</option></select><div class="w2p_query_row" id="w2p_field_auth_user-id" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="in">in</option><option value="not in">not in</option></select><input class="id form-control" id="w2p_value_auth_user-id" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.id&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.id&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.id&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-first_name" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-first_name" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.first_name&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.first_name&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.first_name&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-last_name" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-last_name" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.last_name&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.last_name&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.last_name&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-email" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-email" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.email&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.email&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.email&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div><div class="w2p_query_row" id="w2p_field_auth_user-username" style="display:none"><select class="form-control"><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option><option value="starts with">starts with</option><option value="contains">contains</option><option value="in">in</option><option value="not in">not in</option></select><input class="string form-control" id="w2p_value_auth_user-username" type="text" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;new&#x27;,&#x27;auth_user.username&#x27;)" title="Start building a new search" type="button" value="New Search" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;and&#x27;,&#x27;auth_user.username&#x27;)" title="Add this to the search as an AND term" type="button" value="+ And" /><input class="btn btn-default" onclick="w2p_build_query(&#x27;or&#x27;,&#x27;auth_user.username&#x27;)" title="Add this to the search as an OR term" type="button" value="+ Or" /><input class="btn btn-default" onclick="jQuery(&#x27;#w2p_query_panel&#x27;).slideUp()" type="button" value="Close" /></div></div><script><!--\n\n        jQuery(\'#w2p_query_fields input,#w2p_query_fields select\').css(\n            \'width\',\'auto\');\n        jQuery(function(){web2py_ajax_fields(\'#w2p_query_fields\');});\n        function w2p_build_query(aggregator,a) {\n          var b=a.replace(\'.\',\'-\');\n          var option = jQuery(\'#w2p_field_\'+b+\' select\').val();\n          var value;\n          var $value_item = jQuery(\'#w2p_value_\'+b);\n          if ($value_item.is(\':checkbox\')){\n            if  ($value_item.is(\':checked\'))\n                    value = \'True\';\n            else  value = \'False\';\n          }\n          else\n          { value = $value_item.val().replace(\'"\',\'\\\\"\')}\n          var s=a+\' \'+option+\' "\'+value+\'"\';\n          var k=jQuery(\'#w2p_keywords\');\n          var v=k.val();\n          if(aggregator==\'new\') k.val(s); else k.val((v?(v+\' \'+ aggregator +\' \'):\'\')+s);\n        }\n        \n//--></script><div class="web2py_counter">1 records found</div></div><div class="web2py_table"><div class="web2py_htmltable" style="width:100%;overflow-x:auto;-ms-overflow-x:scroll"><table><colgroup><col data-column="1" id="auth_user-id" /><col data-column="2" id="auth_user-first_name" /><col data-column="3" id="auth_user-last_name" /><col data-column="4" id="auth_user-email" /><col data-column="5" id="auth_user-username" /><col data-column="6" /></colgroup><thead><tr class=""><th class=""><a href="/a/c/f/auth_user?keywords=&amp;order=auth_user.id">Id</a></th><th class=""><a href="/a/c/f/auth_user?keywords=&amp;order=auth_user.first_name">First name</a></th><th class=""><a href="/a/c/f/auth_user?keywords=&amp;order=auth_user.last_name">Last name</a></th><th class=""><a href="/a/c/f/auth_user?keywords=&amp;order=auth_user.email">E-mail</a></th><th class=""><a href="/a/c/f/auth_user?keywords=&amp;order=auth_user.username">Username</a></th><th class=""></th></tr></thead><tbody><tr class="w2p_odd odd with_id" id="1"><td>1</td><td>Bart</td><td>Simpson</td><td>[email protected]</td><td>user1</td><td class="row_buttons" nowrap="nowrap"><a href="/a/c/f/auth_user/auth_membership.user_id/1"><span>Auth memberships</span></a><a href="/a/c/f/auth_user/auth_event.user_id/1"><span>Auth events</span></a><a href="/a/c/f/auth_user/auth_cas.user_id/1"><span>Auth cases</span></a><a href="/a/c/f/auth_user/t0.created_by/1"><span>T0s(created_by)</span></a><a href="/a/c/f/auth_user/t0.modified_by/1"><span>T0s(modified_by)</span></a><a href="/a/c/f/auth_user/t0_archive.created_by/1"><span>T0 archives(created_by)</span></a><a href="/a/c/f/auth_user/t0_archive.modified_by/1"><span>T0 archives(modified_by)</span></a><a class="button btn btn-default" href="/a/c/f/auth_user/view/auth_user/1"><span class="icon magnifier icon-zoom-in glyphicon glyphicon-zoom-in"></span> <span class="buttontext button" title="View">View</span></a></td></tr></tbody></table></div></div><div class="w2p_export_menu">Export:<a class="btn btn-default" href="/a/c/f/auth_user?_export_type=csv&amp;keywords=&amp;order=" title="Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows">CSV</a><a class="btn btn-default" href="/a/c/f/auth_user?_export_type=csv_with_hidden_cols&amp;keywords=&amp;order=" title="Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export">CSV (hidden cols)</a><a class="btn btn-default" href="/a/c/f/auth_user?_export_type=html&amp;keywords=&amp;order=" title="HTML export of visible columns">HTML</a><a class="btn btn-default" href="/a/c/f/auth_user?_export_type=json&amp;keywords=&amp;order=" title="JSON export of visible columns">JSON</a><a class="btn btn-default" href="/a/c/f/auth_user?_export_type=tsv&amp;keywords=&amp;order=" title="Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.">TSV (Spreadsheets)</a><a class="btn btn-default" href="/a/c/f/auth_user?_export_type=tsv_with_hidden_cols&amp;keywords=&amp;order=" title="Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow">TSV (Spreadsheets, hidden cols)</a><a class="btn btn-default" href="/a/c/f/auth_user?_export_type=xml&amp;keywords=&amp;order=" title="XML export of columns shown">XML</a></div></div>'
        )
Esempio n. 14
0
class DGFModel():
    """This class update all the tables necessary to the simulation
    """
    def __init__(self):
        """Class initialization function
        """
        # DGF connection. Please use read only user
        try:
            if IN_DGF:
                self.rdb = DAL("mssql://*****:*****@192.168.20.7/DGF",
                               migrate_enabled=False,
                               migrate=False)
            else:
                self.rdb = DAL('sqlite://dgf_database.db',
                               migrate_enabled=False,
                               migrate=False)
            self.session = current.session
            self.request = current.request
            self.response = current.response
            self.cache = current.cache
            self.__define_tables()
            print self.rdb.tables()
        except:
            print "DGFModel: Can't load database!."

    def __define_tables(self):
        """Define all necessary tables in DGF
        """

        self.rdb.define_table('Deptos',
                              Field('Codigo', type='string', length=1),
                              Field('Nombre', type='string'),
                              Field('Numero', type='integer'),
                              primarykey=['Codigo'],
                              migrate=False)

        self.rdb.define_table(
            'Carpetas_P',
            Field('Codigo', type='integer'),
            # El numero de la carpeta
            Field('Nro_Carpeta', type='integer'),
            Field('Fecha_Pres', type='integer'),
            # Solo funciona así por el tema de que es un string
            Field('Cod_Depto', 'reference Deptos.Codigo'),
            Field('Cod_Sj', type='integer'),
            Field('Longitud', type='double'),
            Field('Latitud', type='double'),
            Field('Baja', type='boolean'),
            Field('Notas', type='string'),
            primarykey=['Codigo'],
            migrate=False)

        self.rdb.define_table('Plantas',
                              Field('CodG', type='string'),
                              Field('CodE', type='integer'),
                              Field('Genero', type='string'),
                              Field('Especie', type='string'),
                              Field('Descripcion', type='string'),
                              Field('Apel', type='string'),
                              Field('Carac', type='text'),
                              Field('Foto', type='upload'),
                              Field('Taxo', type='upload'),
                              primarykey=['CodG', 'CodE'],
                              migrate=False)

        self.rdb.define_table(
            'Carpetas_BN',
            Field('Codigo', type='integer'),
            # El numero de la carpeta
            Field('Nro_Carpeta', type='integer'),
            Field('Fecha_pres', type='integer'),
            Field('Cod_Depto', 'reference Deptos.Codigo'),
            Field('Cod_Sj', type='integer'),
            Field('Latitud', type='double'),
            Field('Longitud', type='double'),
            Field('Tipo_Bosque', type='string'),
            Field('Baja', type='boolean'),
            Field('Notas', type='string'),
            primarykey=['Codigo'],
            migrate=False)

        b = u'Año_Pro'
        a = b.encode('utf8')

        self.rdb.define_table(
            'Planes_Pro',
            Field('Codigo', type='integer'),
            # El numero de la carpeta Carpetas_P(Nro_Carpeta)
            Field('Codigo_Cp', type='integer'),
            Field('Fecha_Act', type='datetime'),
            # RFPV - Esto da lio nombre de campo con caracter especial
            # Field('Año_Pro', type='integer'),
            # Field(a,type='integer'),
            Field('Ano_Pro', type='integer'),
            Field('CodG_Pro', type='string'),
            Field('CodE_Pro', type='integer'),
            Field('Epo_Pro', type='string'),
            Field('Ha_Pro', type='double'),
            Field('Den_Pro', type='integer'),
            Field('E1_Pro', type='integer'),
            Field('E2_Pro', type='integer'),
            Field('E3_Pro', type='integer'),
            Field('Cal_Pro', type='string'),
            Field('Met_Pro', type='string'),
            Field('Sem_Pro', type='string'),
            Field('Planta_Pro', type='string'),
            Field('Tipo_Planta_Pro', type='string'),
            Field('Raleo_Pro', type='string'),
            Field('Poda_Pro', type='string'),
            Field('Corta_Pro', type='string'),
            Field('Objetivo_pro', type='string'),
            Field('Proyecto_g_pro', type='string'),
            Field('Observaciones', type='string'),
            primarykey=['Codigo'],
            migrate=False)

        self.rdb.define_table(
            'Planes',
            Field('Codigo', type='integer'),
            # El codigo de Planes_Pro
            Field('Codigo_Plan_Pro', type='integer'),
            Field('Fecha_Act', type='datetime'),
            # RFPV - Esto da lio nombre de campo con caracter especial
            # Field('Año_Dec', type='integer'),
            # Field('Ano_Dec', type='integer'),
            Field('CodG_Dec', type='string'),
            Field('CodE_Dec', type='integer'),
            Field('Epo_Dec', type='string'),
            Field('Ha_Dec', type='double'),
            Field('Den_Dec', type='integer'),
            Field('E1_Dec', type='integer'),
            Field('E2_Dec', type='integer'),
            Field('E3_Dec', type='integer'),
            Field('Cal_Dec', type='string'),
            Field('Met_Dec', type='string'),
            Field('Sem_Dec', type='string'),
            Field('Planta_Dec', type='string'),
            Field('Tipo_Planta_Dec', type='string'),
            Field('Raleo_Dec', type='string'),
            Field('Poda_Dec', type='string'),
            Field('Corta_Dec', type='string'),
            Field('Objetivo_dec', type='string'),
            Field('Proyecto_g_dec', type='string'),
            Field('Observaciones', type='string'),
            primarykey=['Codigo'],
            migrate=False)

        self.rdb.define_table('Propietarios',
                              Field('Codigo', type='integer'),
                              Field('Nombre', type='string'),
                              Field('Direccion', type='string'),
                              Field('Telefono', type='string'),
                              Field('Representacion', type='string'),
                              primarykey=['Codigo'],
                              migrate=False)

        self.rdb.define_table(
            'Registro',
            Field('Codigo', type='integer'),
            #Field('Codigo_Cp_Pr',self.rdb.Carpetas_P),
            #Field('Codigo_Cp_Bn',self.rdb.Carpetas_BN),
            Field('Codigo_Cp_Pr', type='integer'),
            Field('Codigo_Cp_Bn', type='integer'),
            # Solo funciona así por el tema de que es un string
            Field('Cod_Depto', 'reference Deptos.Codigo'),
            Field('Codigo_Pad', type='integer'),
            Field('Anexo', type='string'),
            Field('Tipo_Bos', type='string'),
            Field('Cant_Bosques', type='integer'),
            Field('Cant_Tipo_Bosque', type='integer'),
            Field('Cant_Tipo_Bosque_Depto', type='integer'),
            Field('Resoluciones', type='string'),
            Field('Codigo_Prop', self.rdb.Propietarios),
            Field('Rep_Prop', type='string'),
            Field('Area', type='double'),
            Field('Tipo_Prop', type='string'),
            primarykey=['Codigo'],
            migrate=False)

    def db(self):
        """
        Get the database connection

        :returns:  DAL connection for DGF database
        """
        return (self.rdb)
Esempio n. 15
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
sys.path.append(
    '/Users/xcbfreedom/projects/web2py/web2py.app/Contents/Resources/')

from gluon.dal import DAL, Field
from gluon.sqlhtml import SQLFORM
from gluon.validators import IS_NOT_EMPTY, IS_EMAIL, IS_LENGTH

db = DAL("sqlite://data/mydb.sqlite")
db.define_table('t_contact', Field("name"), Field("email"), Field("phone"))
db.t_contact.name.requires = IS_NOT_EMPTY()
db.t_contact.email.requires = IS_EMAIL()
db.t_contact.phone.requires = IS_LENGTH(14)

#====insert
print db.t_contact.insert(**dict(name="fx", email="x.comll", phone='123'))
print db.t_contact.insert(**dict(name="axbc", email="x.comll", phone='123'))
db.commit()
print 'insert ok'

#====select
print "select "
print db(db.t_contact.phone == '123').select()
print "select one"
print db.t_contact(**dict(phone='123'))
Esempio n. 16
0
class TestSQLFORM(unittest.TestCase):
    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt', default='web2py'),
                             self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(first_name='Bart',
                                 last_name='Simpson',
                                 username='******',
                                 email='*****@*****.**',
                                 password='******',
                                 registration_key=None,
                                 registration_id=None)

        self.db.commit()

    def test_SQLFORM(self):
        form = SQLFORM(self.db.auth_user)
        self.assertEqual(form.xml()[:5], b'<form')

    def test_represent_SQLFORM(self):
        id = self.db.t0.insert()
        self.db.t0.tt.represent = lambda value: value.capitalize()
        self.db.t0.tt.writable = False
        self.db.t0.tt.readable = True
        form = SQLFORM(self.db.t0, id)
        self.assertTrue(b'Web2py' in form.xml())
        self.db.t0.tt.represent = lambda value, row: value.capitalize()
        form = SQLFORM(self.db.t0, id)
        self.assertTrue(b'Web2py' in form.xml())

    # def test_assert_status(self):
    #     pass

    #  def test_createform(self):
    #     pass

    #  def test_accepts(self):
    #     pass

    #  def test_dictform(self):
    #     pass

    #  def test_smartdictform(self):
    #     pass

    def test_factory(self):
        factory_form = SQLFORM.factory(
            Field('field_one', 'string', IS_NOT_EMPTY()),
            Field('field_two', 'string'))
        self.assertEqual(factory_form.xml()[:5], b'<form')

    #  def test_build_query(self):
    #     pass

    #  def test_search_menu(self):
    #     pass

    def test_grid(self):
        grid_form = SQLFORM.grid(self.db.auth_user)
        self.assertEqual(grid_form.xml()[:4], b'<div')

    def test_smartgrid(self):
        smartgrid_form = SQLFORM.smartgrid(self.db.auth_user)
        self.assertEqual(smartgrid_form.xml()[:4], b'<div')
Esempio n. 17
0
class TestAuth(unittest.TestCase):

    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt'), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.auth.get_or_create_user(dict(first_name='Bart',
                                          last_name='Simpson',
                                          username='******',
                                          email='*****@*****.**',
                                          password='******',
                                          registration_key='bart',
                                          registration_id=''
                                          ))
        # self.auth.settings.registration_requires_verification = False
        # self.auth.settings.registration_requires_approval = False

    def test_assert_setup(self):
        self.assertEqual(self.db(self.db.auth_user.username == 'bart').select().first()['username'], 'bart')
        self.assertTrue('auth_user' in self.db)
        self.assertTrue('auth_group' in self.db)
        self.assertTrue('auth_membership' in self.db)
        self.assertTrue('auth_permission' in self.db)
        self.assertTrue('auth_event' in self.db)

    def test_enable_record_versioning(self):
        self.assertTrue('t0_archive' in self.db)

    def test_basic_blank_forms(self):
        for f in ['login', 'retrieve_password',
                  'retrieve_username',
                  # 'register'  # register complain about : client_side=self.settings.client_side
                  ]:
            html_form = getattr(self.auth, f)().xml()
            self.assertTrue('name="_formkey"' in html_form)

        # NOTE: Not sure it is the proper way to logout_bare() as there is not methods for that and auth.logout() failed
        self.auth.logout_bare()
        # self.assertTrue(self.auth.is_logged_in())

        for f in ['logout', 'verify_email', 'reset_password',
                  'change_password', 'profile', 'groups']:
            self.assertRaisesRegexp(HTTP, "303*", getattr(self.auth, f))

        self.assertRaisesRegexp(HTTP, "401*", self.auth.impersonate)

        try:
            for t in ['t0_archive', 't0', 'auth_cas', 'auth_event',
                      'auth_membership', 'auth_permission', 'auth_group',
                      'auth_user']:
                self.db[t].drop()
        except SyntaxError as e:
            # GAE doesn't support drop
            pass
        return

    def test_get_or_create_user(self):
        self.db.auth_user.insert(email='*****@*****.**', username='******', password='******')
        self.db.commit()
        # True case
        self.assertEqual(self.auth.get_or_create_user({'email': '*****@*****.**',
                                                       'username': '******',
                                                       'password': '******'
                                                       })['username'], 'user1')
        # user2 doesn't exist yet and get created
        self.assertEqual(self.auth.get_or_create_user({'email': '*****@*****.**',
                                                       'username': '******'})['username'], 'user2')
        # user3 for corner case
        self.assertEqual(self.auth.get_or_create_user({'first_name': 'Omer',
                                                       'last_name': 'Simpson',
                                                       'email': '*****@*****.**',
                                                       'registration_id': 'user3',
                                                       'username': '******'})['username'], 'user3')
        # False case
        self.assertEqual(self.auth.get_or_create_user({'email': ''}), None)
        self.db.auth_user.truncate()
        self.db.commit()

    def test_login_bare(self):
        # The following test case should succeed but failed as I never received the user record but False
        self.auth.login_bare(username='******', password='******')
        self.assertTrue(self.auth.is_logged_in())
        # Failing login because bad_password
        self.assertEqual(self.auth.login_bare(username='******', password='******'), False)
        self.db.auth_user.truncate()

    def test_register_bare(self):
        # corner case empty register call register_bare without args
        self.assertRaises(ValueError, self.auth.register_bare)
        # failing register_bare user already exist
        self.assertEqual(self.auth.register_bare(username='******', password='******'), False)
        # successful register_bare
        self.assertEqual(self.auth.register_bare(username='******',
                                                 email='*****@*****.**',
                                                 password='******')['username'], 'user2')
        # raise ValueError
        self.assertRaises(ValueError, self.auth.register_bare,
                          **dict(wrong_field_name='user3', password='******'))
        # raise ValueError wrong email
        self.assertRaises(ValueError, self.auth.register_bare,
                          **dict(email='user4@', password='******'))
        self.db.auth_user.truncate()
        self.db.commit()

    def test_bulk_register(self):
        self.auth.login_bare(username='******', password='******')
        self.auth.settings.bulk_register_enabled = True
        bulk_register_form = self.auth.bulk_register(max_emails=10).xml()
        self.assertTrue('name="_formkey"' in bulk_register_form)

    def test_change_password(self):
        self.auth.login_bare(username='******', password='******')
        change_password_form = getattr(self.auth, 'change_password')().xml()
        self.assertTrue('name="_formkey"' in change_password_form)

    def test_profile(self):
        self.auth.login_bare(username='******', password='******')
        profile_form = getattr(self.auth, 'profile')().xml()
        self.assertTrue('name="_formkey"' in profile_form)
Esempio n. 18
0
db.define_table('auth_user',
                Field('username', type='string', label=T('Username')),
                Field('first_name', type='string', label=T('First Name')),
                Field('last_name', type='string', label=T('Last Name')),
                Field('email', type='string', label=T('Email')),
                Field('password',
                      type='password',
                      readable=False,
                      label=T('Password')),
                Field('created_on',
                      'datetime',
                      default=request.now,
                      label=T('Created On'),
                      writable=False,
                      readable=False),
                Field('modified_on',
                      'datetime',
                      default=request.now,
                      label=T('Modified On'),
                      writable=False,
                      readable=False,
                      update=request.now),
                Field('registration_key',
                      default='',
                      writable=False,
                      readable=False),
                Field('reset_password_key',
                      default='',
                      writable=False,
                      readable=False),
                Field('registration_id',
                      default='',
                      writable=False,
                      readable=False),
                format='%(username)s',
                migrate=settings.migrate)
Esempio n. 19
0
import random
from conf import *
from gluon.dal import DAL, Field

db = DAL(DB_URI)

db.define_table('person',
                Field('student_id', 'integer', notnull=True, unique=True),
                Field('last_name', 'string', notnull=True, required=True),
                Field('first_name', 'string', notnull=True, required=True),
                Field('home_phone', 'string'),
                Field('cell_phone', 'string'),
                Field('cell_provider', 'string'),
                Field('gender', 'string'),
                Field('email', 'string'),
                Field('street', 'string'),
                Field('city', 'string'),
                Field('state', 'string'),
                Field('zip_code', 'string'),
                Field('notes', 'string'),
                Field('pic', 'blob'),
                Field('crew', 'integer', default=None, ondelete='SET NULL'),
                Field('grade', 'integer'),
                Field('leader', 'boolean', default=False),
                migrate=False)

db.define_table('teacher',
                Field('teacher_id', 'integer', notnull=True, unique=True),
                Field('teacher_name', 'string', notnull=True),
                migrate=False)