This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

konrads

By: a guest on Nov 30th, 2007  |  syntax: Python  |  size: 15.54 KB  |  views: 77  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # -*- coding: utf8 -*-
  2. # Copytight 2007 Konrads Smelkovs, KPMG
  3. # ksmelkovs@kpmg.com
  4. from net.grinder.script import Test
  5. from net.grinder.script.Grinder import grinder
  6. from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest
  7. from HTTPClient import NVPair
  8. from com.ziclix.python.sql import zxJDBC
  9. import md5
  10. from net.grinder.common import GrinderException
  11. from BeautifulSoup import BeautifulSoup
  12. import re
  13. connectionDefaults = HTTPPluginControl.getConnectionDefaults()
  14. connectionDefaults.setUseContentEncoding(0)
  15. connectionDefaults.setUseTransferEncoding(1)
  16. import tempfile
  17. connectionDefaults.setProxyServer("localhost", 8008)
  18. httpUtilities = HTTPPluginControl.getHTTPUtilities()
  19. import random,java
  20. #HTTPPluginControl
  21. connectionDefaults.defaultHeaders = \
  22.   ( NVPair( 'Accept-Language', 'en-us,en;q=0.5' ),
  23.     NVPair( 'Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' ),
  24.     NVPair( 'Accept-Encoding', 'gzip,deflate' ),
  25.     NVPair( 'User-Agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.8) Gecko/20071022 Ubuntu/7.10 (gutsy) Firefox/2.0.0.8' ),
  26.     NVPair( 'Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5' ), )
  27.  
  28. url = 'https://www2.vid.gov.lv:443'
  29. common_password='demo'
  30.  
  31. pgParams = {
  32.           'serverName': 'localhost',
  33.           'databaseName' : 'kstest',
  34.           'user': 'kstest',
  35.           'password': 'kstest',
  36.           'portNumber': 5432,
  37.           'initialConnections': 2,
  38.           'maxConnections': 20
  39.           }
  40. host=java.lang.System.getProperty('eds.host')
  41. if host:
  42.     pgParams['serverName']=host
  43. dbname=java.lang.System.getProperty('eds.db')
  44. if dbname:
  45.     pgParams['user']=dbname
  46.     pgParams['databaseName']=dbname
  47.     pgParams['password']=dbname
  48.  
  49. db=apply( zxJDBC.connectx, ( "org.postgresql.ds.PGPoolingDataSource", ), pgParams )
  50. class EDSTestException(Exception):
  51.     """
  52.    EDS Test Base Exception
  53.    """
  54.  
  55. class LoginException( EDSTestException ):
  56.     """
  57.    Login to EDS exception
  58.    """
  59. class SigningException(EDSTestException):
  60.     """
  61.    Exception when signing a declaration
  62.    """
  63. def soupup(text,codec='cp1257'):    
  64.     soup=BeautifulSoup()
  65.     soup.feed(text,codec)
  66.     return soup
  67. class EDSTestCase:
  68.     """
  69.    Common TestCase class for subclassing by all EDS Test Cases.
  70.    """
  71.     db=db
  72.     """
  73.    A PG Connection to DB Server.
  74.    """
  75.     def login( self, username, password ):
  76.         """
  77.        Login with the specified username and password
  78.        """
  79.         grinder.logger.output( "Login test case started" )
  80.         headers1= \
  81.         ( NVPair( 'Referer', 'https://www2.vid.gov.lv/eds/' ), )
  82.  
  83.         headers2= \
  84.         ( NVPair( 'Referer', 'https://www2.vid.gov.lv/eds/logon/logon.asp' ), )    
  85.  
  86.         headers3= \
  87.         ( NVPair( 'Referer', 'https://www2.vid.gov.lv/eds/logon/nm_izvele.asp' ), )    
  88.  
  89.         request1001 = HTTPRequest( url=url, headers=() )
  90.         request1001 = Test( 1001, 'Login - GET /  - User accesses the eds site' ).wrap( request1001 )
  91.        
  92.         request1002 = HTTPRequest( url=url, headers=headers1 )
  93.         request1002 = Test( 1002, 'Login - GET logon.asp - User is redirected to logon page' ).wrap( request1002 )
  94.        
  95.         request1003 = HTTPRequest( url=url, headers=headers2 )
  96.         request1003 = Test( 1003, 'Login - POST logon2.asp - Users logs on' ).wrap( request1003 )
  97.        
  98.         request1004 = HTTPRequest( url=url, headers=headers2 )
  99.         request1004 = Test( 1004, 'Login - GET logon.asp - An odd and useless redirect? ' ).wrap( request1004 )
  100.        
  101.         request1005 = HTTPRequest( url=url, headers=headers2 )
  102.         request1005 = Test( 1005, 'Login - GET nm_izvele.asp - Pick a tax payer' ).wrap( request1005 )
  103.        
  104.         request1006 = HTTPRequest( url=url, headers=headers3 )
  105.         request1006 = Test( 1006, 'Login - GET main.asp - Access the main screen' ).wrap( request1006 )
  106.        
  107.         result = request1001.GET( '/eds/' )        
  108.         result = request1002.GET( '/eds/logon/logon.asp' )
  109.        
  110.         self.token_tabid = \
  111.           httpUtilities.valueFromBodyURI( 'tabid' ) # '11'
  112.         # 2 different values for token_id found in response, using the first one.
  113.         self.token_id = \
  114.           httpUtilities.valueFromBodyURI( 'id' ) # '514'
  115.         self.token_hl = \
  116.           httpUtilities.valueFromBodyURI( 'hl' ) # '1'
  117.         self.token_mod = \
  118.           httpUtilities.valueFromBodyURI( 'mod' ) # '33'
  119.         self.token_Token = \
  120.           httpUtilities.valueFromHiddenInput( 'Token' ) # '64418874'
  121.         self.token_Pass = \
  122.           httpUtilities.valueFromHiddenInput( 'Pass' ) # '*hhj37^'
  123.  
  124.         self.token_Pass = \
  125.           md5.md5( password ).hexdigest().upper()  # Is this supposed to improve security :D :D :D
  126.        
  127.         # Expecting 1004 'Object moved'
  128.         result = request1003.POST( '/eds/logon/logon2.asp',
  129.           ( NVPair( 'Token', self.token_Token ),
  130.             NVPair( 'Pass', self.token_Pass ),
  131.             NVPair( 'UserName', username ),
  132.             NVPair( 'Password', '' ), ),
  133.           ( NVPair( 'Content-Type', 'application/x-www-form-urlencoded' ), ) )
  134.        
  135.         if result.getText().find( "Sazinieties ar VID EDS centru, lai nov" )>-1:
  136.             raise LoginException( "This user has no active taxpayers assigned" )
  137.         #f=open("/tmp/out.txt","w")
  138.         #f.write(result.getText())    
  139.         #f.close()
  140.         #grinder.logger.output(result.getText())
  141.        
  142.        
  143.         result = request1004.GET( '/eds/logon/logon.asp' )
  144.        
  145.  
  146. #TODO: Parse headers and see if nm_izvele is necessary at all        
  147.         result=request1005.GET( '/eds/logon/nm_izvele.asp' )
  148.         if result.getStatusCode()==200:
  149.             if result.getText().find( u"Nodok&#316;u maks&#257;t&#257;ja izv&#275;le" )<0: # String not found
  150.                 raise LoginException( "1005 / Unable to log on with username %s - wrong screen" % username )
  151.             self.token_nmr_nosauk = httpUtilities.valueFromHiddenInput( 'nmr_nosauk' ) # '992233841'
  152. #            self.token_nmr_nosauk = 'Visi'
  153.         elif result.getStatusCode()==302:
  154.             pass
  155.         else:
  156.             raise LoginException( "1005 / Unable to log on with username %s - resultcode: %i" % ( username, result.getStatusCode() ) )
  157.         # Expecting 1004 'Object moved'
  158.         result = request1005.POST( '/eds/logon/nm_izvele.asp',
  159.           ( NVPair( 'nmr', '' ),
  160.  #           NVPair('nmr_nosauk', self.token_nmr_nosauk),
  161.             NVPair( 'submit', 'Turpināt' ), ),
  162.           ( NVPair( 'Content-Type', 'application/x-www-form-urlencoded' ), ) )
  163.  
  164.         result = request1006.GET( '/eds/logon/main.asp' )        
  165.        
  166.         if not result.getText().find( "Dokumentu saraksts" )>-1:
  167.             raise LoginException( "1006 / Unable to lon on with username %s - wrong screen" % username )
  168.         self.token_m2 = \
  169.           httpUtilities.valueFromBodyURI( 'm2' ) # '-1'
  170.         self.token_type = \
  171.           httpUtilities.valueFromBodyURI( 'type' ) # 'j'
  172.         # 5 different values for token_e1 found in response, using the first one.
  173.         self.token_e1 = \
  174.           httpUtilities.valueFromBodyURI( 'e1' ) # '1147088'
  175.         self.token_action = \
  176.           httpUtilities.valueFromHiddenInput( 'action' ) # 'D'
  177.         return result
  178.     def logout( self ):
  179.         """
  180.        Log-out from EDS
  181.        """
  182.         request1007 = HTTPRequest( url=url, headers=() )
  183.         request1007 = Test( 1007, 'Logout - GET logon.asp' ).wrap( request1007 )
  184.         result = request1007.GET( '/eds/logon/logon.asp?l1=logout' )
  185.    
  186.     def getNextLegalEntity( self ):
  187.         """
  188.        Return a yet-unused legal entity (in this test run) for entry submission.
  189.        @return tuple (username,reg_id,)
  190.        """                
  191.         return '1111543'
  192.         cursor=self.db.cursor()
  193.         cursor.execute( """SELECT * from getnextlogin()""" )
  194.         for x in cursor.fetchall():
  195.             #grinder.logger.output("\n\n>>>HELLO: %s" % str(x))
  196.             return x[0]
  197.     def signDeclaration( self ):
  198.         """
  199.        Sign first declaration in the list
  200.        """
  201.         headers10= \
  202.         ( NVPair( 'Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5' ),
  203.           NVPair( 'Referer', 'https://www2.vid.gov.lv/eds/logon/main.asp' ), )
  204.  
  205.  
  206.      
  207.         request704 = HTTPRequest( url=url, headers=headers10 )
  208.         request704 = Test( 1201, 'GET main.asp' ).wrap( request704 )
  209.         result=request704.GET('/eds/logon/main.asp')
  210.         soup=soupup(result.getText())
  211.         try:            
  212.             t=soup.first( "tr", {'class':'tbody_mainlist_white'} ).fetch( "td", {'valign':'middle'} )[1].contents[0]        
  213.             self.signingpath=t.getattr('href')
  214.         except AttributeError:
  215.             name=tempfile.mktemp('declarationSign')
  216.             f=open(name,"wb")
  217.             f.write(result.getText())
  218.             f.close()
  219.             raise SigningException("Error while parsing main screen, perhaps user does not have permission to sign?, screen saved to: %s" % name)
  220.        
  221.  
  222.         headers15= \
  223.         ( NVPair( 'Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5' ),
  224.           NVPair( 'Referer', 'https://www2.vid.gov.lv/eds/logon/'+self.signingpath ), )        
  225.        
  226.         request801 = HTTPRequest( url=url, headers=headers10 )
  227.         request801 = Test( 1202, 'GET akceptet.asp' ).wrap( request801 )
  228.  
  229.         result = request801.GET( '/eds/logon/'+self.signingpath )
  230.         if result.getStatusCode()==302 and result.getHeader("Location")=="par_piesk.asp":
  231.             raise SigningException("The electronic signature for current user is blocked")
  232.         soup=soupup(result.getText())
  233.         try:
  234.             adresats=soup.first( 'input', {'id':'adresats'} ).getattr('value')
  235.             adresats2=soup.first( 'input', {'id':'adresats2'} ).getattr('value')
  236.             izstrades_vieta=soup.first( 'input', {'id':'izstrades_vieta'} ).getattr('value')
  237.             dok_tips=soup.first( 'input', {'id':'dok_tips'} ).getattr('value')
  238.             dok_num=soup.first( 'input', {'name':'dok_num'} ).getattr('value')
  239.             taks_datno=soup.first( 'input', {'name':'taks_datno'} ).getattr('value')
  240.             taks_datlidz=soup.first( 'input', {'name':'taks_datlidz'} ).getattr('value')
  241.             sagatavotajs=soup.first( 'input', {'name':'sagatavotajs'} ).getattr('value')
  242.             atbild_pers=soup.first( 'input', {'name':'atbild_pers'} ).getattr('value')
  243.             nmr_kods=soup.first( 'input', {'name':'nmr_kods'} ).getattr('value')
  244.             nmr_nos=soup.first( 'input', {'name':'nmr_nos'} ).getattr('value')
  245.             nmr_adrese=soup.first( 'input', {'name':'nmr_adrese'} ).getattr('value')
  246.             atbild_pers2=soup.first( 'input', {'name':'atbild_pers2'} ).getattr('value')
  247.             amata_nos=soup.first( 'input', {'name':'amata_nos'} ).getattr('value')
  248.             personas_kods=soup.first( 'input', {'name':'personas_kods'} ).getattr('value')
  249.             epasts=soup.first( 'input', {'id':'epasts'} ).getattr('value')
  250.         except AttributeError:
  251.             name=tempfile.mktemp('declarationSign')
  252.             f=open(name,"wb")
  253.             f.write(result.getText())
  254.             f.close()
  255.             raise SigningException("Error while parsing screen, screen saved to: %s" % name)
  256.         pers_tips=''
  257.         irIzdruka=1
  258.         sig=demo_key
  259.        
  260.        
  261.         requestUrl='/eds/logon/akceptet2.asp?1=1'
  262.         for i in re3.split("""adresats, adresats2, izstrades_vieta, dok_tips, dok_num, taks_datno, taks_datlidz, sagatavotajs, atbild_pers, nmr_kods,
  263.                  nmr_nos, nmr_adrese, atbild_pers2, amata_nos, personas_kods, epasts,pers_tips,irIzdruka"""):
  264.             val=eval(i)
  265.             #grinder.logger.output(">>> %s=%s\n" % (i,val) )
  266.             requestUrl+="&%s=%s" % (i,val)
  267.         request901 = HTTPRequest( url=url, headers=headers15 )
  268.         request901 = Test( 1203, 'POST akceptet2.asp' ).wrap( request901 )
  269.         #print "\n>>>"+requestUrl + "\n"
  270.         formData=\
  271. '''-----------------------------159714522920833419191666707805\r\n\
  272. Content-Disposition: form-data; name=\"docfile\"; filename=\"Key_demo.sig\"\r\n\
  273. Content-Type: application/octet-stream\r\n\
  274. \r\n\
  275. '''+sig+'''\r\n\
  276. -----------------------------159714522920833419191666707805--\r\n\
  277. '''
  278.         result = request901.POST(
  279.                                  requestUrl,    # URI
  280.                                  formData,    # Form data
  281.         ( NVPair( 'Content-Type', 'multipart/form-data; boundary=---------------------------159714522920833419191666707805' ), ) # headers
  282.         )
  283.        
  284.         request902 = HTTPRequest( url=url, headers=headers15 )
  285.         request902 = Test( 1204, 'GET akceptet.asp' ).wrap( request902 )
  286.         result=request902.GET('/eds/logon/akceptet.asp?lErr=False')
  287.         if not re4.search(result.getText()):
  288.             raise SigningDeclaration("Something wrong while signing the form")
  289.    
  290.     def _generateTaxpayers(self,count=10):
  291.         """
  292.        Generate physical persons that are registered taxpayers
  293.        """
  294.         rnd=random.randint(1,9990)
  295.         cursor=self.db.cursor()
  296.         cursor.execute("select pers_kods,vards,uzvards from phys_pers WHERE id > %i limit %i" % (rnd,count))
  297.         return cursor.fetchall()
  298.    
  299.     def _generatePartners(self,count=10):
  300.         """
  301.        Generate legal entitities that are registered taxpayers
  302.        """
  303.         rnd=random.randint(1,9990)
  304.         cursor=self.db.cursor()
  305.         cursor.execute("select nmr_kods,isais_nosauk from taxpayers_legal WHERE id > %i limit %i" % (rnd,count))
  306.         return cursor.fetchall()
  307.    
  308. def instrumentMethod( test, method_name, c=EDSTestCase ):
  309.   """Instrument a method with the given Test."""
  310.   unadorned = getattr( c, method_name )
  311.   import new
  312.   method = new.instancemethod( test.wrap( unadorned ), None, c )
  313.   setattr( c, method_name, method )
  314.  
  315. instrumentMethod( Test( 1000, 'EDS Login' ), 'login' )
  316. instrumentMethod( Test( 1100, 'EDS Logout' ), 'logout' )
  317. instrumentMethod( Test(1200, 'EDS sign declaration'),'signDeclaration')
  318. re3=re.compile("\W+")        
  319. re4=re.compile("Dokuments ir veiksm.gi parakst.ts")
  320.  
  321. demo_key='''ncgw4PqxXjW0eSpThw3aBnf6Thxh+pINLB4BkL2CBrgJBFwrWy+r0FSa7ZX7hVBdKxgsk+QtorurkXjNX2mQFc/3ZZJxH+ZWAImVEC1M0PO+jBkfXwdlUzd5SqftHtUI5s7ZsCkR1KmJSmTdFqafp79/2x9LQSM7htZZzw01Oh5FEsifzka0blseIcs8z0+GOmdBs+EBOZSm+DMaVDibDq8PissnxLUHhk7N14f9lVzRFhRMLuQ8LhiHOshuVeAH/KNTJH/TpVMKrS8zdsdlRMjyeln25fWPxNuG0ytxNSJ6X37bwo/E43499zanz6IGvzDLukIftdujIEgCH4xHVr5A8TcL1VCdVk10Ybp55aQAfdmUU0zzdNZy4ge10Aqnc03ORTQ+szI/2Qh3q3g9qyXQULuUXvpNwoGNKPLFWshCa/Q9gN1ao+qroe2PI9IkIHacS6u0dLgsDT4iTHVW+mcu415YNWm+3e8I8MCh9YziyZd3K0+ZfdoIeXrbLRnYhGQgk1FtH7q73bhBxlb1JRNr9taRv6mtzFvQBj/p/LRF170/O1ziWmz/X6/VmwHUNAoL8KpUyJu55ZuusA36GIygAcsgqjysp7uxCu/6wZcZXEQh0idPWagenPBxy8BWpyX4rl7SN1wqH4DIP+ahVTQiDnP0DrA6pNldSuTNMOJDRQMRcZ09xMFYB9Ps2Z8FGmDjn6a+pPz6ThLlXzBZPDppFAlFWSETOIU1zBpoPsPwPxvu9uIc9TS4dFCZgmcbP4adE/4s1uyXUjdNnLhZ9c0C2/I0uxkGXQOOiffxzddXJEAdLZ7JW4y0xf90y7N6vSFVPRLu0PM1/wfXBfeTiSERPYmPonkdhaNlb34sivPHYRg/7C8iA3T070mkRYIpvJj/D88df9fXPOoXkIuDhFem/yAt6520zdTdcDQH28AQwtLGc7zbs4otwqslPxuQEZ9e1PNMmF6XZ0HaJrOXPmL7UJVH14UgwxKQe6BGFh+DkQ6U32rj/n7e1xnjPVqIKFzH31ZRM0X9nOKR/f0fJiOHxpOv8xKc/al4/bPHL35do/wh4L3FhKrHONVUuif3fKtaLfwom248Uea7vvJA0W8qTH690VoIgUtU64jST80l4TuK59oqDMWl+46sSBte9zuddQTymSklh4Qc2pQokF5cLu6qj9Na/tQn556ht/Ju0rOHQzKb7Hoemvk9pvLhJSld+BcYQmmrqx0XPq29CVxt+s8H7EYHH0xHEEtpvvdsJXDJSZU+nQ=='''
clone this paste RAW Paste Data