Commits

Marcin Kuzminski committed fefffd6

Added some more tests, rewrite testing schema, to autogenerate fresh db, new index.
cleaned up some codes that involves testing.

  • Participants
  • Parent commits 74b9bed
  • Branches celery

Comments (0)

Files changed (7)

File pylons_app/config/environment.py

     config['pylons.strict_tmpl_context'] = True
     test = os.path.split(config['__file__'])[-1] == 'test.ini'
     if test:
-        from pylons_app.lib.utils import make_test_env
-        make_test_env()
+        from pylons_app.lib.utils import create_test_env, create_test_index
+        create_test_env('/tmp', config)
+        create_test_index('/tmp/*', True)
+        
     #MULTIPLE DB configs
     # Setup the SQLAlchemy database engine
     if config['debug'] and not test:

File pylons_app/lib/db_manage.py

 log = logging.getLogger(__name__)
 
 class DbManage(object):
-    def __init__(self, log_sql, dbname,tests=False):
+    def __init__(self, log_sql, dbname, tests=False):
         self.dbname = dbname
         self.tests = tests
         dburi = 'sqlite:////%s' % jn(ROOT, self.dbname)
         if override:
             log.info("database exisist and it's going to be destroyed")
             if self.tests:
-                destroy=True
+                destroy = True
             else:
                 destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
             if not destroy:
             import getpass
             username = raw_input('Specify admin username:')
             password = getpass.getpass('Specify admin password:')
-            self.create_user(username, password, True)
+            email = raw_input('Specify admin email:')
+            self.create_user(username, password, email, True)
         else:
             log.info('creating admin and regular test users')
-            self.create_user('test_admin', 'test', True)
-            self.create_user('test_regular', 'test', False)
+            self.create_user('test_admin', 'test', 'test_admin@mail.com', True)
+            self.create_user('test_regular', 'test', 'test_regular@mail.com', False)
+            self.create_user('test_regular2', 'test', 'test_regular2@mail.com', False)
             
         
     
-    def config_prompt(self,test_repo_path=''):
+    def config_prompt(self, test_repo_path=''):
         log.info('Setting up repositories config')
         
         if not self.tests and not test_repo_path:
             path = test_repo_path
             
         if not os.path.isdir(path):
-            log.error('You entered wrong path: %s',path)
+            log.error('You entered wrong path: %s', path)
             sys.exit()
         
         hooks1 = HgAppUi()
             raise        
         log.info('created ui config')
                     
-    def create_user(self, username, password, admin=False):
+    def create_user(self, username, password, email='', admin=False):
         log.info('creating administrator user %s', username)
         new_user = User()
         new_user.username = username
         new_user.password = get_crypt_password(password)
         new_user.name = 'Hg'
         new_user.lastname = 'Admin'
-        new_user.email = 'admin@localhost.com'
+        new_user.email = email
         new_user.admin = admin
         new_user.active = True
         

File pylons_app/lib/indexers/daemon.py

 log = logging.getLogger('whooshIndexer')
 # create logger
 log.setLevel(logging.DEBUG)
-
+log.propagate = False
 # create console handler and set level to debug
 ch = logging.StreamHandler()
 ch.setLevel(logging.DEBUG)

File pylons_app/lib/utils.py

 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 # MA  02110-1301, USA.
-import shutil
 
 """
 Created on April 18, 2010
 from vcs.utils.lazy import LazyProperty
 import logging
 import os
-from os.path import dirname as dn, join as jn
-import tarfile
+
 log = logging.getLogger(__name__)
 
 
     def __ne__(self, other):
         return not self == other
 
-def make_test_env():
-    """Makes a fresh database from base64+zlib dump and 
+
+#===============================================================================
+# TEST FUNCTIONS
+#===============================================================================
+def create_test_index(repo_location, full_index):
+    """Makes default test index
+    @param repo_location:
+    @param full_index:
+    """
+    from pylons_app.lib.indexers import daemon
+    from pylons_app.lib.indexers.daemon import WhooshIndexingDaemon
+    from pylons_app.lib.indexers.pidlock import DaemonLock, LockHeld
+    from pylons_app.lib.indexers import IDX_LOCATION
+    import shutil
+    
+    if os.path.exists(IDX_LOCATION):
+        shutil.rmtree(IDX_LOCATION)
+         
+    try:
+        l = DaemonLock()
+        WhooshIndexingDaemon(repo_location=repo_location)\
+            .run(full_index=full_index)
+        l.release()
+    except LockHeld:
+        pass    
+    
+def create_test_env(repos_test_path, config):
+    """Makes a fresh database and 
     install test repository into tmp dir
     """
