selenium webdriver python - make selenium test case fail if there is error in custom written python code

11,908

If you want to raise the actual exception that was triggered, you can call raise by itself, which will raise the last active exception:

try:
    for contents in os.listdir(self.file_source_location):
        src_file = os.path.join(self.file_source_location, contents)
        dst_file = os.path.join(self.file_move_location, contents)
        shutil.move(src_file, dst_file)
    print'files_moved_success'
    driver.find_element_by_link_text("check out - definition of check out by the Free Online Dictionary ...").click()
except Exception as e:
    print e
    raise # Raise the exception that brought you here 

If you don't want a traceback and just want to exit, you can also call sys.exit(1) (or whatever error code you want to use) after print e:

import sys
# ...
try:
    for contents in os.listdir(self.file_source_location):
        src_file = os.path.join(self.file_source_location, contents)
        dst_file = os.path.join(self.file_move_location, contents)
        shutil.move(src_file, dst_file)
    print'files_moved_success'
    driver.find_element_by_link_text("check out - definition of check out by the Free Online Dictionary ...").click()
except Exception as e:
    print e
    sys.exit(1)
Share:
11,908
user83969
Author by

user83969

Updated on June 08, 2022

Comments

  • user83969
    user83969 almost 2 years

    I have a selenium webdriver test case exported to python using selenium IDE. Then wanted to add some additional functionality so inserted custom code in between the selenium test case.

    Now the problem is - if i make a mistake or the custom written python code returns error - still the selenium test case continues to execute

    Whereas i want the selenium test case execution to be stopped if there is such error. Have replicated the scenario below with a simple google search followed by a log movement code using shutil module

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import Select
    from selenium.common.exceptions import NoSuchElementException
    import unittest, time, re
    import os, shutil
    
    class SeleniumException(unittest.TestCase):
        def setUp(self):
            self.driver = webdriver.Chrome()
            self.driver.implicitly_wait(30)
            self.base_url = "https://www.google.co.in/"
            self.verificationErrors = []
    
            self.attachment = 1
            self.file_source_location = "F:\\python_test\\logfiles\\"
            self.file_move_location = "F:\\logfiles_back\\"
    
        def test_selenium_exception(self):
            driver = self.driver
            driver.get(self.base_url + "/")
            driver.find_element_by_id("gbqfq").clear()
            driver.find_element_by_id("gbqfq").send_keys("Check this out")
            if self.attachment:
                try:
                    for contents in os.listdir(self.file_source_location):
                        src_file = os.path.join(self.file_source_location, contents)
                        dst_file = os.path.join(self.file_move_location, contents)
                        shutil.move(src_file, dst_file)
                    print'files_moved_success'
                    driver.find_element_by_link_text("check out - definition of check out by the Free Online Dictionary ...").click()
                except Exception as e:
                    print e
    
        def is_element_present(self, how, what):
            try: self.driver.find_element(by=how, value=what)
            except NoSuchElementException, e: return False
            return True
    
        def tearDown(self):
            self.driver.quit()
            self.assertEqual([], self.verificationErrors)
    
    if __name__ == "__main__":
        unittest.main()
    

    In this code - If the movement from logfiles to logfiles_back fails due to reasons like wrong path ...Etc the catch block is executed and i want the selenium test case to quit reporting an error

    What is happening right now is it reports the error and completes the execution of the test case

    How to make this possible ?

  • user83969
    user83969 over 11 years
    Works like a charm - how did you get to know these ? if i should have found this in documentation or by googling - what would have been the keywords to get to this even before knowing that something called raise or sys.exit exists ?
  • RocketDonkey
    RocketDonkey over 11 years
    @user83969 Awesome, happy to hear it :)
  • RocketDonkey
    RocketDonkey over 11 years
    @user83969 Yeah, the docs will definitely have something. docs.python.org/2/reference/simple_stmts.html#raise is the raise-specific section that will give you the details. That is actually a Python-specific thing - that wouldn't have been in the Selenium docs (so no worries about not seeing it :) ). If you were to Google it, I'd look for things like 'handling exceptions in Python' to get an idea of what is happening and see what kinds of options there are in a given situation.
  • user83969
    user83969 over 11 years
    @RocketDonkwy using sys.exit(1) and executing the entire file using subprocess call from another file like theproc = subprocess.Popen("sel_except.py", shell = True).communicate() but while printing the theproc says null. Shouln't it contain 1 or false ?
  • RocketDonkey
    RocketDonkey over 11 years
    @user83969 Try checking theproc.returncode to get the exit code of the process (that is where you should find the 1 value). For more info, check out docs.python.org/2/library/subprocess.html#subprocess.Popen for all kinds of good reading material :) Hope that helps.
  • user83969
    user83969 over 11 years
    @RocketDonkwy Thanks i used check_call and it returns the status to "theproc". However when i use raise or sys.exit(code) in this place(in the child file) the parent file which issues the call subprocess.check_call also stops execution when an error occurs in the child file which is having the above shown code ! - how to deal with this ?
  • RocketDonkey
    RocketDonkey over 11 years
    @user83969 Hmm, let me think on it a bit - my experience with using subprocess is somewhat limited, but I'll see if I can find anything that may point you in the right direction.