Esempio n. 1
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. 2
0
 def test_DALcache(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. 3
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. 4
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. 5
0
class TestSetup(unittest.TestCase):
	"""docstring for TestSetUp"""

	def setUp(self):

		#self.driver = webdriver.Firefox()
		self.driver = webdriver.Remote(command_executor='http://0.0.0.0:4444/wd/hub',
						desired_capabilities=DesiredCapabilities.FIREFOX)

		self.submit_button = "//input[@value='Submit']"

		db_username_postgres = 'postgres'
		db_password_postgres = '1234'
		db_postgres_url = 'postgres://' + db_username_postgres + ':' + db_password_postgres + '@localhost/dev'

		path_to_database = path.join(path.curdir, "../databases")
		self.db_test = DAL(db_postgres_url, folder=path_to_database)
		self.db_test.import_table_definitions(path_to_database)

	def tearDown(self):
		self.driver.quit()

	def submit_form(self):
		self.driver.find_element_by_xpath(self.submit_button).click()	

	def limpa_dados_tabela(self, nome_tabela):
		self.db_test.executesql('delete from ' + nome_tabela)
		self.db_test.commit()		
Esempio n. 6
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. 7
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. 8
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. 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(), b'<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 TestAuthAPI(unittest.TestCase):

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

    def test_login(self):
        result = self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.auth.logout()
        self.assertFalse(self.auth.is_logged_in())
        self.auth.settings.username_case_sensitive = False
        result = self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())

    def test_logout(self):
        self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())
        result = self.auth.logout()
        self.assertTrue(not self.auth.is_logged_in())
        self.assertTrue(result['user'] is None)

    def test_register(self):
        self.auth.settings.login_after_registration = True
        result = self.auth.register(**{
            'username': '******',
            'first_name': 'Lisa',
            'last_name': 'Simpson',
            'email': '*****@*****.**',
            'password': '******'
        })
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.assertTrue(self.auth.is_logged_in())
        with self.assertRaises(AssertionError):  # Can't register if you're logged in
            result = self.auth.register(**{
                'username': '******',
                'first_name': 'Lisa',
                'last_name': 'Simpson',
                'email': '*****@*****.**',
                'password': '******'
            })
        self.auth.logout()
        self.auth.settings.login_after_registration = False
        result = self.auth.register(**{
            'username': '******',
            'first_name': 'Barney',
            'last_name': 'Gumble',
            'email': '*****@*****.**',
            'password': '******'
        })
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.assertFalse(self.auth.is_logged_in())
        self.auth.settings.login_userfield = 'email'
        result = self.auth.register(**{
            'username': '******',
            'first_name': 'Lisa',
            'last_name': 'Simpson',
            'email': '*****@*****.**',
            'password': '******'
        })
        self.assertTrue(result['errors']['email'] == self.auth.messages.email_taken)
        self.assertTrue(result['user'] is None)
        self.auth.settings.registration_requires_verification = True
        result = self.auth.register(**{
            'username': '******',
            'first_name': 'Homer',
            'last_name': 'Simpson',
            'email': '*****@*****.**',
            'password': '******'
        })
        self.assertTrue('key' in result['user'])

    def test_profile(self):
        with self.assertRaises(AssertionError):
            # We are not logged in
            self.auth.profile()
        self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())
        result = self.auth.profile(email='*****@*****.**')
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.assertTrue(self.auth.table_user()[result['user']['id']].email == '*****@*****.**')

    def test_change_password(self):
        with self.assertRaises(AssertionError):
            # We are not logged in
            self.auth.change_password()
        self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())
        self.auth.change_password(old_password='******', new_password='******', new_password2='1234')
        self.auth.logout()
        self.assertTrue(not self.auth.is_logged_in())
        self.auth.login(username='******', password='******')
        self.assertTrue(self.auth.is_logged_in())
        result = self.auth.change_password(old_password='******', new_password='******', new_password2='5678')
        self.assertTrue('new_password2' in result['errors'])
        result = self.auth.change_password(old_password='******', new_password='******', new_password2='1234')
        self.assertTrue('old_password' in result['errors'])

    def test_verify_key(self):
        self.auth.settings.registration_requires_verification = True
        result = self.auth.register(**{
            'username': '******',
            'first_name': 'Homer',
            'last_name': 'Simpson',
            'email': '*****@*****.**',
            'password': '******'
        })
        self.assertTrue('key' in result['user'])
        homer_id = result['user']['id']
        homers_key = result['user']['key']
        result = self.auth.verify_key(key=None)
        self.assertTrue(result['errors'] is not None)
        result = self.auth.verify_key(key='12345')
        self.assertTrue(result['errors'] is not None)
        result = self.auth.verify_key(key=homers_key)
        self.assertTrue(result['errors'] is None)
        self.assertEqual(self.auth.table_user()[homer_id].registration_key, '')
        self.auth.settings.registration_requires_approval = True
        result = self.auth.register(**{
            'username': '******',
            'first_name': 'Lisa',
            'last_name': 'Simpson',
            'email': '*****@*****.**',
            'password': '******'
        })
        lisa_id = result['user']['id']
        result = self.auth.verify_key(key=result['user']['key'])
        self.assertEqual(self.auth.table_user()[lisa_id].registration_key, 'pending')
