Beispiel #1
0
def connect_to_db(data_set):
    """
    This action just stores the different database specific configs into shared variables for use by other actions.
    NOTE: The actual db connection does not happen here, connection to db is made inside the actions which require it.

    db_type         input parameter         <type of db, ex: postgres, mysql>
    db_name         input parameter         <name of db, ex: zeuz_db>
    db_user_id      input parameter         <user id of the os who have access to the db, ex: postgres>
    db_password     input parameter         <password of db, ex: mydbpass-mY1-t23z>
    db_host         input parameter         <host of db, ex: localhost, 127.0.0.1>
    db_port         input parameter         <port of db, ex: 5432 for postgres by default>
    sid         optional parameter         <sid of db, ex: 15321 for oracle by default>
    service_name         optional parameter         <service_name of db, ex: 'somename' for oracle by default>
    odbc_driver     optional parameter      <specify the odbc driver, optional, can be found from pyodbc.drivers()>
    connect to db   database action         Connect to a database

    :param data_set: Action data set
    :return: string: "passed" or "zeuz_failed" depending on the outcome
    """

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME

    try:
        for left, _, right in data_set:
            if left == DB_TYPE:
                sr.Set_Shared_Variables(DB_TYPE, right)
            if left == DB_NAME:
                sr.Set_Shared_Variables(DB_NAME, right)
            if left == DB_USER_ID:
                sr.Set_Shared_Variables(DB_USER_ID, right)
            if left == DB_PASSWORD:
                sr.Set_Shared_Variables(DB_PASSWORD, right)
            if left == DB_HOST:
                sr.Set_Shared_Variables(DB_HOST, right)
            if left == DB_PORT:
                sr.Set_Shared_Variables(DB_PORT, right)
            if left == DB_SID:
                sr.Set_Shared_Variables(DB_SID, right)
            if left == DB_SERVICE_NAME:
                sr.Set_Shared_Variables(DB_SERVICE_NAME, right)
            if left == DB_ODBC_DRIVER:
                sr.Set_Shared_Variables(DB_ODBC_DRIVER, right)

        CommonUtil.ExecLog(sModuleInfo,
                           "Trying to establish connection to the database.",
                           1)
        db_get_connection()

        return "passed"
    except Exception:
        traceback.print_exc()
        return CommonUtil.Exception_Handler(sys.exc_info())
Beispiel #2
0
def find_odbc_driver(db_type="postgresql"):
    """
    Finds the ODBC driver to work with based on the given database type
    :param db_type: type of database (e.g postgres, mysql, etc.)
    :return: name of the driver (string)
    """

    import pyodbc

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME

    db_type = db_type.lower()

    # Check to see if any ODBC driver is specified
    selected_driver = sr.Get_Shared_Variables(DB_ODBC_DRIVER, log=False)

    # If no ODBC driver is specified
    if selected_driver == "zeuz_failed":
        # Driver list for pyodbc to connect through the ODBC standard
        pyodbc_drivers = pyodbc.drivers()

        # Sort to get unicode items first
        pyodbc_drivers.sort(reverse=True, key=lambda x: "unicode" in x.lower())

        for odbc_driver in pyodbc_drivers:
            odbc_driver_lowercase = odbc_driver.lower()

            if db_type == "postgresql":
                if ("postgre" in odbc_driver_lowercase
                        and "unicode" in odbc_driver_lowercase):
                    selected_driver = odbc_driver
                    # We usually want the unicode drivers, so break once we've found it
                    break
                elif ("postgre" in odbc_driver_lowercase
                      and "ansi" in odbc_driver_lowercase):
                    selected_driver = odbc_driver
            elif db_type == "mariadb":
                # mariadb has only one type of odbc driver
                if "mariadb" in odbc_driver_lowercase:
                    selected_driver = odbc_driver
                    break
            elif db_type == "mysql":
                if ("mysql" in odbc_driver_lowercase
                        and "unicode" in odbc_driver_lowercase):
                    selected_driver = odbc_driver
                    # We usually want the unicode drivers, so break once we've found it
                    break
                elif ("mysql" in odbc_driver_lowercase
                      and "ansi" in odbc_driver_lowercase):
                    selected_driver = odbc_driver

    CommonUtil.ExecLog(sModuleInfo,
                       "[Database ODBC DRIVER]: %s" % selected_driver, 0)
    return selected_driver
