def close_workbook(self, alias=None):
        """Closes the workbook identified by the supplied alias.
        
        If no alias is provided, the alias of the active workbook
        is used. In this case a new workbook becomes active.

        Changes made to the file won't be saved automatically.
        Use the `Save` keyword to save the changes to the file.
        """
        if not alias:
            alias = self.active_workbook_alias
        try:
            if alias == self.active_workbook_alias:
                set_new_active_workbook = True
            else:
                set_new_active_workbook = False

            self.workbooks[alias]["workbook"].close()
            self._remove_from_workbooks(alias)

            if set_new_active_workbook and len(self.workbooks) > 0:
                new_alias = self.workbooks.keys()[0]
                self._set_new_active_workbook(new_alias)

        except KeyError:
            logger.warning("Cannot close workbook with alias `{}': workbook "
                           "not opened.".format(alias))
Beispiel #2
0
 def deleteLease(self, hw_address, raise_exceptions=False):
     """
     Delete an entry in the database, from its hw_address key
     If raise_exceptions is set to True, deleting a non-existing key will raise a TypeError exception
     """
     try:
         with self.leases_dict_mutex:
             del self.leases_dict[hw_address]
     except TypeError:
         if raise_exceptions:
             raise
     except KeyError:
         logger.warning(
             'Entry for MAC address ' + hw_address +
             ' cannot be deleted because it does not exist (maybe database has been reset in the meantime)'
         )