Esempio n. 11
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. 12
0
class PlacesTableImporter(TableImporter.TableImporter):
    """ Imports metadata related to places"""

    def __init__(self, settings):
        super(PlacesTableImporter, self).__init__(settings)
        self.db_type = self.config.get('db', 'db_type')
        self.db_folder = self.config.get('db', 'db_folder')
        self.db_file = self.config.get('db', 'db_file')
        self.web2py_loc = self.config.get('db', 'web2py_loc')
        print(self.db_type)
        print(self.db_folder)
        print(self.db_file)
        print(self.web2py_loc)
        # Add DAL to path
        sys.path.append(self.web2py_loc)
        # import required objects
        from gluon.dal import DAL
        # establish a database connection
        self.db = DAL(self.db_type + '://' + self.db_file,
                      folder=self.db_folder)

    def create_table(self):
        from gluon.dal import Field
        self.db.define_table('places',
                             Field('placeID', 'integer'),
                             Field('countryID', 'integer', default=0),
                             Field('stateID', 'integer', default=0),
                             Field('districtID', 'integer', default=0),
                             Field('localityID', 'integer', default=0),
                             Field('name', 'string'))

    def populate_table(self):
        print(self.db.places.insert(placeID=1, countryID=1, stateID=2,
                                    districtID=3, localityID=4,
                                    name='Pune'))
        print(self.db.places.insert(placeID=2, countryID=11, stateID=12,
                                    districtID=3, localityID=4,
                                    name='Hyderabad'))
        print(self.db.places.insert(placeID=3, countryID=21, stateID=42,
                                    districtID=53, localityID=64,
                                    name='Mumbai'))
        print(self.db.places.insert(placeID=4, countryID=1, stateID=22,
                                    districtID=23, localityID=41,
                                    name='Junagad'))
        print(self.db.places.insert(placeID=5, countryID=111, stateID=2,
                                    districtID=3, localityID=49,
                                    name='Lohagad'))
        print(self.db.places.insert(placeID=6, countryID=18, stateID=42,
                                    districtID=13, localityID=4,
                                    name='Raipur'))
        print(self.db.places.insert(placeID=7, countryID=14, stateID=24,
                                    districtID=3, localityID=444,
                                    name='Rampur'))
        print(self.db.places.insert(placeID=8, countryID=1, stateID=2,
                                    districtID=3,
                                    name='Nagpur'))
        print(self.db.places.insert(placeID=9, countryID=1, stateID=2,
                                    name='Maharashtra'))
        print(self.db.places.insert(placeID=10, countryID=1,
                                    name='India'))

    def __del__(self):
        if self.db:
            self.db.commit()
            self.db.close()
            self.db = None
            gc.collect()
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 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_factory_applies_default_validators(self):
        from gluon import current

        factory_form = SQLFORM.factory(
            Field('a_date', type='date'),
        )
        # Fake user input
        current.request.post_vars.update({
            '_formname': 'no_table/create',
            'a_date': '2018-09-14',
            '_formkey': '123',

        })
        # Fake the formkey
        current.session['_formkey[no_table/create]'] = ['123']

        self.assertTrue(factory_form.process().accepted)
        self.assertIsInstance(factory_form.vars.a_date, datetime.date)

    #  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. 15
