def test_nuvlabox_infra(request):
    isg_id = request.config.cache.get('nuvlabox_isg_id', '')

    # check IS
    err = "Unable to validate the NuvlaBox's infrastructure-service"
    with timeout(300, err):
        search_filter = f'parent="{isg_id}" and subtype="swarm"'
        print('Searching for NuvlaBox infrastructure-service: ' + search_filter)
        while True:
            infras = nuvla.api.search('infrastructure-service',
                                    filter=search_filter)

            if infras.count == 0:
                time.sleep(2)
                continue

            infra = infras.resources[0].data
            if infra.get('endpoint').startswith('https://10.'):
                break
            else:
                time.sleep(2)

    cred_subtype = "infrastructure-service-swarm"
    query = f'parent="{infra["id"]}" and subtype="{cred_subtype}"'
    nb_credential = nuvla.api.search('credential', filter=query)
    assert nb_credential.count == 1, \
        f'Cannot find credential for NuvlaBox in {nuvla.api.endpoint}, with query: {query}'

    request.config.cache.set('infra_service', infra)
    request.config.cache.set('nuvlabox_credential', nb_credential.resources[0].data)
    print(f'::set-nuvlabox_credential_id{nb_credential.resources[0].data["id"]}::set-nuvlabox_credential_id')

    credential = nb_credential.resources[0].data
    if credential.get('status', '') != "VALID":
        r = nuvla.api.get(credential['id'] + "/check")
        assert r.data.get('status') == 202, \
            f'Failed to create job to check credential {credential["id"]}'

        with timeout(30, f"Unable to check NuvlaBox's credential for the compute infrastructure"):
            while True:
                j_status = nuvla.api.get(r.data.get('location'))
                if j_status.data['progress'] < 100:
                    time.sleep(1)
                    continue

                assert j_status.data['state'] == 'SUCCESS', \
                    f'Failed to perform credential check. Reason: {j_status.data.get("status-message")}'

                break

        credential = nuvla.api.get(credential['id'])
        assert credential.data['status'] == 'VALID', \
            f'The NuvlaBox compute credential is invalid'
示例#2
0
文件: ssh.py 项目: gbaufake/cf-ui
    def execute_command(self, command, time_to_wait=30):
        ssh_result = {}

        self.web_session.logger.info(
            'Execute command \"{}\" on IP \"{}\".'.format(command, self.ip))

        try:
            stdin, stdout, stderr = self.ssh.exec_command(command)

            with timeout(time_to_wait):
                while not stdout.channel.exit_status_ready():
                    self.web_session.logger.debug(
                        'Exit status not ready after command execute: {}'.
                        format(command))
                    ui_utils(self.web_session).sleep(1)

            if stdout.channel.exit_status == 0:
                ssh_result['output'] = stdout.read()
            else:
                ssh_result['output'] = stderr.read()

            ssh_result['result'] = stdout.channel.exit_status

        except Exception, e:
            self.web_session.logger.error(
                'Failed to execute command \"{}\" on IP \"{}\".'.format(
                    command, self.ip))
            ssh_result['output'] = e
            ssh_result['result'] = -1
 def wait_until_element_displayed(self, element, waitTime):
     with timeout(waitTime, error_message="Timed out waiting for element to be displayed."):
         while True:
             if element.is_displayed():
                 break;
             time.sleep(1)
     return True
示例#4
0
    def get(self,
            url,
            wait_for,
            dissapear=False,
            wait_seconds=None,
            dont_assert=False):
        files_utils.counter += 1
        self.web_session.logger.info("Navigate to URL {}".format(url))

        if "True" in self.web_session.DEBUG:
            files_utils.createScreenshot(self.web_session, "get-URL")

        if wait_seconds:
            secs = int(wait_seconds)
        else:
            secs = int(self.web_session.WAIT_LONG)
        with timeout(seconds=int(self.web_session.WAIT_LONG),
                     error_message="Timed Navigating \"{}\"".format(url)):
            while True:
                try:
                    self.web_driver.get(url)
                    if dissapear:
                        if (dont_assert):
                            self.ui_utils.waitForTextOnPage(
                                wait_for,
                                int(secs)), "Failed to find text '{}'".format(
                                    wait_for)
                        else:
                            assert self.ui_utils.waitForTextOnPage(
                                wait_for,
                                int(secs)), "Failed to find text '{}'".format(
                                    wait_for)
                    else:
                        if (dont_assert):
                            self.ui_utils.waitForTextOnPage(
                                wait_for,
                                secs), "Failed to find text '{}'".format(
                                    wait_for)
                        else:
                            assert self.ui_utils.waitForTextOnPage(
                                wait_for,
                                secs), "Failed to find text '{}'".format(
                                    wait_for)

                    #self.web_session.logger.info("navigated")
                    self.ui_utils.closePossibleModalDialog()
                    break
                except:
                    if self.ui_utils.isTextOnPage(
                            "sorry, but something went wrong"
                    ) or self.ui_utils.isTextOnPage(
                            "The server is temporarily unable"):
                        self.web_session.logger.info(
                            'Encountered "Sorry" message.')
                        self.ui_utils.sleep(5)
                        pass
                    else:
                        self.web_session.logger.error('Failed URL navigation')
                        raise
