예제 #1
0
 def test_get_driver(self):
     """Test the retrieval of a driver through the get_driver 
     function
     """
     a_driver = driver.get_driver("portal", 1)
     self.assertIsInstance(a_driver, driver.Portal)
     a_driver = driver.get_driver("usbrly08b", 1)
     self.assertIsInstance(a_driver, driver.Usbrly08b)
예제 #2
0
 def test_get_driver(self):
     """Test the retrieval of a driver through the get_driver 
     function
     """
     a_driver = driver.get_driver("portal", 1)
     self.assertIsInstance(a_driver, driver.Portal)
     a_driver = driver.get_driver("usbrly08b", 1)
     self.assertIsInstance(a_driver, driver.Usbrly08b)
예제 #3
0
파일: stash.py 프로젝트: thortun/Currency
def main():
	USR = "******"
	PWD = "b97ZGP85Bnx$"
	BASE_STASH_URL = "https://www.pathofexile.com/character-window/get-stash-items?league=Delirium&tabs=1&tabIndex=0,0&accountName=Meldrin"

	driver = get_driver()

	driver.get("https://www.pathofexile.com/login")
	print("Waiting for browser check...")
	time.sleep(10)	# Wait for browser check
	input_credentials(driver, USR, PWD)
	input("Please finish login...")

	driver.get(BASE_STASH_URL)
	time.sleep(2)
	contents = driver.find_element_by_xpath("//pre").get_attribute("innerHTML")
	data = json.loads(contents)
	num_tabs = int(data["numTabs"])

	stash = {"tabs" : []}

	for i in range(num_tabs):
		url = stash_url("Delirium", i, i, "Meldrin")
		driver.get(url)
		this_data = driver.find_element_by_xpath("//pre").get_attribute("innerHTML")
		stash["tabs"].append(json.loads(this_data))
	with open("data/stash.json", "w") as fileID:
		fileID.write(json.dumps(stash))
	driver.quit()
예제 #4
0
파일: main.py 프로젝트: graysurf/ibctest
def main():
    sleep_time = config.sleep_time
    driver = get_driver()
    try:
        init_page(driver)
        logger.info("init finished")
        received = 0
        for i in range(3):
            received += logws(driver)
            if received > 0:
                break
            logger.info("refresh page...")
            driver.refresh()
            time.sleep(10)
        if received == 0:
            file_logger.info("no received data")
            logger.info("no received data")
            return
        body = driver.find_element_by_css_selector("body")
        body.click()
        for i in range(3600):
            driver = handle_alert(driver, init_page)
            logws(driver)
            time.sleep(int(sleep_time))
            if i % 200 < 100:
                body.send_keys(Keys.PAGE_DOWN)
            else:
                body.send_keys(Keys.PAGE_UP)
    except Exception as e:
        file_logger.error(e)
        logger.error(e)
    finally:
        driver.quit()
예제 #5
0
def get_playable_resolutions(config, url):
    print("Fetching available resolutions...")
    d = get_driver(config['driver'])
    available_res = fetch_resolutions(d, url)
    d.close()
    print("Video can be played in", available_res)
    return list(set(config['resolutions']) & set(available_res))
예제 #6
0
 def __init__(self, azami):
     self.azami = azami
     try:
         self.driver = get_driver()
     except:
         self.driver = webdriver.Chrome('./chromedriver')
     self.driver.minimize_window()
예제 #7
0
 def _get_driver():
     try:
         driver = getattr(self, '_driver')
     except AttributeError:
         driver = getattr(self, 'parent', None)
     if driver:
         return driver
     return get_driver()
예제 #8
0
class Powerview_pool(unittest.TestCase):

    driver = dr.get_driver()

    def setUp(self):
        self.driver.implicitly_wait(30)
        self.verificationErrors = []
        self.accept_next_alert = True

    poolName = 'cypool1'
    tempvmName = 'wx2c2g-1'

    def test_01_powerview_adddesktoppool(self):
        driver = self.driver
        pool.add(driver, self.poolName, 'daas116',
                 constant.poolType2.staticOnly, ['wx2c2g-10'])

    def test_02_powerview_addvmintopool(self):
        driver = self.driver
        pool.addvm(driver, self.poolName, self.tempvmName)

    def test_03_powerview_removevmfromdesktop(self):
        driver = self.driver
        pool.removevm(driver, self.poolName, self.tempvmName)

    def test_04_powerview_deletedesktoppool(self):
        driver = self.driver
        pool.delete(driver, self.poolName)

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

    def is_alert_present(self):
        try:
            self.driver.switch_to.alert()
        except NoAlertPresentException as 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.quit()
        self.assertEqual([], self.verificationErrors)
예제 #9
0
    def setUp(self):
        self.driver = get_driver()

        # Clear the state of the element
        self.driver.execute_script("MathJax.OutputJax.EditableSVG.clear($('.MathJax_SVG')[0]);")

        # Focus the EditableSVG
        svg = self.driver.find_element(By.XPATH, '//*[@id="MathJax-Element-1-Frame"]/*[name()="svg"]/*[name()="g"]/*[name()="g"]')
        svg.click()