Beispiel #3
0
    def sup_l2_config_trunk(node, interface, trunk_list=[]):
        oper = 'edit'
        tmp = config_ipc_data()
        tmp.set_oper(oper)
        tmp.set_config_member('configStructName', 'vlan')
        tmp.set_config_member('interface_name', "{}".format(interface))
        tmp.set_config_member('access_vlanid', 0)
        tmp.set_config_level_structName('interface')
        tmp.set_config_level_member('ifname', "{}".format(interface))
        trunk_list = json.loads(trunk_list)
        MIN_VLAN_ID = 1
        MAX_VLAN_ID = 4094
        bitmap = [0] * 512
        if trunk_list and len(trunk_list) > 0:
            for i in range(0, len(trunk_list)):
                element = trunk_list[i]
                list = element.split("-")
                if list and len(list) == 1:
                    min_vlanid = int(str(list[0]))
                    max_vlanid = min_vlanid
                elif list and len(list) == 2:
                    min_vlanid = int(str(list[0]))
                    max_vlanid = int(str(list[1]))
                else:
                    logger.warning(
                        "vlan_type is {}, vlanid_range input error ".format(
                            vlan_type))
                    raise Exception(
                        "vlan_type is {}, vlanid_range input error ".format(
                            vlan_type))

                if min_vlanid < MIN_VLAN_ID \
                        or max_vlanid > MAX_VLAN_ID \
                        or min_vlanid > max_vlanid:
                    logger.warning(
                        "vlanid_range input error ,please input {}-{}".format(
                            MIN_VLAN_ID, MAX_VLAN_ID))
                    raise Exception(
                        "vlanid_range input error ,please input {}-{}".format(
                            MIN_VLAN_ID, MAX_VLAN_ID))

                for ele in range(min_vlanid, max_vlanid + 1):
                    mask = 0x1 << (ele % 8)
                    bitmap[(ele / 8)] |= mask
        tmp.set_config_member('vlan_bitmap', bitmap)
        data = tmp.get_data()
        msg = config_ipc.config_api(node, data)
    def read_sheet_data(self,
                        column_names=None,
                        get_column_names_from_header_row=False,
                        cell_range=None,
                        trim=False):
        """Reads all the data from the active sheet.

        This keyword can output the sheet data in two formats:
            - _As a list of dictionaries_. In the case column names are
            supplied or obtained (see relevant parameters described below),
            the rows will be represented through dictionaries, of which the
            keys will correspond to the column names.
            - _As a list of lists_. If no column names are provided or
            obtained, each row will be read from the sheet as a list, and
            the returned data will, therefore, be a list of all such lists.

        To use column names the following two parameters can be used:

        - If ``column_names`` is provided it is expected to be a list which will
        be used to name the columns in the supplied order.

        - If ``get_column_names_from_header_row`` is ``True``, the column names
        will be read from the first row in the sheet. In this case, the first row
        will not be read as part of the sheet data.

        _NOTE_: If both parameters are supplied, the `column_names`` list
        will have precedence. You will get a warning in your log when this
        situation occurs though.

        Use ``cell_range`` if you want to get data from only that range in the
        sheet, rather than all of the data in it. The expected input form is in
        _A1 Notation_. For example: ``A1:B3``.

        If ``trim`` is ``True``, all cell values are trimmed, i.e. the
        surrounding whitespace is removed.

        Examples:

        |  Read entire sheet with column names from header row  |  |                                 |                 |
        |  Open workbook   |  ${PROPER EXCEL FILE}  |  # no alias provided: defaulting to file path  |                 |
        |  Switch sheet    |  Sheet 1 (with header) |                                                |                 |
        |  @{data sheet}=  |  Read sheet data       |  get_column_names_from_header_row=${TRUE}      |                 |
        |  :FOR            |  ${row}                |  IN                                            |  @{data sheet}  |
        |  \               |  Log list              |  ${row}                                        |                 |
        |  Close workbook  |  ${PROPER EXCEL FILE}  |                                                |                 |

        |  Read sheet range without column names (trimmed) | |                |                 |
        |  Open workbook   |  ${PROPER EXCEL FILE}  |  first excel file       |                 |
        |  Switch sheet    |  Sheet 1 (with header) |                         |                 |
        |  @{data sheet}=  |  Read sheet data       |  cell_range=A1:B3       |  trim=${TRUE}   |
        |  :FOR            |  ${row}                |  IN                     |  @{data sheet}  |
        |  \               |  Log dictionary        |  ${row}                 |                 |
        |  Close workbook  |                        |                         |                 |
    
        For more examples check out the included test suite.
        """
        sheet = self.active_workbook.active
        skip_first_row = False

        if get_column_names_from_header_row:
            if column_names:
                logger.warning("Both the `column_names' and "
                               "`get_column_names_from_header_row' "
                               "parameters were supplied. Using "
                               "`column_names' and ignoring the other.")
            else:
                skip_first_row = True
                column_names = self._get_column_names_from_header_row(sheet)

        if cell_range:
            min_col, min_row, max_col, max_row = range_boundaries(cell_range)
            row_iterator = sheet.iter_rows(min_col=min_col,
                                           min_row=min_row,
                                           max_col=max_col,
                                           max_row=max_row)
            if column_names:
                column_names = column_names[min_col - 1:max_col]
        else:
            row_iterator = sheet.iter_rows()

        if skip_first_row:
            next(row_iterator)  # Skip first row in the case of a header.

        if column_names:
            sheet_data = []
            for row in row_iterator:
                row_data = {}
                for i, cell in enumerate(row):
                    try:
                        row_data[column_names[i]] =\
                        self.read_from_cell(None, cell_obj=cell, trim=trim)
                    except IndexError:
                        raise TooFewColumnNamesSuppliedException

                if not all(value is None for value in row_data.itervalues()):
                    sheet_data.append(row_data)
        else:
            sheet_data = []
            for row in row_iterator:
                row_data = [
                    self.read_from_cell(None, cell_obj=cell, trim=trim)
                    for cell in row
                ]
                if not all(value is None for value in row_data):
                    sheet_data.append(row_data)

        return sheet_data
    def ccServerCheck(self,
                      uri,
                      checkHeaders={},
                      checkMeth="GET",
                      checkVer="1.1",
                      checkMode="strict",
                      checkFile=reqLogPath):
        logger.info("------------- start %s ----------*****>>>" %
                    sys._getframe().f_code.co_name)
        # logger.info("------- %s ------"%type(checkHeaders))
        robotDictType = types.DictType
        if 'DotDict' in dir(robot.utils):
            robotDictType = robot.utils.dotdict.DotDict
        headerTypes = (types.DictType, types.ListType, types.StringType,
                       types.UnicodeType, types.NoneType, robotDictType)
        uriTypes = (types.StringType, types.UnicodeType)
        otherTypes = (types.StringType, types.UnicodeType, types.NoneType)
        if type(checkHeaders) not in headerTypes:
            logger.error(
                "Type of checkHeaders [%s] not in [%s], Return -1 ..." %
                (type(checkHeaders), headerTypes))
            # logger.error(checkHeaders)
            return -1
        if (type(uri) not in uriTypes):
            logger.error("Type of uri [%s] not in [%s], Return -2 ..." %
                         (type(uri), uriTypes))
            return -2
        if (type(checkMeth) not in otherTypes) or (
                type(checkVer) not in otherTypes) or (type(checkMode)
                                                      not in otherTypes):
            logger.error("Type of others [%s,%s,%s] not in [%s], Return -3 ..." \
                         % (type(checkMeth), type(checkVer), type(checkMode), otherTypes))
            return -3
        ### 便于使用,不再检查内存,每次check都读取请求日志文件,以保证请求记录都是最新的最全的
        # if self.reqSplitList==[]:
        res = self.split_requests_file(checkFile)
        if not res:
            logger.error("Split reqFile [%s] Failed, Return -4 ..." %
                         checkFile)
            return -4
        ###
        checkCount = 0
        if os.stat(checkFile).st_size == 0:
            logger.info("No request in reqLogFile: [%s], Return -5 ..." %
                        checkFile)
            return -5
        for i in range(len(self.reqSplitList)):
            checkReqLine = self.reqSplitList[i].split("\r\n")[0]
            if not self.reqSplitList[i] or uri not in checkReqLine:
                logger.info("uri [%s] not in reqSplitList[%s] [%s]" %
                            (uri, i, self.reqSplitList[i]))
                continue
            dictPerReq = self._ccBytesToHttpRespone(self.reqSplitList[i])
            if uri == dictPerReq["uri"]:
                if checkMeth and checkMeth != dictPerReq["meth"]:
                    logger.warning("Uri matched, but CheckMeth [%s] Failed in reqSplitList[%s] [%s]" \
                                   % (checkMeth, i, checkReqLine))
                    continue
                if checkVer and "HTTP/" + checkVer != dictPerReq["ver"]:
                    logger.warning("Uri matched, but CheckVer [%s] Failed in reqSplitList[%s] [%s]" \
                                   % ("HTTP/" + checkVer, i, checkReqLine))
                    continue
                if not checkHeaders:
                    logger.warning(
                        "All matched, CheckHeaders [%s] no check, reqLine [%s] checked Succeed in reqSplitList[%s] [%s]" \
                        % (checkHeaders, checkReqLine, i, self.reqSplitList[i]))
                    checkCount += 1
                    continue
                if isinstance(checkHeaders, dict) or isinstance(
                        checkHeaders, robotDictType):
                    checkRes = self._ccHeadersDictCheck(
                        checkHeaders, dictPerReq["headers"], checkMode)
                elif isinstance(checkHeaders, list):
                    checkRes = self._ccHeadersListCheck(
                        checkHeaders, self.reqSplitList[i], checkMode)
                else:
                    checkRes = self._ccHeadersStrCheck(checkHeaders,
                                                       self.reqSplitList[i],
                                                       checkMode)

                if checkRes:
                    logger.info("All matched, [%s,%s,%s,%s] checked Succeed in reqSplitList[%s] [%s]" \
                                % (uri, checkHeaders, checkMeth, checkVer, i, self.reqSplitList[i]))
                    checkCount += 1
                else:
                    logger.info("CheckHeaders Failed, [%s] checked Failed in reqSplitList[%s] [%s]" \
                                % (checkHeaders, i, self.reqSplitList[i]))
        return checkCount