def unlock_android_app(serial=""):
    """ Attempt to enter password for locked app.  It is up to the user to put proper logic to figure out if the app is password protected.  
    We will assume user have already checked that"""

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
    try:
        # Get password
        if (sr.Test_Shared_Variables("device_password") == False
            ):  # Make sure user stored password in shared variables
            CommonUtil.ExecLog(sModuleInfo,
                               "Can't unlock phone - no password specified.",
                               3)
            return "zeuz_failed"
        password = sr.Get_Shared_Variables(
            "device_password")  # Read device password from shared variables
        if serial != "":
            serial = "-s %s" % serial  # Prepare serial number with command line switch
        # Unlock app
        subprocess.check_output("adb %s shell input keyevent 82" % (serial),
                                shell=True,
                                encoding="utf-8")  # Wakeup device
        time.sleep(1)
        CommonUtil.ExecLog(sModuleInfo,
                           "Serial number of the device used - %s" % serial, 1)
        subprocess.check_output(
            "adb %s shell input text %s" % (serial, password),
            shell=True,
            encoding="utf-8",
        )  # Enter password
        time.sleep(0.5)
        subprocess.check_output(
            "adb %s shell input keyevent KEYCODE_ENTER" % serial,
            shell=True,
            encoding="utf-8",
        )  # Press ENTER key
        time.sleep(
            2)  # Give time for foreground to switch and unlock to complete
    except Exception:
        errMsg = "Unable to unlock app"
        return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
def unlock_android(serial=""):
    """ Attempt to enter password for locked phone """
    # Caveat 1: Only works if device has PIN or PASSWORD, not if they use a pattern, or pattern as a fingerprint backup
    # Caveat 2: Only works if the user connects USB and unlocks the phone. Then, if the phone is locked, we still have an ADB connection, and can work with it.

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
    try:
        lock_status = ""
        if serial != "":
            serial_with_id = "-s %s" % serial
        subprocess.check_output(
            "adb %s shell svc power stayon usb" % (serial_with_id),
            shell=True,
            encoding="utf-8",
        )  # Wakeup device
        lock_status = check_if_device_is_unlocked(serial="")
        if lock_status == True:
            CommonUtil.ExecLog(
                sModuleInfo, "Device is already unlocked. No action is needed",
                1)
            return "passed"

        # Get password
        if (sr.Test_Shared_Variables("device_password") == False
            ):  # Make sure user stored password in shared variables
            CommonUtil.ExecLog(sModuleInfo,
                               "Can't unlock phone - no password specified.",
                               3)
            return "zeuz_failed"
        password = sr.Get_Shared_Variables(
            "device_password")  # Read device password from shared variables
        # Unlock phone

        CommonUtil.ExecLog(sModuleInfo, "Attempting to unlock using adb", 1)
        subprocess.check_output(
            "adb %s shell svc power stayon usb" % (serial_with_id),
            shell=True,
            encoding="utf-8",
        )  # Wakeup device
        time.sleep(0.5)
        subprocess.check_output(
            "adb %s shell input keyevent 82" % (serial_with_id),
            shell=True,
            encoding="utf-8",
        )  # Wakeup device
        time.sleep(0.5)
        subprocess.check_output(
            "adb %s shell input keyevent 82" % (serial_with_id),
            shell=True,
            encoding="utf-8",
        )  # Wakeup device
        time.sleep(0.5)
        CommonUtil.ExecLog(
            sModuleInfo,
            "Serial number of the device used - %s" % serial_with_id, 1)
        subprocess.check_output(
            "adb %s shell input text %s" % (serial_with_id, password),
            shell=True,
            encoding="utf-8",
        )  # Enter password
        time.sleep(0.5)
        subprocess.check_output(
            "adb %s shell input keyevent KEYCODE_ENTER" % serial_with_id,
            shell=True,
            encoding="utf-8",
        )  # Press ENTER key
        time.sleep(
            2)  # Give time for foreground to switch and unlock to complete

        # Unlock phone

        lock_status = check_if_device_is_unlocked(serial)
        if lock_status == True:
            CommonUtil.ExecLog(sModuleInfo,
                               "Successfully unlocked your device", 1)
            return "passed"
        else:
            CommonUtil.ExecLog(
                sModuleInfo,
                "We could not unlock using adb, we will try with uiautomator",
                1,
            )
            Enter_Password_UIAutomator(password, serial)

            lock_status = check_if_device_is_unlocked(serial)
            if lock_status == True:
                CommonUtil.ExecLog(sModuleInfo,
                                   "Successfully unlocked your device", 1)
                return "passed"

            CommonUtil.ExecLog(sModuleInfo, "We could not unlock your device",
                               3)
            return "zeuz_failed"

    except Exception:
        errMsg = "Unable to unlock device"
        return CommonUtil.Exception_Handler(sys.exc_info(), None, errMsg)
