def testCreation(self):
        #create( filename , authenticated , activated , activatingKey = None , email = None , passwd = None)

        #test anonymous session without email
        Transaction.create( self.sessionPath , False , False )
        os.unlink( self.sessionPath )

        #test anonymous session with passwd
        self.assertRaises( SessionError , Transaction.create , self.sessionPath , False , False , passwd = self.passwd )

        #test anonymous session with email
        Transaction.create( self.sessionPath , False , False , userEmail = self.email )
        os.unlink( self.sessionPath )

        #test authenticated session without passwd -> SessionError
        self.assertRaises( SessionError , Transaction.create , self.sessionPath , True , False , userEmail = self.email )

        #test authenticated session without email -> SessionError
        self.assertRaises( SessionError , Transaction.create , self.sessionPath , True , False , passwd = self.passwd )

        #test authenticated session with email and passwd
        Transaction.create( self.sessionPath , True , False , userEmail = self.email , passwd = self.passwd )
        os.unlink( self.sessionPath )

        #test authenticated session with activatingKey
        Transaction.create( self.sessionPath , True , False , activatingKey = self.actkey , userEmail = self.email , passwd = self.passwd )
        os.unlink( self.sessionPath )

        #test that session creation fails if already exists
        Transaction.create( self.sessionPath , False , False )
        self.assertRaises( SessionError , Transaction.create , self.sessionPath , False , False )
        os.unlink( self.sessionPath )
 def testHasJob( self ):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     jobid = "file://tmp/mobyle/results/dnadist/G25406684175968"
     transaction = Transaction( self.sessionPath , Transaction.READ )
     self.assertTrue( transaction.hasJob( jobid ) )
     self.assertFalse( transaction.hasJob( jobid.replace('G','Z') ) )
     transaction.commit()
 def testGetAllData(self):
     shutil.copy( self.xmlSourcePath , self.sessionPath)
     transaction = Transaction( self.sessionPath , Transaction.READ )
     receivedData = transaction.getAllData()
     transaction.commit()
     self.assertTrue( len( receivedData ) == 2 )
     for data in receivedData:
         self.assertTrue( data in self.datas )
 def _fakesession(self, key):
     session_key = key
     session_dir = os.path.join(self.cfg.user_sessions_path(), session_key)
     session = Mobyle.Session.Session(session_dir, session_key, self.cfg)
     os.makedirs(session_dir)
     session_xml = os.path.join(session_dir, session.FILENAME)
     Transaction.create(session_xml, False, True)
     return session
    def testGetAllJobs( self ):
        shutil.copy( self.xmlSourcePath , self.sessionPath)
        transaction = Transaction( self.sessionPath , Transaction.READ )
        receivedJobs = transaction.getAllJobs()
        transaction.commit()
        self.assertTrue( len( receivedJobs ) == 2 )

        for job in receivedJobs:
            self.assertTrue( job in self.jobs )
 def testRollback(self):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.removeData( self.dataID[0] )
     self. assertFalse( transaction.hasData(self.dataID[0] ) )
     transaction.rollback()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     self.assertTrue( transaction.hasData( self.dataID[0] ) )
     transaction.commit()
 def testRemoveJob( self ):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.removeJob( self.jobID[1] )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     self.assertFalse( transaction.hasJob( self.jobID[1] ) )
     transaction.commit()
 def testRenameData( self ):
     shutil.copy( self.xmlSourcePath , self.sessionPath)
     newUserName = '******'
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.renameData( self.dataID[0] , newUserName )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     data = transaction.getData( self.dataID[0] )
     transaction.commit()
     self.assertTrue( newUserName == data[ 'userName' ] )
 def testRenameJob( self ):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     newUserName = "******"
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.renameJob( self.jobID[1] , newUserName )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     job = transaction.getJob( self.jobID[1] )
     transaction.commit()
     self.assertEqual( newUserName , job[ 'userName' ] )
 def testUpdateJobStatus( self ):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     sendStatus = Mobyle.Status.Status( code = 7 ) #hold
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.updateJobStatus( self.jobID[0] , sendStatus )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     job = transaction.getJob( self.jobID[0] )
     transaction.commit()
     self.assertEqual( sendStatus , job[ 'status' ] )
    def testConcurency(self):
        Transaction.create( self.sessionPath , False , False )
        transaction = Transaction( self.sessionPath , Transaction.READ )
        ## sub-process start
        childPid = os.fork()
        if childPid: #father
            pid , status = os.wait()
            self.assertFalse( status )
        else: #child
            cmd = [ sys.executable, 'openTransaction.py' , self.sessionPath , str( Transaction.READ ) ]
            os.execv( cmd[0] , cmd )
        ## sub-process end
        transaction.commit()

        transaction = Transaction( self.sessionPath , Transaction.WRITE )
        ## sub-process start
        childPid = os.fork()
        if childPid: #father
            pid , status = os.wait()
            self.assertTrue( status )
        else: #child
            cmd = [ sys.executable, 'openTransaction.py' , self.sessionPath , str( Transaction.READ ) ]
            os.execv( cmd[0] , cmd )
        ## sub-process end
        transaction.commit()
 def testTransaction(self):
     Transaction.create( self.sessionPath , False , False )
     # Check locks types
     transaction = Transaction( self.sessionPath, Transaction.WRITE )
     transaction.rollback()
     transaction = Transaction( self.sessionPath, Transaction.READ )
     transaction.rollback()
     self.assertRaises(MobyleError, Transaction, self.sessionPath, None )
     # Invalid file
     self.assertRaises(SessionError, Transaction, str(None), Transaction.READ)
 def testgetAllUniqueLabels(self):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     label_1= [ 'label_1', 'label_1_bis' ]
     label_2=  label_1 + [ 'label_2' ]
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.setJobLabels( self.jobID[0] , label_1 )
     transaction.setJobLabels( self.jobID[1] , label_2 )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     label_recieved = transaction.getJobLabels( self.jobID[1] )
     transaction.commit()
     s = set( label_1 + label_2 )
     unique = list( s )
     unique.sort()
     label_recieved.sort()
     self.assertEqual( label_recieved , unique )
 def testLinkJobOutput2Data( self ):
     Transaction.create( self.sessionPath , False , True )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     sendData = self.datas[0]
     transaction.createData( sendData[ 'dataName' ] ,
                             sendData[ 'userName' ] ,
                             sendData[ 'size' ] ,
                             sendData[ 'Type' ] ,
                             sendData[ 'dataBegin' ] ,
                             sendData[ 'inputModes' ] ,
                             producedBy = [] ,
                             usedBy = []
                             )
     sendJob = self.jobs[ 0 ]
     transaction.createJob( sendJob['jobID'] ,
                             sendJob['userName'] ,
                             sendJob['programName'] ,
                             sendJob['status'] ,
                             sendJob['date'] ,
                             [] ,
                             []
                             )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.linkJobOutput2Data( [ sendData[ 'dataName' ] ] , [ sendJob['jobID'] ])
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     data = transaction.getData( sendData[ 'dataName' ] )
     job = transaction.getJob( sendJob['jobID'])
     transaction.commit()
     self.assertEqual( data[ 'producedBy' ][0] , sendJob[ 'jobID' ] )
     self.assertEqual( job[ 'dataProduced' ][0] , sendData[ 'dataName' ] )
    def testCommit(self):
        Transaction.create( self.sessionPath , False , False )

        # Ensure that transaction with modification update the file
        bef = os.stat( self.sessionPath )
        transaction = Transaction( self.sessionPath , Transaction.WRITE )
        transaction._setModified( True )
        transaction.commit()
        aft = os.stat( self.sessionPath )
        self.assertFalse( bef.st_ino == aft.st_ino and bef.st_mtime == aft.st_mtime )

        # Ensure that transaction without modification does not update the file
        bef = os.stat( self.sessionPath )
        transaction = Transaction( self.sessionPath , Transaction.WRITE )
        transaction._setModified( False )
        transaction.commit()
        aft = os.stat( self.sessionPath )
        self.assertTrue( bef.st_ino == aft.st_ino and bef.st_mtime == aft.st_mtime )

        # By default, an empty transaction should have no effect on the file
        bef = os.stat( self.sessionPath )
        transaction = Transaction( self.sessionPath , Transaction.WRITE )
        transaction.commit()
        aft = os.stat( self.sessionPath )
        self.assertTrue( bef.st_ino == aft.st_ino and bef.st_mtime == aft.st_mtime )
 def testAuthenticated(self):
     Transaction.create( self.sessionPath , True , True , activatingKey = self.actkey , userEmail = self.email , passwd = self.passwd )
     transaction = Transaction( self.sessionPath , Transaction.READ )
     auth = transaction.isAuthenticated()
     transaction.commit()
     self.assertTrue( auth )
 def testPasswd(self):
     Transaction.create( self.sessionPath , False , False )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     sendPasswd = "monBeauMotDePasse"
     transaction.setPasswd( sendPasswd )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     receivedPasswd =  transaction.getPasswd()
     transaction.commit()
     self.assertTrue( sendPasswd == receivedPasswd )
 def testCreateAndGetJob( self ):
     Transaction.create( self.sessionPath , False , True )
     sendJob = self.jobs[ 1 ]
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.createJob( sendJob['jobID'] ,
                             sendJob['userName'] ,
                             sendJob['programName'] ,
                             sendJob['status'] ,
                             sendJob['date'] ,
                             sendJob['dataUsed'] ,
                             sendJob['dataProduced']
                             )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     receivedJob = transaction.getJob( sendJob[ 'jobID' ] )
     transaction.commit()
     self.assertEqual( sendJob , receivedJob )
 def testActivatingKey(self):
     Transaction.create( self.sessionPath , False , True , activatingKey = self.actkey , userEmail = None)
     transaction = Transaction( self.sessionPath , Transaction.READ )
     actKey = transaction.getActivatingKey()
     transaction.commit()
     self.assertTrue( actKey == self.actkey )
 def testgetID(self):
     Transaction.create( self.sessionPath , False , False )
     transaction = Transaction( self.sessionPath , Transaction.READ )
     receivedID = transaction.getID()
     transaction.commit()
     self.assertEqual( receivedID , self.sessionKey )
 def testSetAndGetJobDescription(self):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     job_description = "a new beautiful description for this job"
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.setJobDescription( self.jobID[0] , job_description)
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     jobDescription_recieved = transaction.getJobDescription( self.jobID[0] )
     transaction.commit()
     self.assertEqual( jobDescription_recieved , job_description )
     transaction = Transaction( self.sessionPath , Transaction.READ )
     jobDescription_recieved = transaction.getJobDescription( self.jobID[1] )
     transaction.commit()
     self.assertEqual( None , jobDescription_recieved )
 def testSetAndGetJobLabel(self):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     #there is not labels yet in jobs
     transaction = Transaction( self.sessionPath , Transaction.READ )
     label_recieved = transaction.getJobLabels(self.jobID[0])
     transaction.commit()
     self.assertEqual( label_recieved , [] )
     #add one label
     label_send = ['label_1']
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.setJobLabels( self.jobID[0] , label_send )
     transaction.commit()
     #get one label
     transaction = Transaction( self.sessionPath , Transaction.READ )
     label_recieved = transaction.getJobLabels(self.jobID[0])
     transaction.commit()
     self.assertEqual( label_recieved , label_send )
     #add 2 labels
     label_send = ['label_2', 'label_2_bis']
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.setJobLabels( self.jobID[1] , label_send )
     transaction.commit()
     #get 2 labels
     transaction = Transaction( self.sessionPath , Transaction.READ )
     label_recieved = transaction.getJobLabels(self.jobID[1])
     transaction.commit()
     self.assertEqual( label_recieved , label_send )
     #add label in job which have already labels
     new_label = [ 'label_3', 'label_3_bis' ]
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.setJobLabels( self.jobID[1] , new_label )
     transaction.commit()
     #get 2 new labels
     transaction = Transaction( self.sessionPath , Transaction.READ )
     label_recieved = transaction.getJobLabels( self.jobID[1] )
     label_recieved = transaction.getJobLabels( self.jobID[1] )
     transaction.commit()
     self.assertEqual( label_recieved , new_label )
 def testEmail(self):
     Transaction.create( self.sessionPath , False , False )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.setEmail( self.email )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     receivedEmail = transaction.getEmail()
     transaction.commit()
     self.assertTrue( receivedEmail == self.email )
 def testCaptchaSolution( self ):
     sendSoluce = 'solution'
     Transaction.create( self.sessionPath , False , False )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.setCaptchaSolution( sendSoluce )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     receivedSoluce = transaction.getCaptchaSolution()
     transaction.commit()
     self.assertTrue( sendSoluce == receivedSoluce )
     transaction2 = Transaction( self.sessionPath , Transaction.READ )
     receivedSoluce = transaction2.getCaptchaSolution()
     self.assertTrue( sendSoluce == receivedSoluce )
     transaction2.commit()
 def testHasData(self):
     shutil.copy( self.xmlSourcePath , self.sessionPath)
     transaction = Transaction( self.sessionPath , Transaction.READ )
     self.assertTrue( transaction.hasData( self.dataID[1] ) )
     transaction.commit()
 def testAddInputModes(self ):
     shutil.copy( self.xmlSourcePath , self.sessionPath )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.addInputModes( self.dataID[0] , [ 'paste' , 'db' ] )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     data = transaction.getData( self.dataID[0] )
     transaction.commit()
     result = ['paste' , 'db' , 'result']
     result.sort()
     data[ 'inputModes' ].sort()
     self.assertEqual( data[ 'inputModes' ] , result )
     #an inputMode must not be twice in the xml
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     transaction.addInputModes( self.dataID[0] , [ 'paste' ] )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     data = transaction.getData( self.dataID[0] )
     transaction.commit()
     data[ 'inputModes' ].sort()
     self.assertEqual( data[ 'inputModes' ] , result )
 def testCreateAndGetData( self ):
     Transaction.create( self.sessionPath , True , True , activatingKey = 'uneJolieCle' , userEmail = self.email , passwd = self.passwd )
     transaction = Transaction( self.sessionPath , Transaction.WRITE )
     sendData = self.datas[0]
     transaction.createData( sendData[ 'dataName' ] ,
                             sendData[ 'userName' ] ,
                             sendData[ 'size' ] ,
                             sendData[ 'Type' ] ,
                             sendData[ 'dataBegin' ] ,
                             sendData[ 'inputModes' ] ,
                             producedBy = sendData[ 'producedBy' ] ,
                             usedBy = sendData[ 'usedBy' ]
                             )
     transaction.commit()
     transaction = Transaction( self.sessionPath , Transaction.READ )
     receivedData = transaction.getData( sendData[ 'dataName' ] )
     transaction.commit()
     self.assertTrue( receivedData == sendData )
 def __init__( self , cfg , userEmail , passwd=None, ticket_id=None):
     self.log = getLogger('Mobyle.Session.AuthenticatedSession')
     self.cfg = cfg
     assert not(passwd and ticket_id), "please provide either a ticket id or a password" # TODO: clean up the parameters check
     """the maximum size of a session ( in bytes )"""
     self.sessionLimit = self.cfg.sessionlimit()
     self.__userEmail = userEmail
     authenticatedSessionAllowed = self.cfg.authenticatedSession()        
     
     if authenticatedSessionAllowed == "no" :
         self.log.error("can't create  session AUTHENTICATED_SESSION is set to \"no\" in Local/Config/Config.py")          
         raise SessionError , "can't create  authenticated session: permission denied"
           
     key = self.__newSessionKey()
     sessionDir = os.path.normpath( os.path.join( self.cfg.user_sessions_path() , AuthenticatedSession.DIRNAME , key  ) )
     self.key = key 
     """ the user/session  key"""
     self.Dir = sessionDir
     """ the path to this session directory """
    
     if os.path.exists( sessionDir ): #the session already exist
         if passwd:
             if not self.checkPasswd( passwd ):
                 self.log.info( "authentified/%s : Authentication Failure "% ( self.getKey() ) )
                 raise AuthenticationError , "Authentication Failure"
             else:
                 self._getTicket()
         elif ticket_id and not self.checkTicket( ticket_id ):
             raise AuthenticationError , "Invalid ticket or expired ticket"
         else:
             self.__generateTicketId(ticket_id or None)
         
     else: #creation of new Session
         chk = self.__userEmail.check()
         if not chk:
             msg = " %s %s FORBIDDEN can't create authenticated session : %s" % ( self.__userEmail ,
                                 os.environ[ 'REMOTE_ADDR' ] ,
                                 self.__userEmail.getMessage()
                                 )
             self.log.error( msg )
             raise SessionError , "you are not allowed to register on this server for now"
         try:
             os.makedirs( sessionDir , 0755 ) #create parent directory 
         except Exception, err:
             self.log.critical( "unable to create authenticated session : %s : %s" % ( sessionDir , err) , exc_info = True)
             raise SessionError , "unable to create authenticated session"
         mymd5 = md5()
         mymd5.update( passwd )
         cryptPasswd = mymd5.hexdigest()
         
         authenticatedSessionAllowed = self.cfg.authenticatedSession()        
         if authenticatedSessionAllowed == "yes":  
             Transaction.create( os.path.join( sessionDir , self.FILENAME ) , 
                                 True , #authenticated
                                 True , #activated
                                 userEmail = str( self.__userEmail ) , 
                                 passwd = cryptPasswd )
             self.__generateTicketId()
         elif authenticatedSessionAllowed == "email" :
             activatingKey = self.__newActivatingKey()
             try:
                 from Mobyle.Net import Email
                 mail = Email( self.__userEmail )
                 mail.send( 'CONFIRM_SESSION' , { 'SENDER'         : self.cfg.sender() ,
                                                  'HELP'           : self.cfg.mailHelp() ,
                                                  'SERVER_NAME'    : self.cfg.portal_url() ,
                                                  'ACTIVATING_KEY' : activatingKey ,
                                                  'CGI_URL'        : self.cfg.cgi_url() } 
                            )
                 
                 Transaction.create( os.path.join( sessionDir , self.FILENAME ) , 
                                     True ,  #authenticated
                                     False , #activated
                                     activatingKey = activatingKey , 
                                     userEmail = self.__userEmail , 
                                     passwd = cryptPasswd )
                 self.__generateTicketId()
                 # api create( id , authenticated , activated , activatingKey = None , userEmail = None, passwd = None)
             except MobyleError , err :
                 msg = "can't send an activation email, session creation aborted"
                 self.log.error( "%s : %s " % ( msg , err ) )
                 os.rmdir( self.Dir )
                 raise SessionError , msg
    def testisActivated(self):
	# Test unactivated session
        Transaction.create( self.sessionPath , False , False )
        transaction = Transaction( self.sessionPath , Transaction.READ )
        active = transaction.isActivated()
        transaction.commit()
        self.assertFalse( active )
        os.unlink( self.sessionPath )

	# Test already activated session
        Transaction.create( self.sessionPath , False , True )
        transaction = Transaction( self.sessionPath , Transaction.READ )
        active = transaction.isActivated()
        transaction.commit()
        self.assertTrue( active )
        os.unlink( self.sessionPath )

	# Test session after activation
        Transaction.create( self.sessionPath , False , False )
        transaction = Transaction( self.sessionPath , Transaction.WRITE )
        transaction.activate()
        transaction.commit()
        transaction = Transaction( self.sessionPath , Transaction.READ )
        active = transaction.isActivated()
        transaction.commit()
        self.assertTrue( active )
        os.unlink( self.sessionPath )

     # Test session after inactivation
        Transaction.create( self.sessionPath , False , True )
        transaction = Transaction( self.sessionPath , Transaction.WRITE )
        active = transaction.isActivated()
        self.assertTrue( active )
        transaction.inactivate()
        transaction.commit()
        active = transaction.isActivated()
        self.assertFalse( active )
        os.unlink( self.sessionPath )