Beispiel #6
0
=============

robotframework keywords and utilities for Drupal testings
"""

import pkg_resources
from robot.api import logger

from .drupalkeywords import DrupalKeywords

# PEP 396 style version marker
try:
    __version__ = pkg_resources.get_distribution(
        u'robotframework-drupallibrary').version
except:
    logger.warning("Could not get the package version from pkg_resources")
    __version__ = 'unknown'


class DrupalLibrary(DrupalKeywords):
    """=== DrupalLibrary, ATDD testing friend for Drupal sites ===

    Setting up a Drupal site using directly *Selenium2Library* may be a
    hassle.  *DrupalLibrary* provides a set of keyworks for testing Drupal 7
    based sites.

    === About exit_on-failure parameter ===

    You can notice that several keywords like `Sign In` and several others
    take an optional argument named `exit_on_failure` that's ${true} by
    default.
DrupalLibrary
=============

robotframework keywords and utilities for Drupal testings
"""

import pkg_resources
from robot.api import logger

from .drupalkeywords import DrupalKeywords

# PEP 396 style version marker
try:
    __version__ = pkg_resources.get_distribution(u'robotframework-drupallibrary').version
except:
    logger.warning("Could not get the package version from pkg_resources")
    __version__ = 'unknown'


class DrupalLibrary(DrupalKeywords):
    """=== DrupalLibrary, ATDD testing friend for Drupal sites ===

    Setting up a Drupal site using directly *Selenium2Library* may be a
    hassle.  *DrupalLibrary* provides a set of keyworks for testing Drupal 7
    based sites.

    === About exit_on-failure parameter ===

    You can notice that several keywords like `Sign In` and several others
    take an optional argument named `exit_on_failure` that's ${true} by
    default.