示例#5
0
    def wait_until_element_displayed(self, element, waitTime):

        with timeout(waitTime, error_message="Timed out waiting for element to be displayed."):
            while True:
                if element.is_displayed():
                    break;
                time.sleep(1)

        return True
示例#6
0
    def eap_power_stop(self):
        pid = None

        power = self.power_stop

        # Find an EAP in 'start state'
        # Get EAP pid (should be a pid)
        # Stop EAP
        # Validate that no pid (EAP has stopped)

        eap_hawk = self.find_eap_in_state(power.get('start_state'), check_if_resolvable_hostname=True)
        pytest.skip("No EAP with Resolvable Hostname found.")

        eap_hostname = eap_hawk.get("details").get("Hostname")
        ssh_ = ssh(self.web_session, eap_hostname)
        # assert ssh_.get_pid(eap_app) != None, "No EAP pid found."

        self.eap_power_action(power, eap_hawk)
        with timeout(15, error_message="Timeout waiting for EAP Standalone server to Stop on host: {}".format(eap_hostname)):
            while True:
                if ssh_.get_pid('standalone.sh') == None:
                    break

        # Validate eap server state on Summary Page in MIQ UI

        if self.appliance_version == self.MIQ_BASE_VERSION:
            self.web_session.logger.info("Verify IN UI")
            self.verify_eap_status_in_ui(eap_hawk, "Down")

        # Start EAP Standalone server, as to leave the EAP server in the starting state

        assert self.start_eap_standalone_server(eap_hawk)

        with timeout(15, error_message="Timeout waiting for EAP Standalone server to Start on host: {}".format(eap_hostname)):
            while True:
                if ssh_.get_pid('standalone.sh') != None:
                    break

        # Validate eap server state on Summary Page in MIQ UI

        if self.appliance_version == self.MIQ_BASE_VERSION:
            self.verify_eap_status_in_ui(eap_hawk, "Running")

        return True
示例#7
0
 def click_save_button(self):
     with timeout(seconds=15, error_message="Timed out waiting for Save."):
         while True:
             try:
                 self.web_driver.find_element_by_id('save').click()
                 break
             except:
                 # self.web_session.logger.debug("Settings Save Failed")
                 self.ui_utils.sleep(1)
                 pass
示例#8
0
 def click_save_button(self):
     with timeout(seconds=15, error_message="Timed out waiting for Save."):
         while True:
             try:
                 self.web_driver.find_element_by_id('save').click()
                 break
             except:
                 # self.web_session.logger.debug("Settings Save Failed")
                 self.ui_utils.sleep(1)
                 pass
示例#9
0
 def wait_for_icon_present(self, view_icon):
     with timeout(seconds=15, error_message="Failed to locate {} icon".format(view_icon)):
         while True:
             try:
                 self.web_driver.find_element_by_id(view_icon).is_displayed
                 break
             except:
                 self.web_session.logger.debug("{} Not Displayed".format(view_icon))
                 self.ui_utils.sleep(1)
                 pass
示例#10
0
def test_timeout_success():
    """Test function doesn't time out prematurely."""

    def test_func(a, b, c=None):
        assert (a, b, c) == (1, 2, 3)
        gevent.sleep(1)

    timeout_factory = timeout(10)
    wrapped_func = timeout_factory(test_func)
    wrapped_func(1, 2, c=3)
示例#11
0
def assert_download_exist(file, waitTime=15):
    with timeout(
            waitTime,
            error_message="Timed out waiting for Download file: {}".format(
                file)):
        while True:
            r = glob.glob(file)
            if fnmatch.filter(r, file):
                break

            time.sleep(1)