예제 #10
0
    def run(self):
        def myOnStart(offset, length, label, stream, word):
            #print 'worker: OnStart'
            self.onStart.emit(offset, length, label, stream, word)

        def myOnWord(offset, length, label, stream, word, isFirst):
            #print 'worker: OnWord'
            self.onWord.emit(offset, length, label, stream, word, isFirst)

        def myOnEndStream(stream, label):
            #print 'worker: OnEndStream'
            self.onEndStream.emit(stream, label)

        def myOnFinish():
            #print 'worker: OnFinish'
            self.onFinish.emit()

        def mySpeechRequestHook():
            self.requestMoreSpeech.emit()

        self.ttsEngine = driver.get_driver(mySpeechRequestHook)
        startHandle = self.ttsEngine.connect('onStart', myOnStart)
        wordHandle = self.ttsEngine.connect('onWord', myOnWord)
        finishHandle = self.ttsEngine.connect('onFinish', myOnFinish)
        streamHandle = self.ttsEngine.connect('onEndStream', myOnEndStream)

        self.ttsEngine.setVolume(self._volume)
        self.ttsEngine.setRate(self._rate)
        self.ttsEngine.setVoice(self._voice)

        self._ttsCreated = True

        while self._running:
            if self._isChange:
                self.ttsEngine.setVolume(self._volume)
                self.ttsEngine.setRate(self._rate)
                self.ttsEngine.setPauseLength(self._pauseLength)
                self.ttsEngine.setVoice(self._voice)
                self._isChange = False
            QThread.yieldCurrentThread()

        # Kill and cleanup the TTS driver
        self.ttsEngine.disconnect(startHandle)
        self.ttsEngine.disconnect(wordHandle)
        self.ttsEngine.disconnect(finishHandle)
        self.ttsEngine.disconnect(streamHandle)

        self.ttsEngine.stop()
        self.ttsEngine.waitUntilDone()
        self.ttsEngine.destroy()
        del self.ttsEngine

        self._done = True

        return
예제 #11
0
class RSConfig(unittest.TestCase):
    driver = dr.get_driver()
    resource_config.into_resource_config(driver)

    def setUp(self):
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_disk_config(self):
        driver = self.driver
        resource_config.disk_config(driver, 20, 1000)

    def test_platform_quote(self):
        driver = self.driver
        resource_config.platform_quote(driver, 50, 50, 50)

    def test_deskpool_config(self):
        driver = self.driver
        resource_config.deskpool_config(driver, 10)

    def test_roam_config(self):
        driver = self.driver
        resource_config.roam_config(driver, 1024,
                                    "漫游文件已超过最大上限1G,请将不需要漫游的文件删除,谢谢!")

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

    def is_alert_present(self):
        try:
            self.driver.switch_to_alert()
        except NoAlertPresentException as 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.quit()
        self.assertEqual([], self.verificationErrors)
예제 #12
0
class DesktopPolicy(unittest.TestCase):
    driver = dr.get_driver()
    desktop_policy.into_desktop_policy(driver)
    policy_name = desktop_policy.gen_policy_name('qian')

    def setUp(self):
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_create_policy(self):
        driver = self.driver
        desktop_policy.create_policy(driver, self.policy_name, "",
                                     'qiandelivery', (0, 0, 0, 0, 0, 0, 0, 3))

    def test_update_policy(self):
        driver = self.driver
        desktop_policy.update_policy(driver, self.policy_name, "描述",
                                     (1, 1, 1, 1, 1, 1, 1, 1))

    def test_delete_policy(self):
        driver = self.driver
        desktop_policy.delete_policy(driver, self.policy_name)

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

    def is_alert_present(self):
        try:
            self.driver.switch_to_alert()
        except NoAlertPresentException as 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.quit()
        self.assertEqual([], self.verificationErrors)
예제 #13
0
 def add_driver(self, name, driver_type, driver_id):
     """ Add a driver to the test system. The configuration of the
     driver is done with a configuration file. It wil add a driver 
     to the list with the name as key and the specific driver as 
     the value.
     
     :param name: The driver name.
     :type name: string
     :param driver: The kind of driver.
     :type driver: string
     """
     a_driver = driver.get_driver(driver_type, driver_id)
     self.drivers.update({name:a_driver})
예제 #14
0
 def add_driver(self, name, driver_type, driver_id):
     """ Add a driver to the test system. The configuration of the
     driver is done with a configuration file. It wil add a driver 
     to the list with the name as key and the specific driver as 
     the value.
     
     :param name: The driver name.
     :type name: string
     :param driver: The kind of driver.
     :type driver: string
     """
     a_driver = driver.get_driver(driver_type, driver_id)
     self.drivers.update({name: a_driver})
예제 #15
0
def get_html_scores_by_week(weeks, source):
    assert source in ('file', 'web')
    html_by_week = {}
    force_update = False if source == 'file' else True
    driver = get_driver() if source == 'web' else None
    try:
        for week in weeks:
            html = _get_week_html(driver, week, force_update)
            html_by_week[week] = html
    finally:
        if driver:
            driver.quit()
    return html_by_week
