在另一个类的python中使用arg解析器

时间:2016-09-19 08:59:45

标签: python selenium argparse

我正在尝试使用python在

我设法运行测试并且它通过了,但是现在我想添加arg解析器,所以我可以给测试一个不同的URL作为参数。

问题是我的测试是在课堂内, 因此,当我传递参数时,我收到一个错误:

    app_url= (args['base_url'])
NameError: global name 'args' is not defined

如何在Selenium类中定义args?

这是我的代码:

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
from selenium import webdriver
import unittest, time, re
import os
import string
import random
import argparse


def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
agmuser = id_generator()

class Selenium(unittest.TestCase):
    def setUp(self):
        chromedriver = "c:\chromedriver.exe"
        os.environ["webdriver.chrome.driver"] = chromedriver
        self.driver = webdriver.Chrome(chromedriver)
        app_url = (args['base_url'])
        #app_url= "http://myd-vm16635.fufu.net:8080/"
        print "this is the APP URL:" + ' ' + app_url
        self.base_url = app_url
        self.verificationErrors = []
        self.accept_next_alert = True

def test_selenium(self):

    #id_generator.user = id_generator()
    driver = self.driver
    driver.get(self.base_url + "portal/")
    driver.find_element_by_css_selector("span").click()
    driver.find_element_by_id("j_loginName").clear()
    driver.find_element_by_id("j_loginName").send_keys(agmuser)
    driver.find_element_by_id("btnSubmit").click()
    driver.find_element_by_link_text("Login as" + ' ' + agmuser).click()
    driver.find_element_by_css_selector("#mock-portal-Horizon > span").click()
    # driver.find_element_by_id("gwt-debug-new-features-cancel-button").click()
    # driver.find_element_by_xpath("//table[@id='gwt-debug-module-dropdown']/tbody/tr[2]/td[2]").click()
    # driver.find_element_by_id("gwt-debug-menu-item-release-management").click()

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)

if __name__ == "__main__":
    #####################******SCRIPT PARAMS****;**###################################
    # these values can be changed type 'python selenium_job.py --help' for assistance
    ##################################################################################
    parser = argparse.ArgumentParser(description='DevOps team - Sanity test')
    parser.add_argument('-b', '--base_url', help='base_url', default="http://myd-vm16635.fufu.net:8080/")
    args = vars(parser.parse_args())
    unittest.main()

1 个答案:

答案 0 :(得分:0)

parser = argparse.ArgumentParser(...)parser.add_argument()放在if __name__ == "__main__":之外,以便始终创建它但不进行评估。将args = vars(parser.parse_args())保留在__main__内。

这样您就可以从from selenium_tests import parser这样的文件中导入它,然后在其他脚本中执行parser.parse_args()

更简洁的方法是创建一个返回解析器的函数,如:

def get_parsed_args():
    parser = argparse.ArgumentParser(...)
    parser.add_argument(...)
    # etc.
    args = parser.parse_args()
    return args
    # or just...
    return parser.parse_args()

#and then call that in the main program:

if __name__ == '__main__':
    args = get_parsed_args()
    # etc.

在其他要导入的脚本中,执行

from selenium_tests import get_parsed_args

if __name__ == '__main__':
    args = get_parsed_args()
    # etc.