示例#12
0
def test_timeout_exception():
    """Test function times out properly."""

    def test_func(a, b, c=None):
        assert (a, b, c) == (1, 2, 3)
        gevent.sleep(10)

    timeout_factory = timeout(1)
    wrapped_func = timeout_factory(test_func)
    with pytest.raises(TimeoutException):
        wrapped_func(1, 2, c=3)
示例#13
0
 def wait_for_icon_present(self, view_icon):
     with timeout(
             seconds=15,
             error_message="Failed to locate {} icon".format(view_icon)):
         while True:
             try:
                 self.web_driver.find_element_by_id(view_icon).is_displayed
                 break
             except:
                 self.web_session.logger.debug(
                     "{} Not Displayed".format(view_icon))
                 self.ui_utils.sleep(1)
                 pass
示例#14
0
def test_nuvlabox_is_commissioned(request):
    nuvlabox_id = os.environ.get('NUVLABOX_ID')
    error_msg = f'Waiting for NB {nuvlabox_id} to get COMMISSIONED'

    with timeout(300, error_msg):
        while True:
            nuvlabox = nuvla.api.get(nuvlabox_id)
            if nuvlabox.data.get('state', 'UNKNOWN') == 'COMMISSIONED':
                break

            time.sleep(3)

    assert nuvlabox.data['state'] == 'COMMISSIONED', \
        f'NuvlaBox {nuvlabox_id} did not commission'
示例#15
0
    def is_list_view_selected(self):
        self.wait_for_icon_present('view_list')

        with timeout(seconds=15, error_message="Timed out waiting List View to be selected."):
            while True:
                try:
                    grid, tile, list = self.get_view_color_values()
                    if list < grid and list < tile:
                        return True
                except:
                    self.web_session.logger.debug("List View Icon Not Selected")
                    self.ui_utils.sleep(1)
                    pass

        return False
示例#16
0
 def get(self, url, wait_for=wait_for_text):
     self.web_session.logger.debug("Navigate to URL {}".format(url))
     with timeout(seconds=(self.minutes_to_wait * 60), error_message="Timed Navigating \"{}\"".format(url)):
         while True:
             try:
                 self.web_driver.get(url)
                 assert self.ui_utils.waitForTextOnPage(wait_for, 15), "Failed to find text '{}'".format(self.wait_for)
                 break
             except:
                 if self.ui_utils.isTextOnPage("sorry, but something went wrong") or self.ui_utils.isTextOnPage("The server is temporarily unable"):
                     self.web_session.logger.info('Encountered "Sorry" message.')
                     self.ui_utils.sleep(5)
                     pass
                 else:
                     self.web_session.logger.error('Failed URL navigation')
                     raise
示例#17
0
    def is_list_view_selected(self):
        self.wait_for_icon_present('view_list')

        with timeout(
                seconds=15,
                error_message="Timed out waiting List View to be selected."):
            while True:
                try:
                    grid, tile, list = self.get_view_color_values()
                    if list < grid and list < tile:
                        return True
                except:
                    self.web_session.logger.debug(
                        "List View Icon Not Selected")
                    self.ui_utils.sleep(1)
                    pass

        return False
示例#18
0
    def save_provider(self):

        if str(self.web_session.appliance_version) != '5.7*':
            xpath = "//button[contains(text(),'Add')]"
        else:
             xpath = "//button[contains(@ng-click,'addClicked($event, true)')]"

        with timeout(seconds=15, error_message="Timed out waiting for Save."):
            while True:
                WebDriverWait(self.web_driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath)))
                self.web_driver.find_element_by_xpath(xpath).click()
                if (self.ui_utils.isTextOnPage(" was saved")):
                    self.web_session.logger.info("Provider saved.")
                    break;
                else:
                    self.web_session.logger.info("No Provider save message.")

                time.sleep(1)
示例#19
0
    def get_hawkular_deployments(self):
        deployments = []

        with timeout(seconds=30, error_message="Timed out - No Deployments Returned"):
            while True:
                try:
                    rows = self.__hawkular__.inventory.list_server_deployment()
                    if rows:
                        for deployment in rows:
                            dict = {}
                            dict['Nativeid'] = deployment.id
                            dict['Name'] = deployment.name
                            dict['path'] = deployment.path
                            deployments.append(dict)
                        break
                    else:
                        ui_utils(self.web_session).sleep(2)
                except Exception, e:
                    self.__exception_handler(e)