0
class DBContext:
    """ context for the database on web2py 

    stores all the state about currently defined tables, etc.
    passed to all accesssors when created, this is the link for common db code
    """
    USER_TABLE = "users"
    COURSE_TABLE = "courses"
    ENROLLMENT_TABLE = "enrollments"
    NOTE_TABLE = "notes"

    def __init__(self, db_file, migrate_lambda=None):
        """ constructor.
        params:
            db_file - name of the file to put the database in
            migrate_lambda - lambda which accepts table name, returns filename to store migrate in
               default migrate lambda returns true all the time
        """
        self.db_file = db_file
        if migrate_lambda:
            self.migrate = migrate_lambda
        else:
            self.migrate = lambda table: True

        self.db = DAL("sqlite://%s" % self.db_file)
        
        # this is the default username table for the web2py auth module
        # I will define it explicitly here so we can make changes to it.
        # We can add fields to this no problems, however, the built-in auth module requires these fields at a minimum
        self.db.define_table(
            self.USER_TABLE,
            Field('first_name', length=128, default='', requires=IS_NOT_EMPTY()),
            Field('last_name', length=128, default='', requires=IS_NOT_EMPTY()),
            Field('username', length=32, default='', unique=True, requires=IS_NOT_EMPTY()),
            Field('email', length=128, default='', unique=True),
            Field('password', 'password', length=512, readable=False, label='Password', requires=[CRYPT()]), # IS_STRONG()?
            Field('role', 'integer', writable=False, default=User.MIN_ROLE, requires=IS_INT_IN_RANGE(User.MIN_ROLE, User.MAX_ROLE + 1)),

            # these fields are unused, but kept for compatibility with web2py
            Field('registration_key', length=512, writable=False, readable=False, default=''),
            Field('reset_password_key', length=512, writable=False, readable=False, default=''),
            Field('registration_id', length=512, writable=False, readable=False, default=''),
            # end unused fields

            migrate=self.migrate(self.USER_TABLE)
        )
        user_table = self.db[self.USER_TABLE]
        user_table.email.requires =[IS_EMAIL(), IS_NOT_IN_DB(self.db, user_table.email)]

        self.db.define_table(self.COURSE_TABLE,
            Field('department', 'string', requires=IS_NOT_EMPTY()),
            Field('number', 'integer', requires=IS_NOT_EMPTY()),
            Field('section', 'string', requires=IS_NOT_EMPTY()),
            Field('instructor', 'string', requires=IS_NOT_EMPTY()),
            migrate=self.migrate(self.COURSE_TABLE)
        )
        
        self.db.define_table(self.ENROLLMENT_TABLE,
            Field('user_id', self.db.users, requires=IS_NOT_EMPTY()),
            Field('course_id', self.db.courses, requires=IS_NOT_EMPTY()),
            migrate=self.migrate(self.ENROLLMENT_TABLE)
        )

        self.db.define_table(self.NOTE_TABLE,
            Field('start_date', 'date', requires=[IS_NOT_EMPTY(),IS_DATE()]),
            Field('end_date', 'date', requires=[IS_NOT_EMPTY(),IS_DATE()]),
            Field(self.NOTE_TABLE, 'upload', autodelete=True, requires=IS_NOT_EMPTY()), # must do autodelete to avoid polluting the db with old files
            Field('course_id', self.db.courses, requires=IS_NOT_EMPTY()), # foreign key relationship
            Field('created_by', self.db.users, 'integer'), # eventually make this a foreign key on user table
            Field('modified_by', self.db.users, 'integer'), # ditto
            Field('created_on', 'datetime'),
            Field('modified_on', 'datetime'),
            migrate=self.migrate(self.NOTE_TABLE)
        )

    def close(self):
        """ using internal reference to db adapter, but its the only way to close... """
        self.db.commit()
        self.db._adapter.close()
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
    Field('PrecioKg', 'double', default=0, label='Precio Kg.'),
)

totalSalida = db.LineaSalida.Unidades.sum()

db.CabeceraSalida.Total = Field.Virtual(lambda row:
                                        db(db.LineaSalida.cabecera
                                           == row.CabeceraSalida.id).select(totalSalida).first()[totalSalida])


# Inizializaciones para la primera vez que se ejecute la aplicación:
# IMPORTANTE: POR SEGURIDAD UNA VEZ QUE SE ENTRE EN LA APLICACIÓN HAY QUE
# CAMBIAR LA CONTRASEÑA DEL USUARIO [email protected], que inicialmente es
# password_malo