-    new_db_dump = """
-eJztXN1vE8sVn9nxR+wAIXDpFiiXjSAXfEOc2ElwQkVLPjYf5NNOAklUydrYG3tv1t5ldx0nuUJV\noL
-cPrVr1X7jSfUJ96nMfK1Xty23VqlWlPlRIlahUXbXqF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ot2zRsdnLgLCYYip/b7w5jKqUX51IREv4F/FJ7YBy96ja963sJS\n34yd
-OXDGKEud/R8efZUt\n
-"""    
-    newdb = open('test.db', 'wb')
-    newdb.write(new_db_dump.decode('base64').decode('zlib'))
-    newdb.close()
+    from pylons_app.lib.db_manage import DbManage
+    import tarfile
+    import shutil
+    from os.path import dirname as dn, join as jn, abspath
     
+    log = logging.getLogger('TestEnvCreator')
+    # create logger
+    log.setLevel(logging.DEBUG)
+    log.propagate = True
+    # create console handler and set level to debug
+    ch = logging.StreamHandler()
+    ch.setLevel(logging.DEBUG)
+    
+    # create formatter
+    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
+    
+    # add formatter to ch
+    ch.setFormatter(formatter)
+    
+    # add ch to logger
+    log.addHandler(ch)
+    
+    #PART ONE create db
+    log.debug('making test db')
+    dbname = config['sqlalchemy.db1.url'].split('/')[-1]
+    dbmanage = DbManage(log_sql=True, dbname=dbname, tests=True)
+    dbmanage.create_tables(override=True)
+    dbmanage.config_prompt(repos_test_path)
+    dbmanage.create_default_user()
+    dbmanage.admin_prompt()
+    dbmanage.create_permissions()
+    dbmanage.populate_default_permissions()
     
     #PART TWO make test repo
+    log.debug('making test vcs repo')
     if os.path.isdir('/tmp/vcs_test'):
         shutil.rmtree('/tmp/vcs_test')
         
-    cur_dir = dn(dn(os.path.abspath(__file__)))
+    cur_dir = dn(dn(abspath(__file__)))
     tar = tarfile.open(jn(cur_dir, 'tests', "vcs_test.tar.gz"))
     tar.extractall('/tmp')
     tar.close()
-    
-    
-    

File pylons_app/tests/__init__.py

 from webtest import TestApp
 import os
 from pylons_app.model import meta
-from pylons_app.lib.indexers import IDX_LOCATION
 import logging
-import shutil
+
+
 log = logging.getLogger(__name__) 
 
 import pylons.test
 __all__ = ['environ', 'url', 'TestController']
 
 # Invoke websetup with the current config file
-#SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])
-def create_index(repo_location, full_index):
-    from pylons_app.lib.indexers import daemon
-    from pylons_app.lib.indexers.daemon import WhooshIndexingDaemon
-    from pylons_app.lib.indexers.pidlock import DaemonLock, LockHeld
-    
-    try:
-        l = DaemonLock()
-        WhooshIndexingDaemon(repo_location=repo_location)\
-            .run(full_index=full_index)
-        l.release()
-    except LockHeld:
-        pass    
-    
-if os.path.exists(IDX_LOCATION):
-    shutil.rmtree(IDX_LOCATION)
-    
-create_index('/tmp/*', True)    
+#SetupCommand('setup-app').run([config_file])
+
 
 environ = {}
 
         self.sa = meta.Session
 
         TestCase.__init__(self, *args, **kwargs)
-
     