Beispiel #5
0
def db_non_query(data_set):
    """
    This action performs a non-query (insert/update/delete) query and stores the "number of rows affected"
    in the variable <var_name>

    The result will be stored in the format: int
        value

    query                            input parameter    <query: INSERT INTO table_name(col1, col2, ...) VALUES (val1, val2, ...)>
    insert update delete query       database action    <var_name: name of the variable to store the no of rows affected>

    :param data_set: Action data set
    :return: string: "passed" or "zeuz_failed" depending on the outcome
    """

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME

    try:
        variable_name = None
        query = None

        for left, mid, right in data_set:
            if left == "query":
                # Get the query, and remove any whitespaces
                query = right.strip()

            if "action" in mid:
                variable_name = right.strip()

        if variable_name is None:
            CommonUtil.ExecLog(sModuleInfo, "Variable name must be provided.",
                               3)
            return "zeuz_failed"

        if query is None:
            CommonUtil.ExecLog(sModuleInfo, "SQL query must be provided.", 3)
            return "zeuz_failed"

        CommonUtil.ExecLog(sModuleInfo, "Executing query:\n%s." % query, 1)

        # Get db_cursor and execute
        db_con = db_get_connection()
        with db_con:
            with db_con.cursor() as db_cursor:
                db_cursor.execute(query)

                # Commit the changes
                db_con.commit()

                # Fetch the number of rows affected
                db_rows_affected = db_cursor.rowcount

                # Set the rows as a shared variable
                sr.Set_Shared_Variables(variable_name, db_rows_affected)

        db_con.close()
        CommonUtil.ExecLog(sModuleInfo,
                           "Number of rows affected: %d" % db_rows_affected, 0)
        return "passed"
    except Exception as e:
        return handle_db_exception(sModuleInfo, e)
Beispiel #6
0
def update_into_db(data_set):
    """
    This action performs a  update query and stores the "number of rows affected"
    in the variable <var_name>

    The result will be stored in the format: int
        value

    table             input parameter         <table name: test >
    columns             input parameter         <column name: name>
    values             input parameter         <column name: admin>
    where             input parameter         <where condition: name='admin'>
    update into db        database action         <var_name: name of the variable to store the result of the query>

    :param data_set: Action data set
    :return: string: "passed" or "zeuz_failed" depending on the outcome
    """

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME

    try:
        table_name = None
        query = None
        where = None
        columns = None
        values = None
        variable_name = None

        for left, mid, right in data_set:
            if "table" in left.lower():
                # Get the and query, and remove any whitespaces
                table_name = right.strip()
            if left == "where":
                where = right.strip()
            if "action" in mid:
                variable_name = right.strip()
            if "columns" in left.lower():
                columns = right.split(',')
            if "values" in left.lower():
                values = right.split(',')

        if variable_name is None:
            CommonUtil.ExecLog(sModuleInfo, "Variable name must be provided.",
                               3)
            return "zeuz_failed"

        query = "update " + table_name + " set "
        for index in range(len(columns)):
            query += columns[index] + "= "
            query += values[index] + " "
            if (index != (len(columns) - 1)):
                query += ","
        if where is not None:
            query += " where " + where

        CommonUtil.ExecLog(sModuleInfo, "Executing query:\n%s." % query, 1)

        # Get db_cursor and execute
        db_con = db_get_connection()
        with db_con:
            with db_con.cursor() as db_cursor:
                db_cursor.execute(query)
                db_con.commit()

                # Fetch the number of rows affected
                db_rows_affected = db_cursor.rowcount

                # Set the rows as a shared variable
                sr.Set_Shared_Variables(variable_name, db_rows_affected)

        db_con.close()
        CommonUtil.ExecLog(sModuleInfo,
                           "Number of rows affected: %d" % db_rows_affected, 0)
        return "passed"

    except Exception as e:
        return handle_db_exception(sModuleInfo, e)