db.commit()
if "comprobado" not in session.keys() and not is_running_under_test:

    session.comprobado = True
    # initialize admin user and roles group:
    useradmin = db(db.auth_user.id == 1).select()
    if len(useradmin) == 0:
        db.Sede.insert(name="Sede de pruebas")
        db.Almacen.insert(name="AlmacenTest")
        my_crypt = CRYPT(key=auth.settings.hmac_key)
        crypted_passwd = my_crypt('password_malo')[0]
        db.commit()
        # k = db.auth_user.insert(email='*****@*****.**', first_name='Administrator',
        #                         password=crypted_passwd, almacen=1)
        k = db.auth_user.insert(email='*****@*****.**', first_name='Administrator',
                                password=crypted_passwd)
Esempio n. 19
0
class TestAuthAPI(unittest.TestCase):
    def setUp(self):
        self.request = Request(env={})
        self.request.application = 'a'
        self.request.controller = 'c'
        self.request.function = 'f'
        self.request.folder = 'applications/admin'
        self.response = Response()
        self.session = Session()
        T = translator('', 'en')
        self.session.connect(self.request, self.response)
        from gluon.globals import current
        self.current = current
        self.current.request = self.request
        self.current.response = self.response
        self.current.session = self.session
        self.current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = AuthAPI(self.db)
        self.auth.define_tables(username=True, signature=False)
        # Create a user
        self.auth.table_user().validate_and_insert(first_name='Bart',
                                                   last_name='Simpson',
                                                   username='******',
                                                   email='*****@*****.**',
                                                   password='******',
                                                   registration_key='',
                                                   registration_id='')
        self.db.commit()

    def test_login(self):
        result = self.auth.login(**{
            'username': '******',
            'password': '******'
        })
        self.assertTrue(self.auth.is_logged_in())
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.auth.logout()
        self.assertFalse(self.auth.is_logged_in())
        self.auth.settings.username_case_sensitive = False
        result = self.auth.login(**{
            'username': '******',
            'password': '******'
        })
        self.assertTrue(self.auth.is_logged_in())

    def test_logout(self):
        self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())
        result = self.auth.logout()
        self.assertTrue(not self.auth.is_logged_in())
        self.assertTrue(result['user'] is None)

    def test_register(self):
        self.auth.settings.login_after_registration = True
        result = self.auth.register(
            **{
                'username': '******',
                'first_name': 'Lisa',
                'last_name': 'Simpson',
                'email': '*****@*****.**',
                'password': '******'
            })
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.assertTrue(self.auth.is_logged_in())
        with self.assertRaises(
                AssertionError):  # Can't register if you're logged in
            result = self.auth.register(
                **{
                    'username': '******',
                    'first_name': 'Lisa',
                    'last_name': 'Simpson',
                    'email': '*****@*****.**',
                    'password': '******'
                })
        self.auth.logout()
        self.auth.settings.login_after_registration = False
        result = self.auth.register(
            **{
                'username': '******',
                'first_name': 'Barney',
                'last_name': 'Gumble',
                'email': '*****@*****.**',
                'password': '******'
            })
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.assertFalse(self.auth.is_logged_in())
        self.auth.settings.login_userfield = 'email'
        result = self.auth.register(
            **{
                'username': '******',
                'first_name': 'Lisa',
                'last_name': 'Simpson',
                'email': '*****@*****.**',
                'password': '******'
            })
        self.assertTrue(
            result['errors']['email'] == self.auth.messages.email_taken)
        self.assertTrue(result['user'] is None)
        self.auth.settings.registration_requires_verification = True
        result = self.auth.register(
            **{
                'username': '******',
                'first_name': 'Homer',
                'last_name': 'Simpson',
                'email': '*****@*****.**',
                'password': '******'
            })
        self.assertTrue('key' in result['user'])

    def test_profile(self):
        with self.assertRaises(AssertionError):
            # We are not logged in
            self.auth.profile()
        self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())
        result = self.auth.profile(email='*****@*****.**')
        self.assertTrue(result['user']['email'] == '*****@*****.**')
        self.assertTrue(self.auth.table_user()[result['user']['id']].email ==
                        '*****@*****.**')

    def test_change_password(self):
        with self.assertRaises(AssertionError):
            # We are not logged in
            self.auth.change_password()
        self.auth.login(**{'username': '******', 'password': '******'})
        self.assertTrue(self.auth.is_logged_in())
        self.auth.change_password(old_password='******',
                                  new_password='******',
                                  new_password2='1234')
        self.auth.logout()
        self.assertTrue(not self.auth.is_logged_in())
        self.auth.login(username='******', password='******')
        self.assertTrue(self.auth.is_logged_in())
        result = self.auth.change_password(old_password='******',
                                           new_password='******',
                                           new_password2='5678')
        self.assertTrue('new_password2' in result['errors'])
        result = self.auth.change_password(old_password='******',
                                           new_password='******',
                                           new_password2='1234')
        self.assertTrue('old_password' in result['errors'])
        # Test the default 4 min_length is enforced on change password
        result = self.auth.change_password(old_password='******',
                                           new_password='******',
                                           new_password2='123')
        self.assertTrue('new_password' in result['errors'])

    def test_verify_key(self):
        self.auth.settings.registration_requires_verification = True
        result = self.auth.register(
            **{
                'username': '******',
                'first_name': 'Homer',
                'last_name': 'Simpson',
                'email': '*****@*****.**',
                'password': '******'
            })
        self.assertTrue('key' in result['user'])
        homer_id = result['user']['id']
        homers_key = result['user']['key']
        result = self.auth.verify_key(key=None)
        self.assertTrue(result['errors'] is not None)
        result = self.auth.verify_key(key='12345')
        self.assertTrue(result['errors'] is not None)
        result = self.auth.verify_key(key=homers_key)
        self.assertTrue(result['errors'] is None)
        self.assertEqual(self.auth.table_user()[homer_id].registration_key, '')
        self.auth.settings.registration_requires_approval = True
        result = self.auth.register(
            **{
                'username': '******',
                'first_name': 'Lisa',
                'last_name': 'Simpson',
                'email': '*****@*****.**',
                'password': '******'
            })
        lisa_id = result['user']['id']
        result = self.auth.verify_key(key=result['user']['key'])
        self.assertEqual(self.auth.table_user()[lisa_id].registration_key,
                         'pending')
