Posts Tagged ‘Selenium’

10Nov

UPDATED: Nov 11th, 09 , changes: added python info

I have been struggling to find a way to get around selenium’s onload deficiencies. I tried all sorts of ways to hack up my script, but alas it mostly ended up in turmoil. Onload is one of the main ways most developers use to make sure certain actions happen in code, and my entire content bed was about go into flames before I found the light at the end of the tunnel. A magical gift from the heavens known as AutoIt saved me from a timely demise…

All retardedness aside… (sarcasm)..

AutoIt really did solve this problem for me. It may not work so well for others.. it depends on your situation. For me a simply wanted to close a popup window after it loaded from a different windows onload and then click the popup’s confirmation’s Ok button. Then close the original window that started all the madness…

The cool thing about running the code below is that it just runs as a daemon of sorts in the background waiting for some unruley popup to be struck down with Wrath of Kahn, plus it can also test for popups with different names. I am hoping I can do some sweet regex stuff, otherwise, life may prove difficult. In any case here is my AutoIt script:


While True
   If WinWait('Name of the final Popup', '', 1) == 1 Then
     ;Wait for page to load if found
     Sleep(10000)
     ;Close Page
     Send('!{F4}')
     Sleep(5000)
     ;Confirm Dialog
     Send('{ENTER}')
     Sleep(1000)
     ;Close Lanucher Page
     Send('!{F4}')
   EndIf
   ;Let another thread have a turn
   sleep(3)
WEnd

Now, lets say you want the above to be directly embedded into your script rather than have it constantly running externally. I personally use python for my Selenium scripting so in python you can do the follwoing (which is the equivalent of the above script).


from selenium import selenium
import unittest, re, time
from datetime import date, datetime
from xml.dom import minidom
from win32com.client import Dispatch

# Auto it window closing stuff
def autoItCloseWindows(self):
   auto = Dispatch("AutoItX3.Control")
   #Your Popup Name Here is the name of the window...
   #I did this because different windows could open for my project
   if (auto.WinWait("Your Popup Name Here", "", 1) == 1):
      # chill
      time.sleep(5)
      # close window
      auto.Send("!{F4}")
      # wait
      time.sleep(2)
      # confirm dialog box
      auto.Send("{ENTER}")
      time.sleep(5)
      # close the launcher window
      auto.Send("!{F4}")

To run this script you mainly need selenium, time, autoit3 and win32 dispatch. To download win32 stuff for python click here. Another thing to note is that this will only work for windows. There are similar solutions available for *nix. If you are using a mac to do things like this it is probably a waste of your mac ha, but there are also similar solutions.

Good luck oh weary travelers…

Share
21Oct

I have been making tests using Selenium IDE + Selenium RC + Python and trying to get Selenium Grid working as well. I will try to outline what I did in order get a pretty awesome test going. First download selenium IDE (firefox plugin to record your actions), Selenium RC and your choice of Language (I choose python). You can get Selenium here. Also you will need Java and the JDK or SDK whatever they call it.

Start by opening the Selenium IDE in Firefox and then record your test by hitting the record button and navigating around your website. Once you are done turn off the record button. Then play your test back to make sure its doing what you want. Click Options->Format and select the language your want to use. You can integrate this with JUnit or TestNG, but I will make another post about that. I want to try to get this to work with pyunit.

Once you are done, make sure to save your test. Open up the folder you extracted your Selenium RC folder and navigate to selenium-server-1.0.1 and make a bat file in there with the following line.


java -jar selenium-server.jar

Make sure to type this in rather than copy paste, or else it wont work. Now when you click on the bat file it should just start your Selenium RC server and show you a command prompt. If you close this command prompt the server will stop. Now in back in Selenium IDE copy all the code it generated and paste it either in an IDE or text file so you can launch it. Note that if the Selenium RC Server is not running then it will not work and you will get some exceptions thrown at you. One thing I did was tidy everything up, and automate my scripting to batch test a bunch of searches.

So I read an XML file generated by Excel and parsed the data accordingly. Here is part of my source:


from selenium import selenium
import unittest, re, time
from datetime import date, datetime
from xml.dom import minidom

class getParamTest(unittest.TestCase):
   testXML = '../xml/test.xml'
   baseURL = "http://yahoo.com"
   basePage = "/somePage.htm"
   machine = "localhost"
   port = 4444
   #you can add or remove browsers here
   browsers = ["*iexplore","*firefox"]

   def testMain(self):
      courses = self.getAllCourses()
      for browser in self.browsers:
         for course in courses:
            print(course)
            self.getParamTest(course,browser)

   def getParamTest(self, course_name, browser):
      #select local port for the Selenium RC, select the browser, pick the starting URL and start Selenium
      self.selenium = selenium(self.machine, self.port, browser, self.baseURL)
      self.selenium.start()
      sel = self.selenium
      #open the first page
      sel.open(self.basePage)
      time.sleep(5)
      #paste your code here
      #you should always try catch your tests or else you may get some nasty breaks
      self.closeAllWindows(sel)
      self.selenium.stop()
      #end Selenium before trying another test!

   #All windows should probably be closed here. Firefox closes them all
   #Other browsers such as Internet Explorer do not! This will close all
   #Windows selenium knows about
   def closeAllWindows(self,sel):
      names = sel.get_all_window_names()
      while len(names)>0:
      the_window = "name="+names.pop()
      try:
         sel.select_window(the_window)
         sel.close()
      except Exception, (e):
         pass

   #gets a list of all courses as specified by the given XML file
   def getAllCourses(self):
      courses = []
      xmldoc = minidom.parse(self.testXML)
      table = xmldoc.getElementsByTagName("Data")
      counter = 0
      #in an excel XML file everything is stored in dom element data
      #the only relevent info for me was in the third column.
      for item in table:
         counter+=1
         if counter == 3:
         courses.append(item.childNodes[0].data)
         counter = 0
      return courses

if __name__ == "__main__":
   unittest.main()

So I didn’t give you all my test code because it is kind of sensitive. Anyways you should have your own code for that already just paste it where I told you to in the code. One thing to note is then while you use firefox your windows will close automatically once Selenium is stopped at the end of the test; however, IE won’t do that so I found a way to make that happen. You could also use this technique to select nameless windows or popups.

I didn’t have an issue targeting elements on a page; however, if you do consider giving them names in the DOM. If you can’t do that there are usually ways around it. You can use Names, IDs, and maybe even the text present. My main issue was window popups didn’t have names so I grabbed all windows and popped them off of my stack (the last one in is always the last window opened. Another issue is pages not opening to fast. Usually if you insert “time.sleep(5)” or some equivalent waiting thing everything should workout. You should first always try to use “sel.wait_for_page_to_load(“30000″)” where 30000 is in milliseconds; whereas, the 5 in time.sleep is in seconds. Finally, the main method is the one with the word “test” in the front. This method is selected from the unittest class in Selenium as the main method.

Enjoy :-D! Updates coming soon for running tests in parallel and JUnit/PYUnit!

Share