예제 #16
0
class PowerviewCreatevm(unittest.TestCase):
    driver = dr.get_driver()

    def setUp(self):
        self.driver.implicitly_wait(30)
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_powerview_createvm(self):
        driver = self.driver

        vmName = 'cy'
        cloneNumber = 1
        offeringName = '2c2g'
        networkName = 'daas116'
        templateNames = ["daas-win7", "daas-win7share", "daas-win2008"]
        #templateNames = ["daas-win81"]
        for templateName in templateNames:
            vm1.create(driver, vmName + templateName.replace('-', ''),
                       cloneNumber, offeringName, templateName, networkName)

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

    def is_alert_present(self):
        try:
            self.driver.switch_to.alert()
        except NoAlertPresentException as 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.quit()
        self.assertEqual([], self.verificationErrors)
예제 #17
0
def search(keyword):
    browser = get_driver()

    for site in websites:
        site_dict = websites[site]
        search_url = site_dict["dir_str"]["search"]["content"].replace(
            "~", site_dict["site_url"]).replace("query", keyword)
        # print(search_url)
        try:
            browser.get(search_url)
        except InvalidArgumentException:
            print(
                f"{search_url} is invalid. Please double check the site records"
            )
            return 0, "Unable to complete search request. Argument was invalid"

        # ozbargain search results -> className: search-results, deal itself is the same
        search_results = browser.find_element_by_class_name("search-results")
        deals = search_results.find_elements_by_class_name("title")

        links = set()
        for deal in deals:

            #TODO: Still need to skip over related-store content.
            if True in map(lambda x: x in deal.text, IGNORE):
                continue
            a_tag = deal.find_element_by_tag_name("a")
            link = a_tag.get_attribute("href")
            # text = a_tag.text
            if "/node/" in link:

                #TODO: Currently repeated links are showing up because some links don't carry text with it. Need to test for
                # the link unique-ness
                links.add(link)

        # links = [a.get_attribute("href") for deal in deals for a in deal.find_elements_by_tag_name("a")]
        browser.close()
    return 1, links
예제 #18
0
파일: pw_vmmgmt.py 프로젝트: zjd2626/robot
class pw_vmmage(unittest.TestCase):
    dr = driver.get_driver()

    def setUp(self, driver=dr):
        # self.driver = driver.get_driver()
        self.driver = driver
        self.base_url = read_conf.login_url
        self.verificationErrors = []
        self.accept_next_alert = True

    # vmName = 'gjzvm11062'

    def test_01_operatevm(self):
        driver = self.driver
        # time.sleep(10)
        # vmm.entry_to_vmm(driver)
        # vmm.select_vm(driver,vmName)
        # # vmm.vnc_view(driver, self.vmName)
        #     # vmm.select_vm(driver,vmName)
        #     # vmm.entry_select_vm(driver,vmName)
        #     # vmm.vnc_view(driver,vmName)
        vmm.entry_select_vm(driver, vmName)
        vmm.restart_vm(driver, vmName)

    #     # vmm.select_vm(driver, vmName)
    #     # vmm.stop_vm(driver,vmName)
    #     # vmm.select_vm(driver,vmName)
    #     # vmm.copy_to_templet(driver,vmName)
    #
    #     # vmm.enter_clouddiskmanage(driver,vmName)
    #     # vmm.delete_vm(driver,vmName)
    # # def test_02_viewvnc(self):
    # #     driver = self.driver
    # #     time.sleep(5)
    # #     vmm.select_vm(driver, vmName)
    # #     vmm.vnc_view(driver, vmName)
    #
    # #
    def test_02_stopvm(self):
        print("start to stop")
        driver = self.driver
        time.sleep(5)
        # vmm.select_vm(driver, vmName)
        vmm.stop_vm(driver, vmName)

    def test_03_cpvmt(self):
        print("start to copy to template")
        driver = self.driver
        time.sleep(5)
        # vmm.select_vm(driver, vmName)
        vmm.copy_to_templet(driver, vmName)

    def test_04_startvm(self):
        print("start to start")
        driver = self.driver
        time.sleep(5)
        # vmm.select_vm(driver, vmName)
        vmm.start_vm(driver, vmName)

    def test_05_viewvnc(self):
        print("start to test vnc view")
        driver = self.driver
        time.sleep(5)
        # vmm.select_vm(driver, vmName)
        vmm.vnc_view(driver, vmName)

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

    def is_alert_present(self):
        try:
            self.driver.switch_to.alert()
        except NoAlertPresentException as 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.quit()
        self.assertEqual([], self.verificationErrors)
예제 #19
0
 def __init__(self):
     self.driver = driver.get_driver()
 def __init__(self, element):
     self.driver = get_driver()
     if not self.driver.execute_script('return window.jQuery'):
         with open(self.JQUERY_PATH, 'r') as jquery:
             self.driver.execute_script(jquery.read())
     self.element = element
예제 #21
0
def main():
    driver = get_driver(headless=False)
    # block_client_by_mac(driver, 'ac:5f:3e:81:94:78')
    unblock_all(driver)
    sleep(10)