Esempio n. 20
0
class DocDB(object):
    """Creates instances of DocDB. Each instance will have a db connection.

    Extracted from web2py docs:
    ---------------------------
    Here are examples of connection strings for specific types of supported back-end databases
    (in all cases, we assume the database is running from localhost on its default port and is named "test"):

    SQLite	sqlite://storage.db
    MySQL	mysql://username:password@localhost/test
    PostgreSQL	postgres://username:password@localhost/test
    MSSQL	mssql://username:password@localhost/test
    FireBird	firebird://username:password@localhost/test
    Oracle	oracle://username/password@test
    DB2	db2://username:password@test
    Ingres	ingres://username:password@localhost/test
    Informix	informix://username:password@test
    Google App Engine/SQL	google:sql
    Google App Engine/NoSQL	google:datastore

    Notice that in SQLite the database consists of a single file. If it does not exist, it is created.
    This file is locked every time it is accessed. In the case of MySQL, PostgreSQL, MSSQL, FireBird,
    Oracle, DB2, Ingres and Informix the database "test" MUST exist.

    """

    def __init__(self, conn='sqlite://temp.db', pool_size=0, migrate=True):
        """
        Generates a connection with the given DB.
        @connection: system path to the sqlite file to use or DB connection string. If None given,
        a default temp.db file will be created.
        """
        if '://' not in conn:
            print """Connection string needed!\n \
                  Some examples:\n \
                  SQLite  sqlite://storage.db
                  MySQL   mysql://username:password@localhost/test \
                  PostgreSQL  postgres://username:password@localhost/test
            """
            sys.exit(2)
        self._conn = conn
        self._db = DAL(conn, folder=PATH, pool_size=pool_size)
        self._db.define_table('documents',
                   Field('key'),
                   Field('data', 'text'),
                   Field('valid', 'boolean'),
                   migrate = migrate)

        if not self._db(self._db.documents).count():
            try:
                self._db.executesql('CREATE INDEX keyx ON documents (key)') #CREATE INDEX IF NOT EXISTS
            except Exception:
                self._db.rollback()

    def get(self, key):
        """
        Searches and returns the doc for a given key.
        """
        db = self._db
        doc = db((db.documents.key==key) & (db.documents.valid==True)).select(db.documents.data).first()
        if doc:
            return json.loads(doc['data'])
        return None

    def set(self, key, doc):
        """
        Inserts a document (doc) into the DB.
        @doc: can be of any python data structure (string, number, dict, list, ...
        """
        db = self._db
        data = json.dumps(doc)
        db((db.documents.key==key) & (db.documents.valid==True)).update(valid=False)
        db.documents.insert(key=key, data=data, valid=True)
        db.commit()
        return True

    def mset(self, docs):
        """
        Inserts a set of documents into the DB.
        Example:
            >>> l = [('key1', {'key': 'value'}), ('key2', {'key': 'value'}), ('key3', {'key': 'value'})]
            >>> db.mset(*l)
        """
        db = self._db
        counter = 0
        for doc in docs:
            key, data = doc
            data = json.dumps(data)
            db((db.documents.key==key) & (db.documents.valid==True)).update(valid=False)
            db.documents.insert(key=key, data=data, valid=True)
            counter += 1
            if counter > 1000:
                db.commit()
                counter = 0
        db.commit()
        return True

    def versions(self, key):
        """
        Lists all the documents related to a key.
        """
        db = self._db
        results = []
        for doc in db(db.documents.key == key).select():
            id, data, valid = doc['id'], json.loads(doc['data']), doc['valid']
            results.append((id, data, valid))
        return results

    def revert(self, key, version):
        """
        Reverts to a previous version of the document.
        """
        db = self._db
        vers = self.versions(key)
        for doc in vers:
            id, data, valid = doc
            if id == version:
                db((db.documents.key==key) & (db.documents.valid==True)).update(valid=False)
                db(db.documents.id==id).update(valid=True)
                db.commit()
                return True
        return False

    def info(self):
        """
        Returns a dict with info about the current DB (including db filesize, number of keys, etc.).
        """
        dbsize = -1
        db = self._db
        if "postgres" in self._conn:
            dbsize = db.executesql("SELECT pg_size_pretty(pg_database_size('%s'));" % self.dbname)[0][0]
        num_keys = db(db.documents.valid==True).count()
        return dict(keys=num_keys, dbsize=dbsize)

    def keys(self):
        """
        Returns a list of ALL the keys in the current DB.
        """
        db = self._db
        return [doc['key'] for doc in db(db.documents.valid==True).select(db.documents.key)]

    def flushall(self):
        """
        Deletes ALL the content from the DB.
        TODO: Use truncate.
        """
        self._db.documents.truncate()
        self._db.commit()
        #self.__init__()
        return True

    def compact(self, key=None):
        """
        Deletes ALL the versions for a given document or the entire DB.
        """
        db = self._db
        if key:
            db((db.documents.key==key) & (db.documents.valid==False)).delete()
        else:
            db(db.documents.valid==False).delete()
        db.commit()
        return True

    def __contains__(self, item):
        if self.get(item): return True
        return False

    def __getitem__(self, item):
        return self.get(item)

    def __setitem__(self, key, doc):
        return self.set(key, doc)

    def __delitem__(self, key):
        self._db.execute('UPDATE document SET valid == 0 WHERE key == ?', (key,))
        self._db.commit()
        return True
