john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

selenium phantomjs unittest check service port example

import sys
import socket
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException
import unittest, time, re


def is_valid_connection( host, port ):
    try:
        s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
        s.connect( ( host, port ) )
        s.close()
    except Exception:
        return False
    else:
        return True



class SignUpTest( unittest.TestCase ):

    def setUp( self ):
        self.driver = webdriver.PhantomJS( executable_path=phantomjs_binary, port=phantomjs_port )
        self.driver.implicitly_wait( 10 )
        self.base_url = base_url
        self.verificationErrors = []
        self.accept_next_alert = True


    def is_element_present( self, how, what ):
        try:
            self.driver.find_element( by=how, value=what )
        except NoSuchElementException, e:
            return False
        return True


    def is_alert_present( self ):
        try:
            self.driver.switch_to_alert( )
        except NoAlertPresentException, e:
            return False
        return True


    def close_alert_and_get_its_text( self ):
        try:
            alert = self.driver.switch_to_alert( )
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept( )
            else:
                alert.dismiss( )
            return alert_text
        finally:
            self.accept_next_alert = True


    def tearDown( self ):
        self.driver.delete_all_cookies( )    # important to not persist sessions between tests
        self.driver.quit( )
        self.assertEqual( [], self.verificationErrors )


    def test_sign_up( self ):
        driver = self.driver
        account_name = str( int( time.time() / 1000 ) )
        print "DEBUG: creating " + account_name
        driver.get( self.base_url + '/signup' )
        driver.find_element_by_id( 'email' ).clear( )
        driver.find_element_by_id( 'email' ).send_keys( 'user-' + account_name + '@example.com' )
        driver.find_element_by_id( 'password' ).clear( )
        driver.find_element_by_id( 'password' ).send_keys( 'mypassword' )
        driver.find_element_by_id( 'accountname' ).clear( )
        driver.find_element_by_id( 'accountname' ).send_keys( account_name )
        driver.find_element_by_id( 'signup' ).click( )
        self.assertTrue( self.is_element_present( By.NAME, 'email[0]' ) )
        self.assertTrue( self.is_element_present( By.ID, 'next' ) )


if __name__ == '__main__':

    if len( sys.argv ) != 4:
        print "usage: python {} /directory-with-binary/phantomjs  9134  server.example.com".format( sys.argv[0] )
        sys.exit( 1 )
    phantomjs_binary = sys.argv[1]        # '/tmp/phantomjs-1.9.2-linux-x86_64/bin/phantomjs'
    phantomjs_port = int( sys.argv[2] )   # 9134
    hostname = sys.argv[3]                # https://example.com
    base_url = 'https://' + hostname      # defined in main, available to the whole namespace
    del sys.argv[ 1: ]                    # since sys.argv[0] is the module name, remove everything after

    if not is_valid_connection( 'localhost', phantomjs_port ):
        print "ERROR: unable to connect to localhost on port {}".format( phantomjs_port )
        sys.exit( 1 )
    # todo check if a service is listening on phantomjs_port

    unittest.main( )


- - -

import time
import socket
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementNotVisibleException


class Util(object):

    @staticmethod
    def is_valid_connection(host, port):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(10)
            s.connect((host, port))
            s.close()
        except Exception:
            return False
        else:
            return True

    @staticmethod
    def mydebug(text, location='/tmp/crashproof.log'):
        with open(location, 'a') as f:
            f.write(str(int(time.time())) + ': ' + text + '\n')

    @staticmethod
    def assert_is_equal(a, b):
        if a != b:
            raise AssertionError(a + ' does not equal ' + b)

    @staticmethod
    def assert_ends_with(a, b):
        if not a.endswith(b):
            raise AssertionError(a + ' does not equal ' + b)

    @staticmethod
    def assert_a_contains_b(a, b):
        if not b in a:
            raise AssertionError(a + ' does not contain ' + b)

    @staticmethod
    def is_present(driver, identifier, value):
        # TODO: optimize waits by 500ms http://selenium-python.readthedocs.org/en/latest/waits.html
        # from selenium.webdriver.support import (ui.WebDriverWait, expected_conditions)
        result = True
        try:
            driver.find_element(by=identifier, value=value)
        except (NoSuchElementException, ElementNotVisibleException) as error:
            result = False
        return result
        # exists = driver.find_element(by=identifier, value=value).size() != 0

    @staticmethod
    def assert_exists(driver, identifier, value):
        try:
            element = driver.find_element(by=identifier, value=value)
        except (NoSuchElementException, ElementNotVisibleException) as error:
            raise AssertionError(identifier + ' with value: ' + value + ' not found or visible: {}'.format(error))
        return element

    @staticmethod
    def driver_quit(driver, delete_cookies=True):
        if driver:
            try:
                if delete_cookies:
                    driver.delete_all_cookies()    # important to not persist sessions between tests
                driver.quit()
            except Exception as error:
                print 'ignoring error received while quitting: {} '.format(error)

    @staticmethod
    def find_element(driver, identifier, value):
        """ raising AssertionError when an element is not found allows the test framework to mark the error
        """
        try:
            return driver.find_element(by=identifier, value=value)
        except (NoSuchElementException, ElementNotVisibleException) as error:
            raise AssertionError(identifier + ' with value: ' + value + ' not found or visible: {}'.format(error))

    @staticmethod
    def find_elements(driver, identifier, value):
        """ raising AssertionError when an element is not found allows the test framework to mark the error
        """
        try:
            return driver.find_elements(by=identifier, value=value)
        except (NoSuchElementException, ElementNotVisibleException) as error:
            raise AssertionError(identifier + ' with value: ' + value + ' not found or visible: {}'.format(error))

    @staticmethod
    def is_checked_radio(driver, identifier, identifier_target, value):
        result = False
        elements = Util.find_elements(driver, identifier, identifier_target)
        for elem in elements:
            if elem.get_attribute('value') == value:
                if elem.get_attribute('checked'):
                    result = True
        return result

    @staticmethod
    def get_table(driver, table_id, image_column_number=None):
        """ find a table if it exists on the current page
            return a list of rows (each is a list of values)
        """
        tr_web_elements = Util.find_elements(driver, 'xpath', '//table[@id="' + table_id + '"]//tr')
        rows = list()
        for tr in tr_web_elements:
            td_web_elements = tr.find_elements_by_tag_name('td')      # alternatively use th for tableheaders
            values = list()
            count = 0
            for td in td_web_elements:
                if image_column_number is not None and count == image_column_number:
                    try:
                        image = td.find_element_by_tag_name('img')
                        image_url = image.get_attribute('src')
                        values.append(image_url)
                    except Exception as error:
                        print 'img expected at table column {} , {}'.format(image_column_number, error)
                else:
                    values.append(td.text)
                count += 1
            if values:                                  # don't include a row that has no cells
                rows.append(values)
        return rows

  • « directory and file listing passworded POST webapp2
  • Screencast simple screen recorder as gif byzanz »

Published

Jun 28, 2015

Category

python

~630 words

Tags

  • check 3
  • example 36
  • phantomjs 5
  • port 10
  • python 180
  • selenium 5
  • service 12
  • unittest 12