-    def log_user(self):
+    def log_user(self, username='test_admin', password='test'):
         response = self.app.post(url(controller='login', action='index'),
-                                 {'username':'test_admin',
-                                  'password':'test'})
+                                 {'username':username,
+                                  'password':password})
         assert response.status == '302 Found', 'Wrong response code from login got %s' % response.status
         assert response.session['hg_app_user'].username == 'test_admin', 'wrong logged in user'
         return response.follow()
-
- 

File pylons_app/tests/functional/test_admin_settings.py

 from pylons_app.tests import *
+from pylons_app.model.db import User
 
 class TestSettingsController(TestController):
 
 
     def test_edit_as_xml(self):
         response = self.app.get(url('formatted_admin_edit_setting', setting_id=1, format='xml'))
+
+    def test_my_account(self):
+        self.log_user()
+        response = self.app.get(url('admin_settings_my_account'))
+        print response
+        assert 'value="test_admin' in response.body
+        
+        
+            
+    def test_my_account_update(self):
+        self.log_user()
+        new_email = 'new@mail.pl'
+        response = self.app.post(url('admin_settings_my_account_update'), params=dict(
+                                                            _method='put',
+                                                            username='test_admin',
+                                                            new_password='test',
+                                                            password='',
+                                                            name='NewName',
+                                                            lastname='NewLastname',
+                                                            email=new_email,))
+        response.follow()
+        print response
+    
+        print 'x' * 100
+        print response.session
+        assert 'Your account was updated succesfully' in response.session['flash'][0][1], 'no flash message about success of change'
+        user = self.sa.query(User).filter(User.username == 'test_admin').one()
+        assert user.email == new_email , 'incorrect user email after update got %s vs %s' % (user.email, new_email)
+    
+    def test_my_account_update_own_email_ok(self):
+        self.log_user()
+                
+        new_email = 'new@mail.pl'
+        response = self.app.post(url('admin_settings_my_account_update'), params=dict(
+                                                            _method='put',
+                                                            username='test_admin',
+                                                            new_password='test',
+                                                            name='NewName',
+                                                            lastname='NewLastname',
+                                                            email=new_email,))
+        print response
+                
+    def test_my_account_update_err_email_exists(self):
+        self.log_user()
+                
+        new_email = 'test_regular@mail.com'#already exisitn email
+        response = self.app.post(url('admin_settings_my_account_update'), params=dict(
+                                                            _method='put',
+                                                            username='test_admin',
+                                                            new_password='test',
+                                                            name='NewName',
+                                                            lastname='NewLastname',
+                                                            email=new_email,))
+        print response
+        
+        assert 'That e-mail address is already taken' in response.body, 'Missing error message about existing email'
+        
+        
+    def test_my_account_update_err(self):
+        self.log_user()
+                
+        new_email = 'newmail.pl'
+        response = self.app.post(url('admin_settings_my_account_update'), params=dict(
+                                                            _method='put',
+                                                            username='test_regular2',
+                                                            new_password='test',
+                                                            name='NewName',
+                                                            lastname='NewLastname',
+                                                            email=new_email,))
+        print response
+        assert 'An email address must contain a single @' in response.body, 'Missing error message about wrong email'
+        assert 'This username already exists' in response.body, 'Missing error message about existing user'

File pylons_app/websetup.py

     tests = False
     REPO_TEST_PATH = None
     
-    dbname = os.path.split(conf['sqlalchemy.db1.url'])[-1]
-#    filename = os.path.split(conf.filename)[-1]
-#    if filename == 'test.ini':
-#        uniq_suffix = str(int(mktime(datetime.datetime.now().timetuple())))
-#        REPO_TEST_PATH = '/tmp/hg_app_test_%s' % uniq_suffix
-#        
-#        if not os.path.isdir(REPO_TEST_PATH):
-#            os.mkdir(REPO_TEST_PATH)
-#            cur_dir = dn(os.path.abspath(__file__))
-#            tar = tarfile.open(jn(cur_dir,'tests',"vcs_test.tar.gz"))
-#            tar.extractall(REPO_TEST_PATH)
-#            tar.close()
-#            
-#        tests = True    
+    dbname = os.path.split(conf['sqlalchemy.db1.url'])[-1] 
     
     dbmanage = DbManage(log_sql, dbname, tests)
     dbmanage.create_tables(override=True)