Beispiel #7
0
def select_from_db(data_set):
    """
    This action performs a select query and stores the result of the query in the variable <var_name>
    The result will be stored in the format: list of lists
        [ [row1...], [row2...], ... ]

    table             input parameter         <table name: test >
    columns             input parameter         <column name: name,id>
    select from db        database action         <var_name: name of the variable to store the result of the query>

    :param data_set: Action data set
    :return: string: "passed" or "zeuz_failed" depending on the outcome
    """

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME

    try:
        table_name = None
        query = None
        where = None
        columns = None
        variable_name = None
        group_by = None
        order_by = None
        order = " "

        for left, mid, right in data_set:
            if "table" in left.lower():
                # Get the and query, and remove any whitespaces
                table_name = right.strip()
            if left.lower() == "where":
                where = right.strip()
            if "action" in mid.lower():
                variable_name = right.strip()
            if "group" in left.lower():
                group_by = right.split(',')
            if "order" in left.lower():
                order_by = right.split(',')

            if "columns" in left.lower():
                if right == "" or right == "*":
                    columns = ["*"]
                columns = right.split(',')

        if variable_name is None:
            CommonUtil.ExecLog(sModuleInfo, "Variable name must be provided.",
                               3)
            return "zeuz_failed"

        query = "select "
        for index in range(len(columns)):
            query += columns[index] + " "
            if (index != (len(columns) - 1)):
                query += ","

        query += "from " + table_name
        if where is not None:
            query += " where " + where

        if group_by is not None:
            query += " group by "
            for index in range(len(group_by)):
                query += group_by[index] + " "
                if (index != (len(group_by) - 1)):
                    query += ","

        if order_by is not None:
            query += " order by "
            for index in range(len(order_by)):
                query += order_by[index] + " "
                if (index != (len(order_by) - 1)):
                    query += ","

        CommonUtil.ExecLog(sModuleInfo, "Executing query:\n%s." % query, 1)

        # Get db_cursor and execute
        db_con = db_get_connection()
        with db_con:
            with db_con.cursor() as db_cursor:
                db_cursor.execute(query)
                # Commit the changes
                db_con.commit()
                # Fetch all rows and convert into list
                db_rows = []
                while True:
                    db_row = db_cursor.fetchone()
                    if not db_row:
                        break
                    db_rows.append(list(db_row))

                # Set the rows as a shared variable
                sr.Set_Shared_Variables(variable_name, db_rows)

        db_con.close()
        CommonUtil.ExecLog(
            sModuleInfo,
            "Fetched %d rows and stored into variable: %s" %
            (len(db_rows), variable_name),
            0,
        )
        return "passed"
    except Exception as e:
        return handle_db_exception(sModuleInfo, e)
Beispiel #8
0
def db_select(data_set):
    """
    This action performs a select query and stores the result of the query in the variable <var_name>
    The result will be stored in the format: list of lists
        [ [row1...], [row2...], ... ]

    query               input parameter         <query: SELECT * FROM test_cases ORDER BY tc_id ASC LIMIT 10>
    select query        database action         <var_name: name of the variable to store the result of the query>

    :param data_set: Action data set
    :return: string: "passed" or "zeuz_failed" depending on the outcome
    """

    sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME

    try:
        variable_name = None
        query = None

        for left, mid, right in data_set:
            if left == "query":
                # Get the and query, and remove any whitespaces
                query = right.strip()

            if "action" in mid:
                variable_name = right.strip()

        if variable_name is None:
            CommonUtil.ExecLog(sModuleInfo, "Variable name must be provided.",
                               3)
            return "zeuz_failed"

        if query is None:
            CommonUtil.ExecLog(sModuleInfo, "SQL query must be provided.", 3)
            return "zeuz_failed"

        CommonUtil.ExecLog(sModuleInfo, "Executing query:\n%s." % query, 1)

        # Get db_cursor and execute
        db_con = db_get_connection()
        with db_con:
            with db_con.cursor() as db_cursor:
                db_cursor.execute(query)

                # Fetch all rows and convert into list
                db_rows = []
                while True:
                    db_row = db_cursor.fetchone()
                    if not db_row:
                        break
                    db_rows.append(list(db_row))

                # Set the rows as a shared variable
                sr.Set_Shared_Variables(variable_name, db_rows)

        db_con.close()
        CommonUtil.ExecLog(
            sModuleInfo,
            "Fetched %d rows and stored into variable: %s" %
            (len(db_rows), variable_name),
            0,
        )
        return "passed"
    except Exception as e:
        return handle_db_exception(sModuleInfo, e)
Beispiel #9
0
def teardown(data_set):
    """ Cleanup automation """

    # Cleanup shared variables
    Shared_Resources.Clean_Up_Shared_Variables()
    return "passed"
Beispiel #10
0
gui.FAILSAFE = False

#########################
#                       #
#    Global Variables   #
#                       #
#########################

MODULE_NAME = inspect.getmodulename(__file__)

# Valid image positions
positions = ("left", "right", "centre", "center")

# Recall dependency, if not already set
dependency = None
if Shared_Resources.Test_Shared_Variables(
        "dependency"):  # Check if driver is already set in shared variables
    dependency = Shared_Resources.Get_Shared_Variables(
        "dependency")  # Retreive appium driver
else:
    raise ValueError("No dependency set - Cannot run")

# Recall file attachment, if not already set
file_attachment = []
if Shared_Resources.Test_Shared_Variables("file_attachment"):
    file_attachment = Shared_Resources.Get_Shared_Variables("file_attachment")

#########################
#                       #
#   Helper Functions    #
#                       #
#########################