예제 #22
0
from flask import Flask, json, request, Response
from driver import get_driver
from client_list import get_client_list
from block_client import get_blocked_clients, block_client_by_mac, unblock_all

app = Flask(__name__)
driver = get_driver(headless=True)


@app.errorhandler(404)
def page_not_found(e):
    return Response(status=404, mimetype='application/json')


@app.errorhandler(500)
def page_server_error(e):
    return Response(status=404, mimetype='application/json')


@app.route('/api/clients', methods=['GET'])
def clients():
    return app.response_class(response=json.dumps([{
        'mac_address': mac,
        'ip_address': ip
    } for mac, ip in get_client_list(driver)]),
                              mimetype='application/json')


@app.route('/api/black-list', methods=['GET', 'POST', 'DELETE'])
def blocked():
    if request.method == 'GET':
예제 #23
0
 def setUp(self):
     self.driver = driver.get_driver()
     self.verificationErrors = []
     self.accept_next_alert = True
예제 #24
0
class Powerview_delivery(unittest.TestCase):
    driver = dr.get_driver()

    def setUp(self):
        self.driver.implicitly_wait(30)
        self.verificationErrors = []
        self.accept_next_alert = True

    deliveryName = 'cydelivery1'
    userName = '******'
    tempuserName = '******'

    def test_01_powerview_adddesktopdelivery(self):
        driver = self.driver
        delivery.add(driver, self.deliveryName, 'cypool1',
                     constant.poolType.staticOnly, [self.userName])

    def test_02_powerview_adduserintodelivery(self):
        driver = self.driver
        delivery.addusers(driver, self.deliveryName, [self.tempuserName])

    def test_03_powerview_alocatevmtouser(self):
        driver = self.driver
        delivery.alocatevmtouser(driver, self.deliveryName, 'wei2c4g-30',
                                 self.tempuserName)

    def test_03_powerview_randomalocatevmtouser(self):
        driver = self.driver
        delivery.randomalocatevmtouser(driver, self.deliveryName,
                                       [self.userName])

    def test_04_powerview_disconnectuseronvm(self):
        driver = self.driver
        print(self.userName + ' get in vm ,like rdesktop -u' +
              self.tempuserName + '@od.com -pengine 172.28.127.104')
        time.sleep(60)
        delivery.disconnectuseronvm(driver, self.deliveryName,
                                    self.tempuserName)

    def test_05_powerview_logouttuseronvm(self):
        driver = self.driver
        print(self.userName + ' get in vm ,like rdesktop -u' +
              self.tempuserName + '@od.com -pengine 172.28.127.104')
        #time.sleep(60)
        delivery.logouttuseronvm(driver, self.deliveryName, self.tempuserName)

    def test_06_powerview_dealocatevm(self):
        driver = self.driver
        delivery.dealocatevm(driver, self.deliveryName, self.tempuserName)

    def test_07_powerview_removeuserfromdelivery(self):
        driver = self.driver
        delivery.removeusers(driver, self.deliveryName, [self.tempuserName])

    def test_08_powerview_deletedelivery(self):
        driver = self.driver
        delivery.delete(driver, self.deliveryName)

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

    def is_alert_present(self):
        try:
            self.driver.switch_to.alert()
        except NoAlertPresentException as 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.quit()
        self.assertEqual([], self.verificationErrors)
예제 #25
0
logging.info('model=' + model)
url = config_data[model][0][1]
logging.info('open url is' + url)

fileexcel = config_data[model][3][1]
logging.info('read excel file is' + fileexcel)
all_content = read_excel(fileexcel)
logging.info('read data is' + str(all_content))

errorNum = 0
success = False
while errorNum < 5 and not success:
    try:
        for i in all_content[0]:

            driver = get_driver(url)
            logging.info('open Chrome')
            try:
                data = all_content[1][i]
                for p in range(1, len(data)):
                    string = str(data[p][4])  # 内容
                    address = str(data[p][3])  # 地址
                    mode = str(data[p][1])  # 定位方式
                    event = str(data[p][2])  # 操作方法
                    logging.info('data:string is' + string + ',address is' +
                                 address + ',mode is' + mode + ',event is' +
                                 event)
                    element = getelement(driver, mode, address)
                    logging.debug(type(element))
                    getevent(driver, event, element, string)
                    logging.debug(getevent.__name__)
예제 #26
0
 def setUp(self):
     self.driver = get_driver()
예제 #27
0
 def _driver(self):
     if self.__driver:
         return self.__driver
     return get_driver()
예제 #28
0
파일: jobs.py 프로젝트: B-Rich/taurus
 def _init_driver(self, companies):
     if not companies:
         return
     for company in companies:
         dd = driver.get_driver(company)
         self.drivers.append(dd)
예제 #29
0
파일: run.py 프로젝트: heathkh/sprink
 def __init__(self):
     self._driver = driver.get_driver()
     self._zone_intervals = {}
     return
예제 #30
0
파일: run.py 프로젝트: heathkh/sprink
 def __init__(self):
     self._driver = driver.get_driver()
     self._zone_intervals = {}
     return