Esempio n. 21
0
def main_0():
    migrate=True

    db = DAL('postgres://*****:*****@localhost/Lean',pool_size=5,check_reserved=['postgres'], folder=None, bigint_id=True
              ) #fake_migrate_all=True migrate_enabled=True
    db.executesql('SET search_path TO public, admins, model_gen, history, tasks, trac;')
    db.define_table('person',
                Field('id',
                      type = 'id',
                      required = True,
                ),
                Field('name',
                      type = 'string',
                      required = True,
                ),
                Field('surname',
                      type = 'string',
                      required = True,
                ),
                Field('patroname',
                      type = 'string',
                      required = True,
                ),
                Field('is_hidden',
                      type = 'boolean',
                      default = False,
                      required = True,
                ),
                migrate=False
    )



    band_type = Enum(db, 'band_type', code_field=True, migrate=False)
    div_type = Enum(db, 'division_type', code_field=True, migrate=False)
    div_fntype = Enum(db, 'division_fntype', code_field=True, migrate=False)


    def_PG_table(db, 'band',
                Field('name'),
                ref_field(band_type, nocache=True),
                alt_key=['name', band_type.FK_name],
                migrate=False)

    def_PG_table(db, 'a_comp',
                Field('id', 'reference a_bands'),
                Field('comp_name'),
                primarykey=['id'],
                migrate=False)

    def_PG_table(db, 'a_dept',
                Field('id', 'reference a_bands'),
                Field('dept_name'),
                primarykey=['id'],
                migrate=False)


    def_PG_table(db, 'a_men',
                Field('name'),
                migrate=False)


    Entity.init_cls(db)
    band_ent = Entity(db.a_bands, D_field=band_type.FK_name, tracking=True)
    comp_ent = Entity(db.a_comp, parent = band_ent, D_value=1)
    dept_ent = Entity(db.a_dept, parent = band_ent, D_value=2)
    men_ent= Entity(db.a_men )




    band_ent.def_option('region',Field('name'))
    band_ent.def_option('brunch', Field('id'), Field('name'))
    """
    dept_ent.update(10, dept_name='вапвап', **{'region.name':'dept_ert',
                        'brunch.*':[
                                    {'id':14, 'name':''},
                                    ]


    })
    dept_ent.insert(dept_name='вапвап new', **{'region.name':'dept_ert_new',
                        'brunch.*':[
                                    {'id':14, 'name':'new34'},
                                    ]}
                                    )


    comp_ent.insert(name='prnt_name_cmp8', comp_name='comp_name_8',
                    **{'brunch.*':[
                                    {'name':'brunch_name6'},
                                    {'name':'brunch_name7'}
                                    ]
                      }
                    )
    """
    band_ent.create_all_views(migrate=True)
    comp_ent.create_all_views(migrate=True)
    dept_ent.create_all_views(migrate=True)

    men_ent.def_option('age', Field('age', 'integer'))
    men_ent.create_all_views(migrate=True)

    #men_ent.insert(name='Петя fg', **{'age.age':20} )
    band_ent.def_history()
    band_ent._write_history(1)


    band_men = Relation([db.a_bands, db.a_men], Field('men_role'), alt_key=['a_bands_id', 'a_men_id'])
    #band_men.insert(a_bands_id=1, a_men_id=1)
    #band_men.insert(a_bands_id=1, a_men_id=2 )
    #band_men.insert(a_bands_id=2, a_men_id=2 )



    r= band_men._select(None, db.a_men_vw_agg.id, json_agg_sql([db.a_men_vw_agg.name, db.a_bands_vw_agg.name], as_alias='ff'),
                    groupby=[db.a_men_vw_agg.id] )





    #band_ent.create_view( migrate=True )
    #dept_ent.insert(name='prnt_dpt_name', dept_name='dept_name')





    #enm_c=Enum(db, 'atstc_type', code_field=True, migrate=True)
    #enm_clr=Enum(db, 'aclr_type', code_field=True, migrate=True)
    #enm_clr.own.insert(id=1, name='Red', code='#red')
    #enm_clr.own.insert(id=2, name='Blue', code='#bl')
    #enm_clr.own.insert(id=3, name='Green', code='#gr')

    """
    db.define_table('a_entst',
                Field('name'),
                ref_field(enm_clr, nocache=True),
                migrate=True)


    ent= Entity(db.a_entst)
    ent.def_option('opt', Field('color'),  Field('shape') , migrate=True)
    ent.def_option('plan', Field('start', 'date'),  Field('finish', 'date') , migrate=True)
    ent.def_option('opt_lst', Field('id'), Field('this'),  Field('that') , migrate=True)
    #db.plan._entopt.vw_pref='pln'
    #db.plan.start._entopt=Storage(vw_name='start_')
    ent.create_view( migrate=True )
    ent.create_view_json( migrate=True)
    ent.create_view_agg(migrate=True)

    r = ent.update_many(db.a_entst._id<5, del_insert = True,
                    **{
                            'clr':2,
                            'opt.color':None,
                            'opt.shape':'',
                            'opt_lst.*': [dict(id=30, this='', that=''), dict(id=30, this='df0', that='that30')]

                    })

    #ent.update(7, **{'name':'Val', 'opt_lst.*': [dict(id=2 , this='', that='')
    #                                              ]})
    #ent.insert(**{'opt.color':'red'})
    """

    db.commit()


    rows = db().select(comp_ent.view_join_parent.ALL)
    print rows.as_list()
    #db.person._entopt=Storage(vw_pref='prsn')
    #db.person.name._entopt=Storage(vw_name='name')
    #g=Entity._vw_opt_fld_name(db.person.surname)

    pass