def test_nuvlabox_is_stable(request):
    nuvlabox_status_id = request.config.cache.get('nuvlabox_status_id', '')
    with timeout(180, f'Waited too long for container-stats'):
        while True:
            try:
                nuvlabox_status = nuvla.api.get(nuvlabox_status_id)
            except IndexError:
                nuvlabox_status = {}
                pass

            if nuvlabox_status.data.get('resources', {}).get('container-stats'):
                break

            time.sleep(3)

    request.config.cache.set('nuvlabox_status', nuvlabox_status.data)
    for container in nuvlabox_status.data['resources']['container-stats']:
        assert container['container-status'].lower() in ['running', 'paused'], \
            f'NuvlaBox container {container["name"]} is not running'

        assert container['restart-count'] == 0, \
            f'NuvlaBox container {container["name"]} is unstable and restarting'
示例#21
0
 def get(self, url, wait_for=wait_for_text):
     self.web_session.logger.debug("Navigate to URL {}".format(url))
     with timeout(seconds=(self.minutes_to_wait * 60),
                  error_message="Timed Navigating \"{}\"".format(url)):
         while True:
             try:
                 self.web_driver.get(url)
                 assert self.ui_utils.waitForTextOnPage(
                     wait_for, 15), "Failed to find text '{}'".format(
                         self.wait_for_text)
                 break
             except:
                 if self.ui_utils.isTextOnPage(
                         "sorry, but something went wrong"
                 ) or self.ui_utils.isTextOnPage(
                         "The server is temporarily unable"):
                     self.web_session.logger.info(
                         'Encountered "Sorry" message.')
                     self.ui_utils.sleep(5)
                     pass
                 else:
                     self.web_session.logger.error('Failed URL navigation')
                     raise
def test_expected_attributes(request):
    infra = request.config.cache.get('infra_service', {})
    swarm_enabled = nuvla.api.get(infra['id']).data['swarm-enabled']
    nuvlabox_status = request.config.cache.get('nuvlabox_status', {})

    # update the status
    with timeout(120, 'VPN IP is not available in NuvlaBox Status'):
        while True:
            nuvlabox_status = nuvla.api.get(nuvlabox_status['id']).data
            if nuvlabox_status.get('ip') and nuvlabox_status['ip'].startswith('10.'):
                break

            time.sleep(3)

    default_err_log_suffix = ': attribute missing from NuvlaBox status'
    assert nuvlabox_status.get('ip'), \
        f'IP{default_err_log_suffix}'

    assert nuvlabox_status['ip'].startswith('10.'), \
        'VPN IP is not set'
    assert nuvlabox_status.get('operating-system'), \
        f'Operating System{default_err_log_suffix}'

    assert nuvlabox_status.get('architecture'), \
        f'Architecture{default_err_log_suffix}'

    assert nuvlabox_status.get('hostname'), \
        f'Hostname{default_err_log_suffix}'

    assert nuvlabox_status.get('hostname'), \
        f'Hostname{default_err_log_suffix}'

    assert nuvlabox_status.get('last-boot'), \
        f'Last Boot{default_err_log_suffix}'

    assert nuvlabox_status.get('nuvlabox-engine-version'), \
        f'NuvlaBox Engine Version{default_err_log_suffix}'

    assert nuvlabox_status.get('installation-parameters'), \
        f'Installation Parameters{default_err_log_suffix}'

    assert nuvlabox_status.get('orchestrator'), \
        f'Orchestrator{default_err_log_suffix}'

    nuvlabox = nuvla.api.get(nuvlabox_id)
    assert 'NUVLA_JOB_PULL' in nuvlabox.data.get('capabilities', []), \
        f'NuvlaBox {nuvlabox_id} is missing the  NUVLA_JOB_PULL capability'

    if swarm_enabled:
        assert nuvlabox_status.get('node-id'), \
            f'Node ID{default_err_log_suffix}'

        assert nuvlabox_status.get('cluster-id'), \
            f'Cluster ID{default_err_log_suffix}'

        assert nuvlabox_status.get('cluster-node-role'), \
            f'Cluster Node Role{default_err_log_suffix}'

        assert nuvlabox_status.get('cluster-nodes'), \
            f'Cluster Nodes{default_err_log_suffix}'

        assert nuvlabox_status.get('cluster-managers'), \
            f'Cluster managers{default_err_log_suffix}'

        assert nuvlabox_status.get('cluster-join-address'), \
            f'Cluster Join Address{default_err_log_suffix}'