예제 #31
0
class DiskMgmt(unittest.TestCase):
    gdriver = driver.get_driver()
    gvmname = "qaWin7"
    gdisk = "qa" + time.strftime("%Y%m%d%H%M%S")
    gsnap = "snap" + time.strftime("%Y%m%d%H%M%S")
    gnewdisk = "disk" + time.strftime("%Y%m%d%H%M%S")
    verificationErrors = []

    def setUp(self):
        # self.driver = g.driver
        # self.verificationErrors = []
        self.accept_next_alert = True

    def test_01_createdisk(self):
        dr = self.gdriver
        diskname = self.gdisk
        vmname = self.gvmname

        dr.find_element_by_xpath(".//*[@id='mCSB_1_container']/li[1]").click()
        print('Begin to create clouddisk, disk name is ' + diskname)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
        ).click()

        sleep(1)
        # 创建云磁盘
        dr.find_element_by_css_selector("#tran_pop_icon3").click()

        dr.find_element_by_css_selector("#c_disk_name").clear()
        dr.find_element_by_css_selector("#c_disk_name").send_keys(diskname)

        dr.find_element_by_css_selector("#c_disk_account").clear()
        dr.find_element_by_css_selector("#c_disk_account").send_keys("1")

        # dr.find_element_by_css_selector("#create_disk_confirm").click()
        WebDriverWait(dr, 60).until(
            EC.element_to_be_clickable(
                (By.CSS_SELECTOR, "#create_disk_confirm"))).click()
        # 创建中提示信息
        # WebDriverWait(dr,60).until(EC.visibility_of_element_located(
        #     (By.XPATH,"html/body/div[17]/div[3]/div/button"))).click()
        WebDriverWait(dr, 60).until(
            EC.element_to_be_clickable((
                By.XPATH,
                "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
            ))).click()

        locator = (By.XPATH, ".//*[@class='remind']")
        expect_text = "云磁盘{0}创建成功".format(diskname + '-1')

        try:
            # text=WebDriverWait(dr, 60).until(EC.visibility_of_element_located(locator)).text
            # print(text)
            WebDriverWait(dr, 60).until(
                EC.text_to_be_present_in_element(locator, expect_text))
            print(expect_text)
        except BaseException:
            print("云磁盘创建失败.")
            self.verificationErrors.append('error')

        #在列表中查找创建出来的云磁盘
        # all_row=dr.find_elements(By.XPATH,".//*[@id='mainTable']/tbody/tr")
        # rownum=len(all_row)
        #
        # for i in range(rownum):
        #     name=all_row[i].find_elements_by_tag_name('td')[1].text.split("-")[0]
        #     # status=all_row[i].find_elements_by_tag_name('td')[2].text
        #     print("name is %s" %name)
        #     if name==vmname:
        #         all_row[i].click()
        #         dr.find_element_by_xpath(".//*[@id='tran_pop_icon4']").click()
        #         break
        # else:
        #     self.fail("clouddisk not found...")
        #     log.logger.info("clouddisk not found...")
        # 选中创建的云磁盘并点击
        # seldisk=WebDriverWait(dr,60).until(EC.visibility_of_element_located(
        #     (By.XPATH,".//*[@id='mainTable']/tbody/tr/td[contains(text(),'%s')]" %diskname)))
        # text=seldisk.text
        # print(text)

    def test_02_mountdisk(self):
        dr = self.gdriver
        vmname = self.gvmname
        diskname = self.gdisk

        # #进入云磁盘管理
        print('Begin to mount clouddisk, disk name is ' + diskname)
        try:
            WebDriverWait(dr, 10).until(
                EC.visibility_of(
                    dr.find_element(
                        By.XPATH,
                        ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
                    )))
        except:
            dr.find_element_by_xpath(
                ".//*[@id='mCSB_1_container']/li[1]").click()
        sleep(2)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
        ).click()

        sleep(2)
        # 选中创建的云磁盘并点击
        seldisk = WebDriverWait(dr, 60).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 ".//*[@id='mainTable']/tbody/tr/td[contains(text(),'%s')]" %
                 diskname)))
        text = seldisk.text
        print(text)
        seldisk.click()

        # 点击挂载
        dr.find_element_by_xpath(".//*[@id='tran_pop_icon4']").click()

        # 查询
        sleep(5)
        dr.find_element_by_xpath(
            ".//*[@id='attachForm']//input[@name='vmName']").clear()
        dr.find_element_by_xpath(
            ".//*[@id='attachForm']//input[@name='vmName']").send_keys(vmname)
        dr.find_element_by_xpath(".//*[@id='search']").click()

        sleep(2)
        dr.find_element_by_xpath("//input[@name='mount_vm_radio']").click()

        dr.find_element_by_xpath(
            "//div[contains(@style,'display: block;')]"
            "//div[@class='ui-dialog-buttonset']/button[text()='确定']").click()
        sleep(1)
        dr.find_element_by_xpath(
            "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
        ).click()

        locator = (By.XPATH, ".//*[@class='remind']")
        expect_text = "云磁盘{0}挂载成功".format(text)

        try:
            WebDriverWait(dr, 60).until(
                EC.text_to_be_present_in_element(locator, expect_text))
            print(expect_text)
        except BaseException:
            print("云磁盘挂载失败.")

    def test_03_umountdisk(self):
        dr = self.gdriver
        vmname = self.gvmname
        diskname = self.gdisk

        #进入虚拟机管理
        print('进入虚拟机管理页面')

        try:
            WebDriverWait(dr, 10).until(
                EC.visibility_of(
                    dr.find_element(
                        By.XPATH,
                        ".//*[@id='mCSB_1_container']//span[contains(text(),'虚拟机管理')]"
                    )))
        except:
            print("except here...")
            dr.find_element_by_xpath(
                ".//*[@id='mCSB_1_container']/li[1]").click()
        sleep(3)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'虚拟机管理')]"
        ).click()

        sleep(2)
        dr.find_element_by_xpath(
            ".//*[@id='vmIndexForm']//input[@name='vmName']").clear()
        dr.find_element_by_xpath(
            ".//*[@id='vmIndexForm']//input[@name='vmName']").send_keys(vmname)
        dr.find_element_by_xpath(".//*[@id='submit']").click()

        sleep(5)
        # 查询虚拟机状态并停止
        element = WebDriverWait(dr, 60).until(
            EC.visibility_of_element_located(
                (By.XPATH,
                 ".//*[@id='stretch-table']//a[contains(@vmname,'%s')]" %
                 vmname)))
        status = element.get_attribute('state')
        print('status is %s' % status)
        # state = WebDriverWait(dr, 60).until(EC.visibility_of_element_located(
        #     (By.PARTIAL_LINK_TEXT, vmname))).get_attribute('state')
        # print(state)
        if status == "RUNNING":
            print("停止虚拟机....")
            WebDriverWait(dr, 60).until(
                EC.element_to_be_clickable((
                    By.XPATH,
                    ".//*[@id='stretch-table']//tr[contains(@displayname,'%s')]"
                    % vmname))).click()
            dr.find_element_by_xpath("//a[@name='stop']").click()
            dr.find_element_by_xpath(
                "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
            ).click()

            locator = (By.XPATH, ".//*[@class='remind']")
            expect_text = "虚拟机{0}停止成功".format(vmname + '-1')
            try:
                WebDriverWait(dr, 60).until(
                    EC.text_to_be_present_in_element(locator, expect_text))
                print(expect_text)
            except BaseException:
                print("虚拟机停止失败.")

        #进入云磁盘管理
        print('Begin to unmount clouddisk, disk name is ' + diskname)

        try:
            WebDriverWait(dr, 10).until(
                EC.visibility_of(
                    dr.find_element(
                        By.XPATH,
                        ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
                    )))
        except:
            dr.find_element_by_xpath(
                ".//*[@id='mCSB_1_container']/li[1]").click()
        sleep(3)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
        ).click()

        # 选中创建的云磁盘并点击
        WebDriverWait(dr, 60).until(
            EC.element_to_be_clickable(
                (By.XPATH, ".//td[contains(text(),'%s')]//..//a[text()='卸载']" %
                 diskname))).click()
        # rows = dr.find_elements(By.XPATH, ".//table[@id='mainTable']/tbody/tr")
        # for row in rows:
        #     text = row.find_element_by_class_name("td_diskName").text
        #     if text.startswith(diskname):
        #         row.find_element_by_link_text("卸载").click()
        #         break

        confirm_locator = "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
        # 确认是否卸载云磁盘
        # dr.find_element_by_xpath(
        #     "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']").click()
        WebDriverWait(dr, 60).until(
            EC.visibility_of_element_located(
                (By.XPATH, confirm_locator))).click()
        sleep(2)

        # 提示正在卸载云磁盘
        WebDriverWait(dr, 60).until(
            EC.visibility_of_element_located(
                (By.XPATH, confirm_locator))).click()

        locator = (By.XPATH, ".//*[@class='remind']")
        expect_text = "云磁盘{0}卸载成功".format(diskname + '-1')
        try:
            WebDriverWait(dr, 60).until(
                EC.text_to_be_present_in_element(locator, expect_text))
            print(expect_text)
        except BaseException:
            print("云磁盘卸载失败.")

    def test_04_take_snapshot(self):
        dr = self.gdriver
        vmname = self.gvmname
        diskname = self.gdisk
        snapname = self.gsnap

        # 进入云磁盘管理
        # dr.find_element_by_xpath(".//*[@id='mCSB_1_container']/li[1]").click()
        print('Begin to create snapshot, snapshot is %s' % snapname)

        try:
            WebDriverWait(dr, 10).until(
                EC.visibility_of(
                    dr.find_element(
                        By.XPATH,
                        ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
                    )))
        except:
            print("except here...")
            dr.find_element_by_xpath(
                ".//*[@id='mCSB_1_container']/li[1]").click()
        sleep(3)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
        ).click()

        # 选中创建的云磁盘并点击
        WebDriverWait(dr, 60).until(
            EC.element_to_be_clickable(
                (By.XPATH, ".//td[contains(text(),'%s')]//..//a[text()='快照']" %
                 diskname))).click()
        # WebDriverWait(dr,60).until(EC.visibility_of_element_located(
        #     (By.XPATH,".//table[@id='mainTable']/tbody/tr/td[contains(text(),'%s')]" %diskname))).click()
        #
        # rows = dr.find_elements(By.XPATH, ".//table[@id='mainTable']/tbody/tr")
        # for row in rows:
        #     text = row.find_element_by_class_name("td_diskName").text
        #     if text.startswith(diskname):
        #         row.find_element_by_link_text("快照").click()
        #         break
        # else:
        #     self.fail("未找到要创建快照的云磁盘")

        # 创建快照对话框
        dr.find_element_by_xpath(".//*[@id='create_snap_name']").clear()
        dr.find_element_by_xpath(".//*[@id='create_snap_name']").send_keys(
            snapname)
        dr.find_element_by_xpath(".//*[@id='create_snap_confirm']").click()

        # 确认是否创建
        dr.find_element_by_xpath(
            "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
        ).click()

        locator = (By.XPATH, ".//*[@class='remind']")
        expect_text = "云磁盘快照{0}创建成功".format(snapname)
        try:
            WebDriverWait(dr, 60).until(
                EC.text_to_be_present_in_element(locator, expect_text))
            print(expect_text)
        except BaseException:
            print("云磁盘快照创建失败.")

        # dr.find_element_by_link_text("快照管理").click()
        #
        # locator = "//div[@id='content']//span[@class][@title]"
        #
        # rows = dr.find_elements_by_xpath(locator)
        # for row in rows:
        #     text = row.text
        #     if text == snapname:
        #         print("云磁盘快照%s创建成功" % snapname)
        #         break
        # else:
        #     print("云磁盘快照%s创建失败" % snapname)

    def test_05_expand_disk(self):
        '''云磁盘扩容'''
        dr = self.gdriver
        vmname = self.gvmname
        diskname = self.gdisk

        # 进入云磁盘管理
        try:
            WebDriverWait(dr, 10).until(
                EC.visibility_of(
                    dr.find_element(
                        By.XPATH,
                        ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
                    )))
        except:
            print("except here...")
            dr.find_element_by_xpath(
                ".//*[@id='mCSB_1_container']/li[1]").click()
        sleep(3)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
        ).click()

        print('Begin to expand disk, diskname is %s' % diskname)
        # #选中创建的云磁盘并点击
        # WebDriverWait(dr,60).until(EC.visibility_of_element_located(
        #     (By.XPATH,".//table[@id='mainTable']/tbody/tr/td[contains(text(),'%s')]" %diskname))).click()

        try:
            presize = WebDriverWait(dr, 10).until(
                EC.visibility_of_element_located(
                    (By.XPATH,
                     ".//*[@id='mainTable']//input[contains(@diskname,'%s')]" %
                     diskname))).get_attribute('disksize')
            print("扩容前的云磁盘大小是:%s" % presize)
        except:
            self.fail("不存在云磁盘%s." % diskname)

        # rows = dr.find_elements(By.XPATH, ".//table[@id='mainTable']/tbody/tr")
        # for row in rows:
        #     text = row.find_element_by_class_name("td_diskName").text
        #     if text.startswith(diskname):
        #         # 找到了云磁盘,点击扩容按钮
        #         presize = row.find_elements_by_tag_name("td")[3].text
        #         print("扩容前的云磁盘大小是:%s" % presize)
        #         row.find_element_by_link_text("扩容").click()
        #         break
        # else:
        #     self.fail("不存在云磁盘%s." % diskname)

        WebDriverWait(dr, 60).until(
            EC.element_to_be_clickable(
                (By.XPATH, ".//td[contains(text(),'%s')]//..//a[text()='扩容']" %
                 diskname))).click()

        # 确定扩容
        dr.find_element_by_css_selector("#expand_dialog_confirm").click()

        # 开始扩容确定信息
        dr.find_element_by_xpath(
            "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
        ).click()

        # 扩容结果提示窗口
        dr.find_element_by_xpath(
            "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
        ).click()

        # rows = dr.find_elements(By.XPATH, ".//table[@id='mainTable']/tbody/tr")
        # for row in rows:
        #     text = row.find_element_by_class_name("td_diskName").text
        #     if text.startswith(diskname):
        #         # 找到了云磁盘,点击扩容按钮
        #         aftersize = row.find_elements_by_tag_name("td")[3].text
        #         print("扩容后的云磁盘大小是:%s" % aftersize)
        #         break
        # else:
        #     self.skipTest("没找到云磁盘%s." % diskname)

        try:
            aftersize = WebDriverWait(dr, 10).until(
                EC.visibility_of_element_located(
                    (By.XPATH,
                     ".//*[@id='mainTable']//input[contains(@diskname,'%s')]" %
                     diskname))).get_attribute('disksize')
            print("扩容后的云磁盘大小是:%s" % aftersize)
        except:
            self.fail("不存在云磁盘%s." % diskname)

        try:
            self.assertGreater(aftersize, presize)
            print("扩容成功.")
        except BaseException:
            print("扩容失败.")

    def test_06_restore_snapshot(self):
        '''恢复快照'''
        dr = self.gdriver
        vmname = self.gvmname
        snapname = self.gsnap
        newdisk = self.gnewdisk

        # 进入云磁盘管理
        try:
            WebDriverWait(dr, 10).until(
                EC.visibility_of(
                    dr.find_element(
                        By.XPATH,
                        ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
                    )))
        except:
            print("except here...")
            dr.find_element_by_xpath(
                ".//*[@id='mCSB_1_container']/li[1]").click()
        sleep(3)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
        ).click()

        dr.find_element_by_link_text("快照管理").click()

        rows = dr.find_elements(By.XPATH, ".//*[@id='content']//tbody/tr")
        for row in rows:
            text = row.find_elements_by_tag_name("td")[0].text
            # print(text)
            if text.startswith(snapname):
                row.find_element_by_link_text("恢复").click()
                break
        else:
            self.skipTest("未找到需要恢复的快照")

        print('Begin to restore disk %s from snapshot %s' %
              (newdisk, snapname))

        # dr.find_element_by_xpath(".//*[@id='recovery_snapshot_dialog']//input[@name='new_disk_name']")
        dr.find_element_by_css_selector("input[name='new_disk_name']").clear()
        dr.find_element_by_css_selector(
            "input[name='new_disk_name']").send_keys(newdisk)

        dr.find_element_by_css_selector("#snap_restore_confirm").click()

        # 确认信息
        dr.find_element_by_xpath(
            "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"
        ).click()

        locator = (By.XPATH, ".//*[@class='remind']")
        expect_text = "云磁盘快照{0}恢复成功".format(snapname)
        try:
            WebDriverWait(dr, 60).until(
                EC.text_to_be_present_in_element(locator, expect_text))
            print(expect_text)
        except BaseException:
            print("云磁盘快照恢复失败.")

    def test_07_del_disk(self):
        '''删除云磁盘'''
        dr = self.gdriver

        # 进入云磁盘管理
        try:
            WebDriverWait(dr, 10).until(
                EC.visibility_of(
                    dr.find_element(
                        By.XPATH,
                        ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
                    )))
        except:
            print("except here...")
            dr.find_element_by_xpath(
                ".//*[@id='mCSB_1_container']/li[1]").click()
        sleep(3)
        dr.find_element_by_xpath(
            ".//*[@id='mCSB_1_container']//span[contains(text(),'云磁盘管理')]"
        ).click()

        disknames = []
        rows = dr.find_elements(By.XPATH, ".//table[@id='mainTable']/tbody/tr")

        for row in rows:
            text = row.find_element_by_class_name("td_diskName").text
            if text.startswith("qa2018") or text.startswith("disk2018"):
                disknames.append(text)

        for name in disknames:
            print("删除云磁盘%s" % name)
            WebDriverWait(dr, 60).until(
                EC.element_to_be_clickable(
                    (By.XPATH,
                     ".//td[contains(text(),'%s')]//..//a[text()='删除']" %
                     name))).click()

            confirm_locator = "//div[contains(@style,'display: block;')]//div[@class='ui-dialog-buttonset']/button[text()='确定']"

            WebDriverWait(dr, 60).until(
                EC.element_to_be_clickable(
                    (By.XPATH, confirm_locator))).click()
            sleep(1)
            WebDriverWait(dr, 60).until(
                EC.element_to_be_clickable(
                    (By.XPATH, confirm_locator))).click()

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

    def is_alert_present(self):
        pass
        '''
        try: self.driver.switch_to.alert()
        except NoAlertPresentException, e: return False
        return True
        '''

    def close_alert_and_get_its_text(self):
        pass
        '''
        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.gdriver.quit()
        self.assertEqual([], self.verificationErrors)
 def without_wait(*args, **kwargs):
     try:
         driver.get_driver().implicitly_wait(0)
         return func(*args, **kwargs)
     finally:
         driver.get_driver().implicitly_wait(settings.implicit_timeout)
예제 #33
0
import json
import os
import requests
from driver import get_driver
import pandas as pd

# current directory that this python file is in
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
SITES_PATH = CURR_DIR + "/sites.json"
ignore = ["OUT OF STOCK", "EXPIRED", "CLOSED"]

with open(SITES_PATH) as f:
    sites = json.load(f)

chrome = get_driver(f"{CURR_DIR}/chromedriver", CURR_DIR)
chrome.get("https://www.ozbargain.com.au")

deals = chrome.find_elements_by_class_name("node-ozbdeal")

scraped = []
for deal in deals:
    title = deal.find_elements_by_class_name("title")[0].text

    if True in map(lambda x: x in title, ignore):
        continue

    #TODO: Expand the description by going to the actual link and scraping the description from link
    descr = deal.find_elements_by_class_name(
        "content")[0].find_elements_by_tag_name("p")[0].text
    # link = deal.find_elements_by_class_name("submitted")[0].find_elements_by_class_name("via")[0]
    print(title, descr)
예제 #34
0
def play_with_res(video,res,config,f):
    print("Launching browser...")
    d = get_driver(config['driver'])
    y = YouTube(video,res, d, config['youtube'], f)
    y.play()
    time.sleep(2)