class ChromeDriverObject(object): def __init__(self): self.ut = Utility() self.log = Logger() # Set chromedriver path # Pass the option 'headless' if it is needed to run chrome in headless # configuration def set_chromedriver_object(self, chromeArgs): try: chromeArgs = chromeArgs chromeOptions = webdriver.ChromeOptions() driver_path = self.ut.get_driver_path('/dependencies/dir_chromedriver/chromedriver') self.ut.set_executable_permission(driver_path) self.log.log_info("Setting executable permission to the chrome binary") self.log.log_info("Setting path of chromedriver") if not chromeArgs: driver = webdriver.Chrome(executable_path=driver_path) else: while '' in chromeArgs: chromeArgs.remove('') for val in chromeArgs: chromeOptions.add_argument(val) driver = webdriver.Chrome(executable_path=driver_path, options=chromeOptions) self.log.log_info("Path for chrome binary is set") return driver except WebDriverException as e: self.log.log_error("There is an exception in the Web Driver configuration") self.log.log_error(e)
class GeckoDriverObject(object): def __init__(self): self.ut = Utility() self.log = Logger() # Set geckodriver path # Pass the option 'headless' if it is needed to run gecko in headless # configuration def set_geckodriver_object(self, geckoArgs=None): try: geckoArgs = geckoArgs firefoxOptions = Options() driver_path = self.ut.get_driver_path( '/dependencies/dir_geckodriver/geckodriver') self.log.log_info("Setting path of geckodriver") if not geckoArgs: driver = webdriver.Firefox(executable_path=driver_path) else: while '' in geckoArgs: geckoArgs.remove() for val in geckoArgs: firefoxOptions.add_argument(val) driver = webdriver.Firefox(executable_path=driver_path, firefox_options=firefoxOptions) return driver except WebDriverException as e: self.log.log_error( "There is an exception in the Web Driver configuration") self.log.log_error(e)
class OperaDriverObject(object): def __init__(self): self.ut = Utility() self.ot = OS_type() self.log = Logger() # Set opera odriver path # Pass the option 'headless' if it is needed to run gecko in headless # configuration def set_operadriver_object(self): try: os_type = self.ot.os_name() driver = None if os_type == "macos": driver_path = self.ut.get_driver_path('/dependencies/dir_operadriver/operadriver_mac64/operadriver') self.ut.set_executable_permission(driver_path) self.log.log_info("Setting path of operadriver") driver = webdriver.Opera(executable_path=driver_path) self.log.log_info("Path for opera binary is set") if os_type == "linux": driver_path = self.ut.get_driver_path('/dependencies/dir_operadriver/operadriver_linux64/operadriver') self.ut.set_executable_permission(driver_path) self.log.log_info("Setting path of operadriver") driver = webdriver.Opera(executable_path=driver_path) self.log.log_info("Path for opera binary is set") return driver except WebDriverException as e: self.log.log_error("There is an exception in the Web Driver configuration") self.log.log_error(e)
class RemotechromedriverObject(object): def __init__(self): self.log = Logger() def set_remote_chromedriver_object(self, com_exec): try: chromedriver = webdriver.Remote( command_executor=com_exec, desired_capabilities=DesiredCapabilities.CHROME) self.log.log_info("Remote chromedriver configuration successful") return chromedriver except WebDriverException as e: self.log.log_error( "There is an exception in the WebDriver configuration") self.log.log_error(e)
class PhantomDriverObject(object): def __init__(self): self.ut = Utility() self.log = Logger() # Set chromedriver path # Pass the option 'headless' if it is needed to run chrome in headless # configuration def set_phantomdriver_object(self): try: driver_path = self.ut.get_driver_path('/dependencies/dir_phantomjsdriver/phantomjsdriver/bin/phantomjs') self.ut.set_executable_permission(driver_path) self.log.log_info("Setting executable permission to the phantom binary") driver = webdriver.PhantomJS(executable_path=driver_path) self.log.log_info("Path for phantom binary is set") return driver except WebDriverException as e: self.log.log_error("There is an exception in the Web Driver configuration")
class RemotephantomdriverObject(object): def __init__(self): self.log = Logger() def set_remote_phantomdriver_object(self, com_exec, capabilities): try: phantomdriver = webdriver.Remote( command_executor=com_exec, # desired_capabilities={ # 'waitForReady': True, # 'applicationType': 'Web', # 'takesScreenshot': False, # 'reuseExistingSession': True # } desired_capabilities=capabilities) self.log.log_info("Remote geckodriver configuration successful") return phantomdriver except WebDriverException as e: self.log.log_error( "There is an exception in the WebDriver configuration") self.log.log_error(e)
class SafariDriverObject(object): def __init__(self): self.log = Logger() self.ut = Utility() self.ot = OS_type() # Get the executable binary path for safari from the config.ini file def set_safaridriver_object(self): try: os_environ = self.ot.os_name() if os_environ == "linux": self.log.log_error( "Safari is not supported in Linux based operating system") if os_environ == "macos": driver = webdriver.Safari() self.log.log_info("Starting safari services") return driver except WebDriverException as e: self.log.log_error( "There is an exception in the Web Driver configuration") self.log.log_error(e)
class Utility(object): def __init__(self): self.log = Logger() # This method would get the required path for the directory or a file. # This would generate the absolute path to the required directory and the file def get_path(self, path_param): try: requiredPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), path_param) return requiredPath except IOError as e: self.log.log_error("Required Directory / File not found") self.log.log_error(e) # This method would get the required configuration from the config.ini file # and ould return the parser object which can be utilised as required. def config_reader(self): parser = SafeConfigParser() parser.read(self.get_path('../configurations/downloader_config.ini')) return parser # This method would download the required binaries and packages required # for the respective browser def driver_downloader(self, api_url, dir_path): try: request_api = requests.get(api_url, stream=True) if request_api.status_code == 200: wget.download(api_url, out=dir_path) else: request_api.raise_for_status() except requests.exceptions.Timeout: self.log.log_error("Request time out encountered") except requests.exceptions.TooManyRedirects: self.log.log_error("Too many redirects encountered") except requests.exceptions.HTTPError as e: self.log.log_error(e) sys.exit(1) # This method would parse the required json object and would return back # the required JSON from where we can extract the required information. def api_parser(self, api_url): try: response = None request_api = requests.get(api_url) if request_api.status_code == 200: request = requests.get(api_url) response = request.json() return response else: request.raise_for_status() except requests.exceptions.Timeout: self.log.log_error("Request time out encountered") except requests.exceptions.TooManyRedirects: self.log.log_error("Too many redirects encountered") except requests.exceptions.HTTPError: self.log.log_error("HTTP error encountered") sys.exit(1) # Get the required download URLs from the API data based on the operating system type def get_api_data(self, api_url): linux = None mac = None env = {} api_response = self.api_parser(api_url) for ent in api_response['assets']: if "_linux64" in ent['browser_download_url']: linux = ent['browser_download_url'] if "_mac64" in ent['browser_download_url']: mac = ent['browser_download_url'] if "linux32.tar.gz" in ent['browser_download_url']: linux = ent['browser_download_url'] if "linux64.tar.gz" in ent['browser_download_url']: linux = ent['browser_download_url'] if "macos.tar.gz" in ent['browser_download_url']: mac = ent['browser_download_url'] env = {"linux": linux, "mac": mac} return env # Unzip the required .zip package based on the path of the zip file. def unzip_file(self, dir_path): try: zipFile_path = Utility.get_driver_path('/dependencies/' + dir_path) file_info = os.listdir(zipFile_path) sleep(2) for i in file_info: with ZipFile(zipFile_path + i, 'r') as zipfile: zipfile.extractall(zipFile_path) zipfile.close() except OSError: self.log.log_error("File / Directory " + dir_path + "not found") # Unzip the required .gzip package based on the path of the gzip file. def untar_file(self, dir_path): try: tarFile_path = Utility.get_driver_path('/dependencies/' + dir_path) file_info = os.listdir(tarFile_path) sleep(2) for fname in file_info: tar = tarfile.open(tarFile_path + fname, "r:gz") tar.extractall(tarFile_path) tar.close() except OSError: self.log.log_error("File / Directory " + dir_path + "not found") # Rename the required directory def rename_dir(self, dir_path): try: dir_path = Utility.get_driver_path('/dependencies/' + dir_path) file_info = os.listdir(dir_path) os.rename(dir_path + file_info[1], dir_path + 'phantomjsdriver') except OSError: self.log.log_error("File / Directory " + dir_path + "not found") # Delete the contents of the directory when updating a package def delete_dir_contents(self, dir_content_directory): dep_tree = Utility.get_driver_path('/dependencies/' + dir_content_directory) try: for item in os.listdir(dep_tree): if item.endswith(".zip"): os.remove(dep_tree + item) elif os.path.isdir(dep_tree + item): shutil.rmtree(dep_tree + item) else: os.remove(dep_tree + item) except OSError: self.log.log_error("File / Directory " + dir_content_directory + "not found") # Checkpoint to verify driver is there in the directory before updating the driver binary def check_directory_content(self, file_dir_path): if not os.path.exists(Utility.get_driver_path(file_dir_path)): self.log.log_warning( "You cannot update the respective driver binary first without downloading it" ) sys.exit(0) else: pass # Get the current time stamp @staticmethod def get_current_time_stamp(): curr_timestamp = str(datetime.now()) return curr_timestamp # Print the required message @staticmethod def log_message(log_type, log_message): time_stamp = Utility.get_current_time_stamp() log_message = "[" + time_stamp + "]: " + "[" + log_type + "] - " + log_message print(log_message) # Get the path for the drivers @staticmethod def get_driver_path(path): driver_path = "/usr/local/bin" + path return driver_path # Set executable permission for drivers @staticmethod def set_executable_permission(driver_path): st = os.stat(driver_path) os.chmod(driver_path, st.st_mode | stat.S_IEXEC) # Delete driver executables from /usr/local/bin def delete_driver_history(self): rel_dir_path = Utility.get_driver_path("/dependencies") if not os.path.exists(rel_dir_path): self.log.log_error("Driver directory does not exist") else: shutil.rmtree(rel_dir_path, ignore_errors=True) self.log.log_info("Deleted driver directory from /usr/local/bin") # return json data @staticmethod def json_file_reader(file_path): with open(file_path) as data_file: json_data = json.loads(data_file) return json_data
class TestChrome(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) self.utility = Utility_object() self.log = Logger() def parseJSONChrome(self): dict_data = {} jsonData = self.utility.json_file_reader() for item in jsonData['assets']: dict_data = { "url": item['chromedriver']['url'], "release_version": item['chromedriver']['release_version'], "mac_v_64": item['chromedriver']['mac_v_64'], "linux_v_64": item['chromedriver']['linux_v_64'] } return dict_data def testChromeDriverMac(self): _data = self.parseJSONChrome() _releaseVersionAPI = _data.get('release_version') _releaseVersion = "" response = requests.get(_releaseVersionAPI) try: if response.status_code == 200: _releaseVersion = response.text except requests.exceptions.Timeout: self.log.log_error("Request time out") except requests.exceptions.TooManyRedirects: self.log.log_error("Too many redirects") except requests.exceptions.RequestException as e: self.log.log_error(e) _url = _data.get('url') _mac_bin = _data.get('mac_v_64') # API url _apiURLBuilder = _url + _releaseVersion + "/" + _mac_bin # Download file try: _url = requests.get(_apiURLBuilder) if _url.status_code == 200: wget.download(_apiURLBuilder) self.log.log_info( "Binary for chromedriver downloaded for macOS") except requests.exceptions.Timeout: self.log.log_error("Request time out") except requests.exceptions.TooManyRedirects: self.log.log_error("Too many redirects") except requests.exceptions.RequestException as e: self.log.log_error(e) # Assert for file exists self.assertTrue(os.path.exists('chromedriver_mac64.zip')) self.log.log_info("Required path for binary exist") # Delete file self.utility.delete_file("chromedriver_mac64.zip") self.log.log_info("Downloaded binaries deleted") def testChromeDriverLinux(self): _data = self.parseJSONChrome() _releaseVersionAPI = _data.get('release_version') _releaseVersion = "" response = requests.get(_releaseVersionAPI) try: if response.status_code == 200: _releaseVersion = response.text except requests.exceptions.Timeout: self.log.log_error("Request time out") except requests.exceptions.TooManyRedirects: self.log.log_error("Too many redirects") except requests.exceptions.RequestException as e: self.log.log_error(e) _url = _data.get('url') _linux_bin = _data.get('linux_v_64') # API url _apiURLBuilder = _url + _releaseVersion + "/" + _linux_bin # Download file try: _url = requests.get(_apiURLBuilder) if _url.status_code == 200: wget.download(_apiURLBuilder) self.log.log_info( "Binary for chromedriver downloaded for Linux") except requests.exceptions.Timeout: self.log.log_error("Request time out") except requests.exceptions.TooManyRedirects: self.log.log_error("Too many redirects") except requests.exceptions.RequestException as e: self.log.log_error(e) # Assert for file exists self.assertTrue(os.path.exists('chromedriver_linux64.zip')) self.log.log_info("Required path for binary exist") # Delete file self.utility.delete_file("chromedriver_linux64.zip") self.log.log_info("Deleted respective binary")
class TestOpera(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) self.utility = Utility_object() self.log = Logger() @classmethod def parse_json(self, api): response = requests.get(api) if response.status_code == 200: data = response.json() return data['browser_download_url'] def parseJSONOpera(self): dict_data = {} jsonData = self.utility.json_file_reader() for item in jsonData['assets']: dict_data = { "mac": item['operadriver']['mac_v_64'], "linux": item['operadriver']['linux_v_64'] } return dict_data def testOperaDriverMac(self): driverAPI = self.parseJSONOpera() data = driverAPI.get('mac') download_url = self.parse_json(data) # Check response code _response = requests.get(download_url) if _response.status_code == 200: wget.download(download_url) self.log.log_info("Binary downloaded for mac") else: self.log.log_error("Connection error") raise requests.exceptions.ConnectionError("Connection error") # Assert for file exists self.assertTrue(os.path.exists('operadriver_mac64.zip')) self.log.log_info("Path for binary file exist") # Delete file self.utility.delete_file("operadriver_mac64.zip") self.log.log_info("Binary files deleted") def testOperaDriverLinux(self): driverAPI = self.parseJSONOpera() data = driverAPI.get('linux') download_url = self.parse_json(data) # Check response code _response = requests.get(download_url) if _response.status_code == 200: wget.download(download_url) self.log.log_info("Binary files downloaded") else: self.log.log_error("Connection error") raise requests.exceptions.ConnectionError("Connection error") # Assert for file exists self.assertTrue( os.path.exists('../TestFunction/operadriver_linux64.zip')) self.log.log_info("Path for binary file exist") # Delete file self.utility.delete_file("operadriver_linux64.zip") self.log.log_info("Binary files deleted")