Beispiel #1
0
 def __init__(self):
     self.parseExcel = ParseExcel()
     self.log = Log()
     self.select = SelectTheSorting()
     self.pa = PageAction()
     self.pj = ParseJson()
     self.rm = RequestMethod()
Beispiel #2
0
 def __init__(self, filePath):
     # 创建解析Excel工具类的实例对象
     self.parseEx = ParseExcel()
     # 将数据文件Excel加载到内存
     self.parseEx.loadWorkBook(filePath)
     self.apiSheetFileName = ""
     self.apiName = ""
     self.requestMethod = ""
     self.requestUrl = ""
     self.paramsInfo = ""
     self.reponseDataStore = {}
     self.CheckPoint = {}
Beispiel #3
0
class TestRead(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)
    browser = ''

    @set_phone_model(phone_model)
    def setUp(self) -> None:
        TestRead.browser = webdriver.Chrome(chrome_options=options)

        logger.info("开始登陆...")
        TestRead.browser.get("https://plogin.m.jd.com/user/login.action")
        TestRead.login_cookie=LoginAction.login('你的用户名', "你的密码", TestRead.browser)

    def tearDown(self) -> None:
        pass

    def test_P(self):
        logger.info("开始执行唤起菜单脚本...")
        #获取是否执行列

        TestRead.browser.get('https://jdread.jd.com/h5/m')

        bcp=BookCityPage(TestRead.browser)
        bcp.toolButtonObj().click()

        time.sleep(2)
Beispiel #4
0
 def getTerminalSN(self):
     # 从提供的设备列表中选择对应的移动终端
     if TerminalSn is not None:
         return TerminalSn
     terminalList = []  # 用于存放匹配的设备列表
     terminalObject = ParseExcel()
     print(TerminalFilePath)
     terminalObject.loadWorkBook(TerminalFilePath)
     # 根据用例步骤名获取步骤sheet对象
     stepSheet = terminalObject.getSheetByName('Terminal')
     # 获取步骤sheet中步骤数
     stepNum = terminalObject.getRowsNumber(stepSheet)
     # 获取前端入参
     orderPlatform = self.jsonDict.get('orderplatform',
                                       'android')  # 获取终端系统类型
     bitType = self.jsonDict.get('bitType', '32')  # 获取终端设备位数
     manufacturer = self.jsonDict.get('manufacturer', 'huawei')  # 获取终端厂商名称
     for step in range(2, stepNum + 1):
         stepRow = terminalObject.getRow(stepSheet, step)
         terminalSN = stepRow[terminal_ser - 1].value
         terminalPlatform = stepRow[terminal_platform - 1].value
         terminalBittype = str(stepRow[terminal_bittype - 1].value)
         terminalManufacturer = stepRow[terminal_manufacturer - 1].value
         terminalIsonline = stepRow[terminal_isonline - 1].value
         if terminalPlatform == orderPlatform and terminalBittype == bitType:
             if terminalSN and terminalIsonline == 'Y':
                 terminalList.append(terminalSN)
     return None if len(terminalList) == 0 else terminalList[random.randint(
         0,
         len(terminalList) - 1)]
# -*- coding: utf-8 -*-
from appModules.LoginAction import LoginAction

from util.ParseExcel import ParseExcel
from config.VarConfig import *

if __name__ == "__main__":
    from selenium import webdriver
    import time

    # 创建解析Excel对象
    excelObj = ParseExcel()
    # 将excel文件加载到内存
    excelObj.loadWorkBook(dataFilePath)

    # 根据excel文件中的Sheet名称获取此Sheet对象
    userSheet = excelObj.getSheetByName(u"126账号")
    # 获取126账号sheet中是否执行列
    isExecuteUser = excelObj.getColumn(userSheet, account_isExecute)

    for idx, i in enumerate(isExecuteUser[1:]):
        # 循环遍历126账号表中的账号,为需要执行的账号添加联系人
        if i == "y":
            # 获取第i行数据 从第二行开始才有数据
            userRow = excelObj.getRow(userSheet, idx + 2)
            print userRow
            # 获取第i行中的用户名
            username = userRow[account_username - 1]
            print username
            # 获取第i行中的密码
            password = str(userRow[account_password - 1])
from selenium.webdriver.chrome.options import Options
from util.ParseExcel import ParseExcel
from config.VarConfig import *
from appModules.LoginAction import LoginAction
from appModules.AddContactPersonAction import AddContactPerson
import traceback
from time import sleep
from util.Log import *

# 设置此次测试的环境编码为utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

# 将excel数据文件加载到内存
excelObj = ParseExcel()
excelObj.loadWorkBook(dataFilePath)


def LaunchBrowser():
    # 创建Chrome浏览器的一个Options实例对象
    chrome_options = Options()
    # 向Options实例中添加禁用扩展插件的设置参数项
    chrome_options.add_argument("--disable-extensions")
    # 添加屏蔽 --ignore-certificate-errors提示信息的设置参数项
    chrome_options.add_experimental_option("excludeSwitches",
                                           ["ignore-certificate-errors"])
    # 添加浏览器最大化的设置参数项,已启动最大化
    chrome_options.add_argument("--start-maximized")
    # 启动带有自定义设置的chrome浏览器
    driver = webdriver.Chrome(executable_path="E:\\driver\\chromedriver",
class TestLogin(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    def setUp(self) -> None:
        pass

    def tearDown(self) -> None:
        pass

    @set_phone_model(phone_model)
    def test_Login(self):
        logger.info("开始执行登录脚本...")
        #获取是否执行列
        isExecuteUser = TestLogin.excelObj.get_col_values(acount_isExecute)
        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if i == 'Y':
                username = TestLogin.excelObj.get_cell_value(
                    idx + 2, acount_username)
                password = TestLogin.excelObj.get_cell_value(
                    idx + 2, acount_password)
                usertype = TestLogin.excelObj.get_cell_value(
                    idx + 2, acount_type)
                logger.info("执行测试数据:%s,%s,%s" % (username, password, usertype))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    browser.get(minepage)
                    logger.info('启动浏览器,访问"我的"页面...')
                    minePage = MinePage(browser)
                    minePage.LoginEntryButton().click()
                    logger.info('点击"我的"页面的登录按钮...')
                    LoginAction.login(username, password, browser)
                    logger.info('登录操作执行...')

                    try:
                        #minePage.ExitButtonObj()  # 如果在"我的"页面找到退出按钮,则通过测试用例,如果没找到该按钮则测试用例未通过
                        browser.implicitly_wait(5)
                        self.assertIs(minePage.ExitButtonObj().is_displayed(),
                                      True)
                        logger.info('在"我的"页面找【退出】按钮')
                    except Exception as e:
                        # self.assertTrue(1 == 2)

                        logger.debug('在"我的"页面找到【退出】按钮,失败,用例不通过')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'fail', 'red')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                    else:
                        logger.info('在"我的"页面找到【退出】按钮,成功,用例通过')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'success', 'green')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_Login_Button(self):
        logger.info("开始执行登陆按钮脚本...")
        pc = ParseConfigFile()

        try:

            browser = webdriver.Chrome(chrome_options=options)

            browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(browser)
            time.sleep(3)

            # bookcityPage.loginButton().click()
            login_button = bookcityPage.loginButton()
            browser.execute_script("arguments[0].click();", login_button)

            jd_login_button = getElement(browser, 'xpath', '// a[. = "登 录"]')
            try:

                self.assertIs(jd_login_button.is_displayed(), True)
                logger.info('书城登陆按钮点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城登陆按钮点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e
Beispiel #8
0
class executeScriptWithMobile(object):
    #针对移动终端的脚本执行操作
    def __init__(self, FilePath):
        self.excelObj = ParseExcel()
        self.excelFile = FilePath
        self.excelObj.loadWorkBook(FilePath)

    def executeStep(self, stepSheet, step, stepDescribe, keyWord, picValue,
                    threshold, target_pos, rgb):
        temp = ""  #初始化中间临时变量
        # 构造需要执行的python语句,对应的是AppAction.py文件中的终端动作函数调用的字符串表示
        if isinstance(picValue, int):
            picValue = str(picValue)
        if picValue and picValue.endswith('.png'):
            picValue = os.path.join(os.path.split(self.excelFile)[0], picValue)
        if threshold is None and target_pos is None and rgb is None:
            if picValue and picValue.endswith('.png'):
                temp = "(Template(r'" + picValue + "'))"
            else:
                temp = "'" + picValue + "'"
        elif threshold and target_pos is None and rgb is None:
            temp = "Template(r'" + picValue + "', threshold=" + str(
                threshold) + ")"
        elif threshold is None and target_pos and rgb is None:
            temp = "Template(r'" + picValue + "', target_pos=" + str(
                target_pos) + ")"
        elif threshold is None and target_pos is None and rgb:
            temp = "Template(r'" + picValue + "', rgb=" + rgb + ")"
        elif threshold and target_pos and rgb is None:
            temp = "Template('r" + picValue + "', threshold=" + str(
                threshold) + ", target_pos=" + str(target_pos) + ")"
        elif threshold and target_pos is None and rgb:
            temp = "Template(r'" + picValue + "', threshold=" + str(
                threshold) + ", rgb=" + rgb + ")"
        elif threshold is None and target_pos and rgb:
            temp = "Template(r'" + picValue + "', target_pos=" + str(
                target_pos) + ", rgb=" + rgb + ")"
        elif threshold and target_pos and rgb:
            temp = "Template(r'" + picValue + "', threshold=" + str(
                threshold) + ", target_pos=" + str(
                    target_pos) + ", rgb=" + rgb + ")"
        expressionStr = keyWord.strip() + "(" + temp + ")"
        # 执行表达式
        print(expressionStr)
        try:
            eval(expressionStr)
            # 在测试执行时间列写入执行时间
            self.excelObj.writeCellCurrentTime(stepSheet,
                                               rowNo=step,
                                               colsNo=mobile_runTime)
        except Exception as err:
            # 截取异常屏幕图片
            capturePic = snapShot()
            # 获取详细的异常堆栈信息
            errorInfo = traceback.format_exc()
            # 在测试步骤Sheet中写入失败信息
            writeTestResult(self.excelObj, stepSheet, step, "mobile", "faild",
                            errorInfo, capturePic)
            info("步骤“%s”执行失败!函数执行表达式为:%s" % (stepDescribe, expressionStr))
        else:
            # 在测试步骤Sheet中写入成功信息
            writeTestResult(self.excelObj, stepSheet, step, "mobile", "pass")
            # 记录syslog信息
            info("步骤“%s”执行通过!函数执行表达式为:%s" % (stepDescribe, expressionStr))

    def execute(self, caseStepSheetName):
        # 利用aritest执行手机终端,遍历指定excel表单中的内容
        try:
            # 根据用例步骤名获取步骤sheet对象
            info('开始<%s>场景的测试...' % caseStepSheetName)
            stepSheet = self.excelObj.getSheetByName(caseStepSheetName)
            # 获取步骤sheet中步骤数
            stepNum = self.excelObj.getRowsNumber(stepSheet)
            for step in range(2, stepNum + 1):
                stepRow = self.excelObj.getRow(stepSheet, step)
                # 获取excel表单中每一行单元格的数据
                stepDescribe = stepRow[testStep_testStepDescribe - 1].value
                keyWord = stepRow[mobile_keyWords - 1].value
                picValue = stepRow[mobile_picPath - 1].value
                threshold = stepRow[mobile_threshold - 1].value
                target_pos = stepRow[mobile_target_pos - 1].value
                rgb = stepRow[mobile_rgb - 1].value
                args = stepSheet, step, stepDescribe, keyWord, picValue, threshold, target_pos, rgb
                self.executeStep(*args)
        except Exception as err:
            # 打印详细的异常堆栈信息
            debug(traceback.print_exc())

    def getOrderId(self):
        # 获取订单号
        if jsonDict.get('orderTerminal') == '4':
            time.sleep(5)
            return TerminalPoco("com.jd.lib.ordercenter:id/atm").get_text()
class Login(unittest.TestCase):
    def setUp(self):
        self.excelObj = ParseExcel()
        self.excelObj.load_workbook(dataFilePath001)

    def tearDown(self):
        pass

    def test_login(self):
        logging.info(u'登录测试用例现在开始执行')
        try:
            user_sheet = self.excelObj.get_sheetbyname(u'login')
            is_execute = self.excelObj.get_column(user_sheet, login_isExecute)
            logging.debug('is_execute[1:]:%s' % is_execute[1:])
            for idx, value in enumerate(is_execute[1:]):
                if value == 'y':
                    user_data = self.excelObj.get_row(user_sheet, idx+2)
                    username = user_data[login_username - 1]
                    password = user_data[login_password - 1]
                    assert_word = user_data[login_assert - 1]
                    driver = webdriver.Chrome()
                    driver.get('https://www.51kaihui.com/login/index')
                    time.sleep(3)
                    LoginAction.login(d=driver, username=username, password=password)
                    logging.info(u'登录用户名:%s,密码:%s' % (username, password))
                    time.sleep(3)
                    try:
                        assert assert_word in driver.page_source
                    except AssertionError as e:
                        logging.info(u'用户%s断言关键字:%s,断言失败' % (username, assert_word))
                        self.excelObj.write_cell(sheet=user_sheet,
                                                 content='failed',
                                                 row_number=idx+2,
                                                 column_number=login_testResult,
                                                 style='red')
                        self.excelObj.write_cell_currenttime(user_sheet, row_number=idx+2, column_number=login_testTime)
                    else:
                        logging.info(u'断言关键字:%s,断言成功' % assert_word)
                        self.excelObj.write_cell(sheet=user_sheet,
                                                 content='pass',
                                                 row_number=idx+2,
                                                 column_number=login_testResult,
                                                 style='green')
                        self.excelObj.write_cell_currenttime(user_sheet, row_number=idx+2, column_number=login_testTime)
                    driver.quit()
        except Exception as e:
            raise e
Beispiel #10
0
class TestLogin(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    def setUp(self) -> None:
        pass

    def tearDown(self) -> None:
        pass

    def test_Login(self):
        logger.info("开始执行登录脚本...")
        #获取是否执行列
        isExecuteUser = TestLogin.excelObj.get_col_values(login_isExecute)
        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if i == 'Y':
                username = TestLogin.excelObj.get_cell_value(
                    idx + 2, acount_username)
                password = TestLogin.excelObj.get_cell_value(
                    idx + 2, acount_password)
                logger.info("执行测试数据:%s,%s" % (username, password))
                try:
                    options = webdriver.ChromeOptions()
                    browser = webdriver.Chrome(options=options)
                    browser.maximize_window()
                    browser.get(loginpageUrl)
                    logger.info('启动浏览器,访问登录页面...')
                    LoginAction.login(username, password, browser)
                    logger.info('登录操作执行...')
                    try:
                        # browser.implicitly_wait(5)       # 如果在首页页面找到MDT管理系统logo,则通过测试用例,如果没找到该logo则测试用例未通过
                        homepage = HomePage(browser)
                        self.assertIs(homepage.logoDiv().is_displayed(), True)
                        logger.info('在首页页面找【MDT管理系统】logo')
                    except Exception as e:
                        # self.assertTrue(1 == 2)
                        logger.debug('在首页页面找不到【MDT管理系统】logo,失败,用例不通过')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, login_testResult, 'fail', 'red')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, login_time,
                            str(time.time() - start_time) + 's', 'red')
                        raise e

                    else:
                        logger.info('在首页页面找到【MDT管理系统】logo,成功,用例通过')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, login_testResult, 'success', 'green')
                        TestLogin.excelObj.write_cell_value(
                            idx + 2, login_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue
Beispiel #11
0
class TesShoppingCart(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    @classmethod
    @set_phone_model(phone_model)
    def setUpClass(cls) -> None:
        TesShoppingCart.browser = webdriver.Chrome(chrome_options=options)

        logger.info("开始登陆...")
        TesShoppingCart.browser.get(
            "https://plogin.m.jd.com/user/login.action")
        TesShoppingCart.login_cookie = LoginAction.login(
            not_vip_username, not_vip_password, TesShoppingCart.browser)

    @classmethod
    def tearDownClass(cls) -> None:
        TesShoppingCart.browser.quit()

    def test_Add_Book_and_Delete_Book(self):
        #获取是否执行列
        isExecuteUser = TesShoppingCart.excelObj.get_col_values(
            book_isExecute, sheet_name='购买书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if i == 'Y':
                bookid = TesShoppingCart.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = TesShoppingCart.excelObj.get_cell_value(
                    idx + 2, book_name)
                logger.info("执行测试数据:%s,%s" % (bookid, bookname))
                # 通过接口api拿到我的书籍列表中的书
                my_books_data = MyBooks.getData(
                    TesShoppingCart.excelObj.get_cell_value(
                        idx + 2, buyer_pin))
                # 判断buyer是否已经拥有该书:
                have_flag = bookid in my_books_data
                if have_flag:
                    TesShoppingCart.excelObj.write_cell_value(
                        idx + 2, book_isExecute, 'N')
                else:
                    try:

                        TesShoppingCart.browser.get(
                            pc.getUrl('bookdetail') % (bookid))

                        logger.info('启动浏览器,访问"书详页"页面...')
                        book_detail_page = BookDetailPage(
                            TesShoppingCart.browser)

                        add_shopping_cart_button = book_detail_page.shopCartButton(
                        )
                        TesShoppingCart.browser.execute_script(
                            "arguments[0].scrollIntoView();",
                            add_shopping_cart_button)

                        add_shopping_cart_button.click()
                        time.sleep(2)
                        add_shopping_cart_button.click()
                        shopping_cart_page = ShoppingCartPage(
                            TesShoppingCart.browser)

                        try:
                            first_book_in_shopping_cart = shopping_cart_page.shoppingCartBookListObj(
                            )[0].text
                            self.assertIs(
                                bookname in first_book_in_shopping_cart, True)

                            shopping_cart_page.shoppingCartBookOptionListObj(
                            )[0].click()
                            shopping_cart_page.shoppingCartDeleteButton(
                            ).click()
                            time.sleep(2)
                            shopping_cart_page.shoppingCartDeleteConfirmButton(
                            ).click()

                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, execute_testResult, 'success',
                                'green')
                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, execute_time,
                                str(round(
                                    (time.time() - start_time) / 1000, 2)) +
                                's')
                            logger.info('购物车删除书籍,用例通过!')
                            break

                        except AssertionError as e:
                            logger.debug('购物车删除书籍,用例不通过!')
                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, execute_testResult, 'fail', 'red')
                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, execute_time,
                                str(time.time() - start_time) + 'ms', 'red')
                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, book_isExecute, 'N')
                            raise e

                    except ElementNotVisibleException as e:

                        logger.error("数据问题,元素没有找到..")

                    except NoSuchElementException as e:

                        logger.error("数据问题..重试")

                    except Exception as e:

                        logger.error(e)

                        raise e
            else:
                continue

    def test_Add_Book_and_Buy_Book(self):
        # 获取是否执行列
        isExecuteUser = TesShoppingCart.excelObj.get_col_values(
            book_isExecute, sheet_name='购买书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if i == 'Y':
                bookid = TesShoppingCart.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = TesShoppingCart.excelObj.get_cell_value(
                    idx + 2, book_name)
                logger.info("执行测试数据:%s,%s" % (bookid, bookname))
                # 通过接口api拿到我的书籍列表中的书
                my_books_data = MyBooks.getData(
                    TesShoppingCart.excelObj.get_cell_value(
                        idx + 2, buyer_pin))
                # 判断buyer是否已经拥有该书:
                have_flag = bookid in my_books_data
                if have_flag:
                    TesShoppingCart.excelObj.write_cell_value(
                        idx + 2, book_isExecute, 'N')
                else:
                    try:

                        TesShoppingCart.browser.get(
                            pc.getUrl('bookdetail') % (bookid))

                        logger.info('启动浏览器,访问"书详页"页面...')
                        book_detail_page = BookDetailPage(
                            TesShoppingCart.browser)

                        add_shopping_cart_button = book_detail_page.shopCartButton(
                        )
                        # TesShoppingCart.browser.execute_script("arguments[0].scrollIntoView();", add_shopping_cart_button)

                        add_shopping_cart_button.click()
                        time.sleep(2)
                        add_shopping_cart_button.click()
                        shopping_cart_page = ShoppingCartPage(
                            TesShoppingCart.browser)
                        price = shopping_cart_page.shoppingCartBookPriceListObj(
                        )[0].text
                        book_image = shopping_cart_page.shoppingCartBookImageListObj(
                        )[0]
                        book_name_in_cart = shopping_cart_page.shoppingCartBookNameListObj(
                        )[0]

                        try:
                            self.assertIs(book_image.is_displayed(), True)
                            self.assertIs(book_name_in_cart.is_displayed(),
                                          True)
                            first_book_in_shopping_cart = shopping_cart_page.shoppingCartBookListObj(
                            )[0].text
                            self.assertIs(
                                bookname in first_book_in_shopping_cart, True)

                            shopping_cart_page.shoppingCartBookOptionListObj(
                            )[0].click()
                            shopping_cart_page.shoppingCartSettlementButton(
                            ).click()

                            time.sleep(2)
                            avail_amount = shopping_cart_page.shoppingCartSettlementAvailAmountObj(
                            ).text.strip('-')
                            settlement_amount = shopping_cart_page.shoppingCartSettlementAmountObj(
                            ).text
                            check_price = False
                            if price == avail_amount and price == settlement_amount:
                                check_price = True
                            self.assertIs(check_price, True)
                            shopping_cart_payable_amount = shopping_cart_page.shoppingCartPayableAmountObj(
                            ).text
                            if '¥0' in shopping_cart_payable_amount:
                                shopping_cart_buy_confirm_btn = shopping_cart_page.shoppingCartBuyConfirmButton(
                                )
                                shopping_cart_buy_confirm_btn.click()
                                time.sleep(2)
                                self.assertIs(
                                    "支付完成" == TesShoppingCart.browser.title,
                                    True)
                                TesShoppingCart.excelObj.write_cell_value(
                                    idx + 2, book_isExecute, 'N')
                                TesShoppingCart.excelObj.write_cell_value(
                                    idx + 2, execute_testResult, 'success',
                                    'green')
                                TesShoppingCart.excelObj.write_cell_value(
                                    idx + 2, execute_time,
                                    str(
                                        round(
                                            (time.time() - start_time) / 1000,
                                            2)) + 's')
                                logger.info('购物车购买书籍,用例通过!')
                                break
                            else:
                                logger.warning('余额不足...')
                                text_mail(
                                    '来自m站自动化测试脚本',
                                    '在购物车购买书籍测试用例中%s账户余额不足,请及时充值' %
                                    (not_vip_username))
                                self.assertTrue(1 == 2)

                        except AssertionError as e:
                            logger.debug('购物车删除书籍,用例不通过!')
                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, execute_testResult, 'fail', 'red')
                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, execute_time,
                                str(time.time() - start_time) + 'ms', 'red')
                            TesShoppingCart.excelObj.write_cell_value(
                                idx + 2, book_isExecute, 'N')
                            raise e

                    except ElementNotVisibleException as e:
                        TesShoppingCart.excelObj.write_cell_value(
                            idx + 2, book_isExecute, 'N')
                        logger.error("数据问题,元素没有找到..")

                    except NoSuchElementException as e:

                        TesShoppingCart.excelObj.write_cell_value(
                            idx + 2, book_isExecute, 'N')
                        logger.error("数据问题..重试")

                    except Exception as e:
                        TesShoppingCart.excelObj.write_cell_value(
                            idx + 2, book_isExecute, 'N')
                        logger.error(e)

                        raise e
            else:
                continue
class testBookDetailNeedLogin(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    def setUp(self) -> None:
        pass

    def tearDown(self) -> None:
        pass

    @set_phone_model(phone_model)
    def test_VIP_user_read_VIP_book(self):
        logger.info("开始执行书详页-VIP用户查看VIP书详页脚本...")

        #获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='VIP逻辑验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            data_Type = testBookDetailNeedLogin.excelObj.get_cell_value(
                idx + 2, book_type)
            if 'Y' == i and "VIP_user_VIP_book" == data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    #登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")
                    LoginAction.login(username, password, browser,
                                      pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(browser)
                    vip_price = bookDetailPage.vipOriginalPriceObj()
                    vip_read_button = bookDetailPage.vipReadButtonObj()
                    vip_read_button_text = bookDetailPage.vipReadButtonTextObj(
                    )
                    vip_read_for_free_text = bookDetailPage.vipReadForFreeTextObj(
                    )
                    vip_flag = bookDetailPage.vipFlagObj()

                    try:

                        self.assertIs(vip_read_for_free_text.is_displayed(),
                                      True)
                        self.assertIs(vip_read_button.is_displayed(), True)
                        self.assertIs("VIP免费读" == vip_read_button_text.text,
                                      True)
                        self.assertIs(vip_price.is_displayed(), True)
                        self.assertIs(vip_flag.is_displayed(), True)

                        logger.info('执行书详页-VIP用户查看VIP书详页脚本成功!用例通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'success', 'green')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-VIP用户查看VIP书详页脚本失败!用例不通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'fail', 'red')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_VIP_user_read_NVIP_book(self):
        logger.info("开始执行书详页-VIP用户查看NVIP书详页脚本...")

        #获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='VIP逻辑验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            data_Type = testBookDetailNeedLogin.excelObj.get_cell_value(
                idx + 2, book_type)
            if 'Y' == i and "VIP_user_NVIP_book" == data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    #登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")
                    LoginAction.login(username, password, browser,
                                      pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(browser)

                    read_button_text = bookDetailPage.readButtonTextObj()
                    price = bookDetailPage.realPriceObj()

                    try:

                        self.assertIs("立即阅读" == read_button_text.text, True)
                        self.assertIs(price.is_displayed(), True)

                        logger.info('执行书详页-VIP用户查看NVIP书详页脚本成功!用例通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'success', 'green')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-VIP用户查看NVIP书详页脚本失败!用例不通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'fail', 'red')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_NVIP_user_read_VIP_book(self):
        logger.info("开始执行书详页-NVIP用户查看VIP书详页脚本...")

        #获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='VIP逻辑验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            data_Type = testBookDetailNeedLogin.excelObj.get_cell_value(
                idx + 2, book_type)
            if 'Y' == i and "NVIP_user_VIP_book" == data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    browser.get(pc.getUrl('bookdetail') % (bookid))
                    bookDetailPage = BookDetailPage(browser)

                    read_button_text = bookDetailPage.readButtonTextObj()
                    price = bookDetailPage.realPriceObj()
                    no_vip_read_text = bookDetailPage.noVipReadTextObj()
                    vip_flag = bookDetailPage.vipFlagObj()

                    try:

                        self.assertIs("立即阅读" == read_button_text.text, True)
                        self.assertIs(price.is_displayed(), True)
                        self.assertIs("开通VIP,免费阅读此书>" == no_vip_read_text.text,
                                      True)
                        self.assertIs(vip_flag.is_displayed(), True)

                        logger.info('执行书详页-NVIP用户查看VIP书详页脚本成功!用例通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'success', 'green')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-NVIP用户查看VIP书详页脚本失败!用例不通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'fail', 'red')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_NVIP_user_read_NVIP_book(self):
        logger.info("开始执行书详页-NVIP用户查看NVIP书详页脚本...")

        #获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='VIP逻辑验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            data_Type = testBookDetailNeedLogin.excelObj.get_cell_value(
                idx + 2, book_type)
            if 'Y' == i and "NVIP_user_NVIP_book" == data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    browser.get(pc.getUrl('bookdetail') % (bookid))

                    bookDetailPage = BookDetailPage(browser)

                    read_button_text = bookDetailPage.readButtonTextObj()
                    price = bookDetailPage.realPriceObj()

                    try:

                        self.assertIs("立即阅读" == read_button_text.text, True)
                        self.assertIs(price.is_displayed(), True)
                        self.assertIs("VIP免费阅读" not in browser.page_source,
                                      True)
                        self.assertIs(
                            "开通VIP,免费阅读此书>" not in browser.page_source, True)

                        logger.info('执行书详页-NVIP用户查看NVIP书详页脚本成功!用例通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'success', 'green')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-NVIP用户查看NVIP书详页脚本失败!用例不通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_testResult_book_detail, 'fail',
                            'red')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, execute_time_book_detail,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_shopping_cart_button(self):
        logger.info("开始执行书详页-购物车按钮脚本...")

        # 获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='VIP逻辑验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            data_Type = testBookDetailNeedLogin.excelObj.get_cell_value(
                idx + 2, book_type)
            if 'Y' == i and "VIP_user_NVIP_book" == data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    # 登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")
                    LoginAction.login(username, password, browser,
                                      pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(browser)

                    bookDetailPage.shoppingCarButton().click()
                    time.sleep(2)

                    try:

                        self.assertIs("购物车" == browser.title, True)

                        logger.info('执行书详页购物车脚本成功!用例通过')

                    except AssertionError as e:
                        logger.debug('执行书详页-购物车脚本失败!用例不通过')

                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_book_write_comment_page(self):
        logger.info("开始执行书详页-写书评页面元素验证脚本...")

        #获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='写书评验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if 'Y' == i:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_acount_username)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_acount_password)
                bookauthor = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_book_author)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    # 登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")
                    LoginAction.login(username, password, browser,
                                      pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')

                    bookDetailPage = BookDetailPage(browser)
                    bookDetailPage.writeBookCommentButton().click()
                    time.sleep(2)
                    writeCommentPage = WriteCommentPage(browser)

                    try:

                        self.assertIs(
                            writeCommentPage.titleObj().is_displayed(), True)
                        self.assertIs(
                            writeCommentPage.bookNameObj().text == bookname,
                            True)
                        a = writeCommentPage.bookAuthorObj().text + "[著]"
                        self.assertIs(a == bookauthor, True)
                        style = writeCommentPage.publishButtonText(
                        ).get_attribute("style")
                        #黑色color:rgb(222,219,214)
                        #红色:color:rgb(239,60,60)
                        #返回内容'color: rgb(222, 219, 214);'

                        logger.info('执行书详页-目录验证脚本成功!用例通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_testResult, 'success',
                            'green')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-目录验证脚本失败!用例不通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_testResult, 'fail',
                            'red')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_write_book_comment(self):
        logger.info("开始执行书详页-写书评页面验证脚本...")

        #获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='写书评验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if 'Y' == i:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_acount_username)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, catagory_acount_password)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    # 登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")

                    LoginAction.login(username, password, browser,
                                      pc.getUrl('allcomments') % (bookid))
                    all_comments_page = AllCommentPage(browser)
                    all_comments_page.writeCommentButton().click()

                    # LoginAction.login(username, password, browser, pc.getUrl('writecomment') % (bookid))
                    logger.info('启动浏览器,访问"写书评"页面...')
                    write_comment_page = WriteCommentPage(browser)

                    try:

                        self.assertIs(
                            write_comment_page.titleObj().is_displayed(), True)
                        # self.assertIs( write_comment_page.bookAuthorObj().is_displayed(),True)
                        self.assertIs(
                            len(write_comment_page.commentStarObj()) == 5,
                            True)
                        # self.assertIs(write_comment_page.bookNameObj().is_displayed(),True)
                        self.assertIs(
                            write_comment_page.commentStarTextObj().text ==
                            "非读不可", True)

                        write_comment_page.commentDetailObj().send_keys(
                            "这本书真的很棒!")
                        time.sleep(2)
                        write_comment_page.publishButton().click()

                        time.sleep(2)

                        response_text = all_comments_page.commentsObj()[0].text
                        comment_content_check = '这本书真的很棒!' in response_text
                        time_check = '刚刚' in response_text
                        check_result = comment_content_check and time_check
                        self.assertIs(check_result, True)

                        logger.info('执行书详页-写书评验证脚本成功!用例通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_testResult, 'success',
                            'green')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-写书评验证脚本失败!用例不通过')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_testResult, 'fail',
                            'red')
                        testBookDetailNeedLogin.excelObj.write_cell_value(
                            idx + 2, catagory_execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_add_shop_cart_button(self):
        logger.info("开始执行书详页-加入购物车按钮脚本...")

        # 获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='VIP逻辑验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            data_Type = testBookDetailNeedLogin.excelObj.get_cell_value(
                idx + 2, book_type)
            if 'Y' == i and "VIP_user_NVIP_book" == data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    # 登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")
                    LoginAction.login(username, password, browser,
                                      pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(browser)

                    add_shopping_cart_button = bookDetailPage.shopCartButton()
                    browser.execute_script("arguments[0].scrollIntoView();",
                                           add_shopping_cart_button)

                    add_shopping_cart_button.click()
                    time.sleep(2)
                    add_shopping_cart_button.click()

                    try:

                        shopping_cart_page = ShoppingCartPage(browser)
                        first_book_in_shopping_cart = shopping_cart_page.shoppingCartBookListObj(
                        )[0].text
                        self.assertIs(bookname in first_book_in_shopping_cart,
                                      True)
                        shopping_cart_page.shoppingCartBookOptionListObj(
                        )[0].click()
                        shopping_cart_page.shoppingCartDeleteButton().click()
                        time.sleep(2)
                        shopping_cart_page.shoppingCartDeleteConfirmButton(
                        ).click()

                        logger.info('执行书详页加入购物车脚本成功!用例通过')

                    except AssertionError as e:
                        logger.debug('执行书详页-加入购物车脚本失败!用例不通过')

                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model(phone_model)
    def test_read_book_button(self):
        logger.info("开始执行书详页-阅读按钮脚本...")

        # 获取是否执行列
        isExecuteUser = testBookDetailNeedLogin.excelObj.get_col_values(
            book_isExecute, sheet_name='VIP逻辑验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            data_Type = testBookDetailNeedLogin.excelObj.get_cell_value(
                idx + 2, book_type)
            if 'Y' == i and "VIP_user_VIP_book" == data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))

                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    # 登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")
                    LoginAction.login(username, password, browser,
                                      pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(browser)

                    read_button = bookDetailPage.readButton()
                    browser.execute_script("arguments[0].scrollIntoView();",
                                           read_button)

                    try:

                        self.assertIs(read_button.text == 'VIP免费读', True)
                        read_button.click()
                        time.sleep(2)
                        check_url = '%sstatic/read/dist/index.html?ebookId=%s&name=' % (
                            url, bookid) in browser.current_url
                        self.assertIs(check_url, True)
                        logger.info('执行书详页阅读按钮脚本成功!用例通过')

                    except AssertionError as e:
                        logger.debug('执行书详页-阅读按钮脚本失败!用例不通过')

                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            elif 'Y' == i and "VIP_user_VIP_book" != data_Type:
                bookid = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_id)
                bookname = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, book_name)
                username = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_username_check_vip)
                password = testBookDetailNeedLogin.excelObj.get_cell_value(
                    idx + 2, acount_password_check_vip)

                logger.info("执行测试数据:%s,%s,%s,%s" %
                            (bookid, bookname, username, password))
                try:

                    browser = webdriver.Chrome(chrome_options=options)

                    # 登陆
                    logger.info('登录操作执行...')
                    browser.get("https://plogin.m.jd.com/user/login.action")
                    LoginAction.login(username, password, browser,
                                      pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(browser)

                    read_button = bookDetailPage.readButton()
                    browser.execute_script("arguments[0].scrollIntoView();",
                                           read_button)

                    try:

                        self.assertIs(read_button.text == '立即阅读', True)
                        read_button.click()
                        time.sleep(2)
                        check_url = '%sstatic/read/dist/index.html?ebookId=%s&name=' % (
                            url, bookid) in browser.current_url
                        self.assertIs(check_url, True)
                        logger.info('执行书详页阅读按钮脚本成功!用例通过')

                    except AssertionError as e:
                        logger.debug('执行书详页-阅读按钮脚本失败!用例不通过')

                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e

            else:
                continue
class TestSearch(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    def setUp(self) -> None:
        pass

    def tearDown(self) -> None:
        pass

    @set_phone_model('Galaxy S5')
    def test_Search_By_Name(self):
        logger.info("开始执行搜索脚本...")
        #获取是否执行列
        isExecuteUser = TestSearch.excelObj.get_col_values(book_isExecute,
                                                           sheet_name='搜索书籍')
        pc = ParseConfigFile()
        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if i == 'Y':
                bookname = TestSearch.excelObj.get_cell_value(
                    idx + 2, book_name)
                logger.info("执行测试数据:%s" % (bookname))
                try:
                    browser = webdriver.Chrome(chrome_options=options)
                    browser.get(pc.getUrl('search'))
                    logger.info('启动浏览器,访问"搜索"页面...')

                    searchbookPage = SearchBookPage(browser)
                    logger.info('触发搜索...')
                    searchbookPage.SearchInputBoxObj().send_keys(bookname)
                    searchbookPage.SearchInputBoxObj().send_keys(
                        Keys.ENTER)  # 通过回车键来代替鼠标的左键

                    try:
                        name = searchbookPage.SearchResultFirstBookName().text
                        # 搜索结果中第一本书的名字和输入的书名相等
                        self.assertIs(name == bookname, True)
                        logger.info('通过书名搜索用例通过')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'success', 'green')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except Exception as e:
                        logger.debug('通过书名搜索用例不通过')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'fail', 'red')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    @set_phone_model('Galaxy S5')
    def test_Search_By_Author(self):
        logger.info("开始执行搜索脚本...")
        #获取是否执行列
        isExecuteUser = TestSearch.excelObj.get_col_values(book_isExecute,
                                                           sheet_name='搜索书籍')
        pc = ParseConfigFile()
        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if i == 'Y':
                bookauthor = TestSearch.excelObj.get_cell_value(
                    idx + 2, book_author)
                logger.info("执行测试数据:%s" % (bookauthor))
                try:

                    browser = webdriver.Chrome(chrome_options=options)
                    browser.get(pc.getUrl('search'))
                    logger.info('启动浏览器,访问"搜索"页面...')
                    searchbookPage = SearchBookPage(browser)
                    logger.info('触发搜索...')
                    searchbookPage.SearchInputBoxObj().send_keys(bookauthor)
                    searchbookPage.SearchInputBoxObj().send_keys(
                        Keys.ENTER)  # 通过回车键来代替鼠标的左键

                    try:
                        author = searchbookPage.SearchResultFirstBookAuthor(
                        ).text
                        # 搜索结果中第一本书的作者和输入的人名相等
                        self.assertTrue(author == bookauthor)
                        logger.info('通过作者搜索用例通过')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'success', 'green')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('通过作者搜索用例不通过')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_testResult, 'fail', 'red')
                        TestSearch.excelObj.write_cell_value(
                            idx + 2, execute_time,
                            str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue
class TestRead(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    @classmethod
    @set_phone_model(phone_model)
    def setUpClass(cls) -> None:
        TestRead.browser = webdriver.Chrome(chrome_options=options)

        logger.info("开始登陆...")
        TestRead.browser.get("https://plogin.m.jd.com/user/login.action")
        TestRead.login_cookie = LoginAction.login(not_vip_username, not_vip_password, TestRead.browser)

    @classmethod
    def tearDownClass(cls) -> None:
        TestRead.browser.quit()

    def setUp(self) -> None:
        pass

    def tearDown(self) -> None:
        pass

    def test_Popup_Menu(self):
        logger.info("开始执行唤起菜单脚本...")
        #获取是否执行列
        isExecuteUser=TestRead.excelObj.get_col_values(book_isExecute,sheet_name='阅读书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            if i=='Y':
                bookid=TestRead.excelObj.get_cell_value(idx+2,book_id)
                bookname=TestRead.excelObj.get_cell_value(idx+2,book_name)
                logger.info("执行测试数据:%s,%s"%(bookid,bookname))
                try:

                    TestRead.browser.get(pc.getUrl('read')%(bookid,bookname))
                    logger.info('启动浏览器,访问"阅读"页面...')
                    readbookPage = ReadBookPage(TestRead.browser)

                    logger.info('点击"阅读"页面的中间1次...')
                    center_section=readbookPage.CenterSectionObj()
                    ActionChains(TestRead.browser).move_to_element(center_section).click().perform()

                    try:
                        settingButton = readbookPage.SettingButton()
                        #智能点击
                        AIclick(settingButton)
                        self.assertIs(readbookPage.JDHeaderBar().is_displayed(),True)
                        logger.info('调起菜单成功!用例通过')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_testResult, 'success', 'green')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_time, str(round((time.time() - start_time)/1000,2)) + 's')

                    except AssertionError as e:
                        logger.debug('调起菜单失败!用例通过')
                        TestRead.excelObj.write_cell_value(idx+2,execute_testResult,'fail','red')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_time,str(time.time()-start_time)+'ms', 'red')
                        raise e


                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_More_Tools_Button(self):
        logger.info("开始执行唤起更多工具按钮脚本...")
        #获取是否执行列
        isExecuteUser=TestRead.excelObj.get_col_values(book_isExecute,sheet_name='阅读书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            if i=='Y':
                bookid=TestRead.excelObj.get_cell_value(idx+2,book_id)
                bookname=TestRead.excelObj.get_cell_value(idx+2,book_name)
                logger.info("执行测试数据:%s,%s"%(bookid,bookname))
                try:

                    TestRead.browser.get(pc.getUrl('read')%(bookid,bookname))

                    logger.info('启动浏览器,访问"阅读"页面...')
                    readbookPage = ReadBookPage(TestRead.browser)

                    logger.info('点击右侧区域翻一页...')
                    AIclick(readbookPage.RightSectionObj())

                    logger.info('点击"阅读"页面的中间1次...')
                    # AIclick(readbookPage.CenterSectionObj())
                    center_section=readbookPage.CenterSectionObj()
                    # center_section.click()
                    ActionChains(TestRead.browser).move_to_element(center_section).click().perform()
                    time.sleep(2)

                    logger.info('点击右上角更多按钮...')
                    # readbookPage.HeaderMenuObj().click()
                    TestRead.browser.execute_script("arguments[0].click()",readbookPage.HeaderMenuObj())
                    time.sleep(2)

                    try:
                        searchIndexButtonJS = "document.getElementsByClassName('jdr-dropdown-item')[0].click()"
                        TestRead.browser.execute_script(searchIndexButtonJS)
                        time.sleep(2)

                        self.assertIs("<title>精选</title>" in TestRead.browser.page_source,True)
                        logger.info('调起菜单成功!用例通过')

                    except Exception as e:
                        logger.debug('更多按钮操作失败!用例不通过')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_testResult, 'fail', 'red')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_time,
                                                           str(time.time() - start_time) + 'ms', 'red')
                        raise e


                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")
                    raise e

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")
                    raise e

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_Turn_Page(self):
        logger.info("开始执行翻页脚本...")
        #获取是否执行列
        isExecuteUser=TestRead.excelObj.get_col_values(book_isExecute,sheet_name='阅读书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            if i=='Y':
                bookid=TestRead.excelObj.get_cell_value(idx+2,book_id)
                bookname=TestRead.excelObj.get_cell_value(idx+2,book_name)
                logger.info("执行测试数据:%s,%s"%(bookid,bookname))
                try:

                    TestRead.browser.get(pc.getUrl('read')%(bookid,bookname))

                    logger.info('启动浏览器,访问"阅读"页面...')
                    readbookPage = ReadBookPage(TestRead.browser)
                    logger.info('点击"阅读"页面的右侧翻页7次...')

                    for i in range(7):
                        readbookPage.RightSectionObj().click()
                        time.sleep(1)

                    logger.info('点击"阅读"页面的左侧翻页1次...')
                    readbookPage.LeftSectionObj().click()

                    try:
                        title=readbookPage.ChapterTitleObj().text
                        content=readbookPage.ChapterFirstContentObj().text
                        # 章节标题包含:不能在“温室”里培养干部;且内容包含:现在在一些地方,则通过用例
                        self.assertIs((('不能在“温室”里培养干部' in title) and ('现在在一些地方' in content)),True)
                        logger.info('翻页后判断文中内容用例通过')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_testResult, 'success', 'green')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_time, str(round((time.time() - start_time)/1000,2)) + 's')

                    except Exception as e:
                        logger.debug('翻页后判断文中内容用例不通过')
                        TestRead.excelObj.write_cell_value(idx+2,execute_testResult,'fail','red')
                        TestRead.excelObj.write_cell_value(idx + 2, execute_time,str(time.time()-start_time)+'ms', 'red')


                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_Buy_In_Read_Page(self):
        logger.info("开始执行书内购买脚本...")
        #获取是否执行列
        isExecute=TestRead.excelObj.get_col_values(book_isExecute,sheet_name='购买书籍')
        pc = ParseConfigFile()
        buy_success=False

        for idx,i in enumerate(isExecute[1:]):
            start_time=time.time()
            if (not buy_success) and i=='Y':
                bookid = TestRead.excelObj.get_cell_value(idx + 2, book_id)
                buyerUsername=TestRead.excelObj.get_cell_value(idx + 2, buyer_username)
                buyerPassword=TestRead.excelObj.get_cell_value(idx + 2, buyer_password)
                bookname=TestRead.excelObj.get_cell_value(idx + 2, book_name)
                logger.info("执行测试数据:%s,%s,%s" % (bookid,buyerUsername,buyerPassword))

                #通过接口api拿到我的书籍列表中的书
                my_books_data=MyBooks.getData(TestRead.excelObj.get_cell_value(idx + 2, buyer_pin))
                #判断buyer是否已经拥有该书:
                have_flag= bookid in my_books_data
                if have_flag:
                    TestRead.excelObj.write_cell_value(idx + 2, book_isExecute, 'N')
                else:
                    try:

                        TestRead.browser.get(pc.getUrl('read') % (bookid, bookname))
                        logger.info('访问"阅读"页面成功...')
                        time.sleep(2)
                        readbookPage = ReadBookPage(TestRead.browser)
                        readbookPage.CenterSectionObj().click()
                        logger.info('点击中间区域成功...')
                        time.sleep(2)
                        readbookPage.DirButton().click()
                        logger.info('点击目录成功...')
                        chapter_dirs=readbookPage.chapterNeedPayrDirs()

                        if chapter_dirs and len(chapter_dirs)!=0:
                            first_need_pay_chapter=chapter_dirs[1]
                        else:
                            raise NoSuchElementException()

                        ###滚动屏幕,漏出最后一个可读的章节目录,以便点击
                        TestRead.browser.execute_script("arguments[0].scrollIntoView(false);", first_need_pay_chapter)

                        # browser.execute_script(scrollJS1)
                        TestRead.browser.implicitly_wait(5)
                        # scrollJS2 = "window.scrollBy(0,50)"
                        # browser.execute_script(scrollJS2)

                        time.sleep(2)
                        readbookPage.LastChapterFreeDir().click()
                        logger.info('点击最后一章试读章节目录成功...')

                        time.sleep(2)
                        turnPageFlag=True
                        while turnPageFlag:
                            readbookPage.RightSectionObj().click()
                            time.sleep(1)
                            if readbookPage.YesOrNotBuyBookDialog().is_displayed():
                                turnPageFlag=False
                                time.sleep(1)
                                logger.info('打开询问是否购买弹窗成功...')

                        time.sleep(2)
                        readbookPage.BuyBookConfirmButton().click()
                        logger.info('点击确认购买按钮成功...')

                        time.sleep(2)
                        bCanBuy=readbookPage.BuyBookCommitButton().text
                        try:
                            if '确认购买'==bCanBuy:
                                readbookPage.BuyBookCommitButton().click()
                                time.sleep(2)
                                # 通过接口api拿到我的书籍列表中的书
                                my_books_data = MyBooks.getData(TestRead.excelObj.get_cell_value(idx + 2, buyer_pin))
                                # 判断buyer是否已经拥有该书:
                                have_flag = bookid in my_books_data

                                self.assertIs(have_flag,True)
                                logger.info('文内购买书籍用例通过')
                                buy_success=True
                                TestRead.excelObj.write_cell_value(idx+2,book_isExecute,'N')
                                TestRead.excelObj.write_cell_value(idx + 2, execute_testResult, 'success', 'green')
                                TestRead.excelObj.write_cell_value(idx + 2, execute_time, str(round((time.time() - start_time)/1000,2)) + 's')
                            elif '充值并购买' == bCanBuy:
                                logger.warning('余额不足...')
                                buy_success=True
                                text_mail('来自m站自动化测试脚本', '在文内购买书籍测试用例中%s账户余额不足,请及时充值' % (buyerUsername))
                                self.assertTrue(1==2)

                        except AssertionError as e:
                            logger.debug('文内购买书籍用例不通过')
                            TestRead.excelObj.write_cell_value(idx + 2, execute_testResult, 'fail', 'red')
                            TestRead.excelObj.write_cell_value(idx + 2, execute_time,str(time.time() - start_time) + 'ms', 'red')
                            TestRead.excelObj.write_cell_value(idx + 2, book_isExecute, 'N')
                            raise e
                    except ElementNotVisibleException as e:
                        logger.error("数据问题,元素没有找到..")
                    except NoSuchElementException as e:
                        logger.error("数据问题..重试")
                    except Exception as e:
                        logger.error(e)
                        raise e

            else:
                continue

    def test_Buy_In_Read_Page_Not_Enought_Money(self):
        logger.info("开始执行书内购买脚本...")
        #获取是否执行列
        isExecute=TestRead.excelObj.get_col_values(book_isExecute,sheet_name='购买书籍余额不足')
        pc = ParseConfigFile()
        complete_flag=False

        for idx,i in enumerate(isExecute[1:]):
            start_time=time.time()
            if (not complete_flag) and i=='Y':
                bookid = TestRead.excelObj.get_cell_value(idx + 2, book_id)
                buyerUsername=TestRead.excelObj.get_cell_value(idx + 2, buyer_username)
                buyerPassword=TestRead.excelObj.get_cell_value(idx + 2, buyer_password)
                bookname=TestRead.excelObj.get_cell_value(idx + 2, book_name)
                logger.info("执行测试数据:%s,%s,%s" % (bookid,buyerUsername,buyerPassword))

                #通过接口api拿到我的书籍列表中的书
                my_books_data=MyBooks.getData(TestRead.excelObj.get_cell_value(idx + 2, buyer_pin))
                #判断buyer是否已经拥有该书:
                have_flag= bookid in my_books_data
                if have_flag:
                    TestRead.excelObj.write_cell_value(idx + 2, book_isExecute, 'N')
                else:
                    try:

                        TestRead.browser.get(pc.getUrl('read')%(bookid,bookname))

                        logger.info('访问"阅读"页面成功...')

                        time.sleep(2)
                        readbookPage = ReadBookPage(TestRead.browser)
                        readbookPage.CenterSectionObj().click()
                        logger.info('点击中间区域成功...')

                        time.sleep(2)
                        readbookPage.DirButton().click()
                        logger.info('点击目录成功...')

                        time.sleep(2)
                        last_free_chapter=readbookPage.LastChapterNeedPayrDir()
                        TestRead.browser.execute_script("arguments[0].scrollIntoView();", last_free_chapter)
                        last_free_chapter.click()
                        logger.info('点击最后一章试读章节目录成功...')

                        time.sleep(2)
                        turnPageFlag=True
                        while turnPageFlag:
                            readbookPage.RightSectionObj().click()
                            time.sleep(1)
                            if readbookPage.YesOrNotBuyBookDialog().is_displayed():
                                turnPageFlag=False
                                time.sleep(1)
                                logger.info('打开询问是否购买弹窗成功...')

                        time.sleep(2)
                        readbookPage.BuyBookConfirmButton().click()
                        logger.info('点击确认购买按钮成功...')

                        time.sleep(2)
                        canOrNotCanBuy=readbookPage.BuyBookCommitButton().text
                        try:

                            self.assertIs('充值并购买'==canOrNotCanBuy,True)
                            logger.info('文内购买书籍余额不足判断,测试用例通过')
                            TestRead.excelObj.write_cell_value(idx+2,execute_testResult,'success','green')
                            TestRead.excelObj.write_cell_value(idx + 2, execute_time,str(time.time()-start_time)+'ms')
                            complete_flag=True

                        except AssertionError as e:
                            logger.debug('文内购买书籍余额不足判断测试用例不通过')
                            complete_flag=True
                            TestRead.excelObj.write_cell_value(idx + 2, execute_testResult, 'fail', 'red')
                            TestRead.excelObj.write_cell_value(idx + 2, execute_time,str(time.time() - start_time) + 'ms', 'red')
                            TestRead.excelObj.write_cell_value(idx + 2, book_isExecute, 'N')
                            raise e

                    except ElementNotVisibleException as e:

                        logger.error("数据问题,元素没有找到..重试")

                    except NoSuchElementException as e:

                        logger.error("数据问题..重试")

                    except Exception as e:

                        logger.error(e)

                        raise e

            else:
                continue
class testBookDetailNotNeedLogin(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    @classmethod
    @set_phone_model(phone_model)
    def setUpClass(cls) -> None:
        testBookDetailNotNeedLogin.browser = webdriver.Chrome(chrome_options=options)

    @classmethod
    def tearDownClass(cls) -> None:
        testBookDetailNotNeedLogin.browser.quit()

    def setUp(self) -> None:
        pass

    def tearDown(self) -> None:
        pass

    def test_price_free_book(self):
        logger.info("开始执行书详页免费书价格脚本...")

        #获取是否执行列
        isExecuteUser=testBookDetailNotNeedLogin.excelObj.get_col_values(book_isExecute, sheet_name='价格逻辑验证书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            bookType=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_type)
            if 'Y'==i and "免费"==bookType:
                bookid=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_id)
                bookname=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_name)
                logger.info("执行测试数据:%s,%s"%(bookid,bookname))
                try:

                    testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
                    price=bookDetailPage.priceObj()

                    try:

                        self.assertIs(price.is_displayed() and "免费"==price.text,True)
                        logger.info('书详页免费书价格脚本执行成功!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult, 'success', 'green')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time, str(round((time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('书详页免费书价格脚本执行失败!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult, 'fail', 'red')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time, str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_price_no_discount_book(self):
        logger.info("开始执行书详页非折扣书价格脚本...")

        #获取是否执行列
        isExecuteUser=testBookDetailNotNeedLogin.excelObj.get_col_values(book_isExecute, sheet_name='价格逻辑验证书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            bookType=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_type)
            if 'Y'==i and "没折扣"==bookType:
                bookid=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_id)
                bookname=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_name)
                logger.info("执行测试数据:%s,%s"%(bookid,bookname))
                try:
                    testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
                    realprice_obj=bookDetailPage.realPriceObj()
                    # realprice=realprice_obj.text.strip('阅豆')
                    realprice=str(int(round(float(realprice_obj.text.strip('¥'))*100)))
                    api_realprice=str(BookDetai.getData(bookid)['jd_price'])

                    try:

                        self.assertIs(realprice_obj.is_displayed() and api_realprice==realprice,True)
                        logger.info('书详页非折扣书籍脚本执行成功!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult, 'success', 'green')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time, str(round((time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('书详页非折扣书籍价格脚本执行失败!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult, 'fail', 'red')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time, str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_price_sell_out_book(self):
        logger.info("开始执行书详页下柜书价格脚本...")

        #获取是否执行列
        isExecuteUser=testBookDetailNotNeedLogin.excelObj.get_col_values(book_isExecute, sheet_name='价格逻辑验证书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            bookType=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_type)
            if 'Y'==i and "下柜"==bookType:
                bookid=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_id)
                bookname=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_name)
                logger.info("执行测试数据:%s,%s"%(bookid,bookname))
                try:

                    testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
                    price=bookDetailPage.priceObj()

                    try:

                        self.assertIs(price.is_displayed() and "此书已下柜"==price.text,True)
                        logger.info('书详页下柜书价格脚本执行成功!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult, 'success', 'green')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time, str(round((time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('书详页下柜书书价格脚本执行失败!用例不通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult, 'fail', 'red')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time, str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_price_sell_off_book(self):
        logger.info("开始执行书详页打折书价格脚本...")

        pc = ParseConfigFile()

        try:

            # books_data=getDataList('本周特价')
            testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookcity'))

            bookcityPage = BookCityPage(testBookDetailNotNeedLogin.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)

            bookcityPage.channelFeaturedButton().click()
            time.sleep(2)
            bookcityPage.discountButton().click()
            # time.sleep(2)
            # discountPage = DiscountPage(testBookDetailNotNeedLogin.browser)
            # discountPage.first_book().click()

            time.sleep(2)
            current_url=testBookDetailNotNeedLogin.browser.current_url
            collection_id=re.search(r'\d{4}',current_url).group(0)

            collection_data=CollectionDetail.getDataJson(collection_id)


            bookid=str(collection_data['data']['items'][0]['ebook_id'])

            testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))

            logger.info('启动浏览器,访问"书籍详情"页面...')
            bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
            real_price_obj = bookDetailPage.realPriceObj()
            original_price_obj=bookDetailPage.originalPriceObj()
            discount_obj=bookDetailPage.discountObj()
            # color=discount.get_attribute('color')


            api_realprice = str(BookDetai.getData(bookid)['jd_price'])
            api_price = str(BookDetai.getData(bookid)['price'])
            api_discount= str(BookDetai.getData(bookid)['discount'])

            real_price=str(int(round(float(real_price_obj.text.strip('¥')) * 100)))
            original_price=str(int(round(float(original_price_obj.text.strip('¥'))* 100)))
            discount= discount_obj.text

            try:

                self.assertIs(real_price_obj.is_displayed() and api_realprice == real_price, True)
                self.assertIs(original_price_obj.is_displayed() and api_price == original_price, True)
                self.assertIs(discount_obj.is_displayed() and api_discount == discount, True)

                logger.info('书详页折扣书价格脚本执行成功!用例通过')

            except AssertionError as e:
                logger.debug('书详页折扣书价格脚本执行失败!用例通过')

                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_book_cover_author_publish_recmmand_name(self):
        logger.info("开始执行书详页-书籍封面、书名、作者和出版社脚本...")

        #获取是否执行列
        isExecuteUser=testBookDetailNotNeedLogin.excelObj.get_col_values(book_isExecute_book_detail, sheet_name='基本信息验证书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            data_Type=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_type)
            if 'Y'==i :
                bookid=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_id)
                bookname=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_name)
                bookAuthor=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_author)
                bookPublish=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_publish)

                logger.info("执行测试数据:%s,%s,%s,%s"%(bookid,bookname,bookAuthor,bookPublish))
                try:

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))

                    bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
                    book_cover_obj=bookDetailPage.bookCoverObj()
                    book_publish_obj=bookDetailPage.publishObj()
                    book_author_obj=bookDetailPage.authorObj()
                    book_name_obj=bookDetailPage.bookNameObj()
                    book_recommand_obj=bookDetailPage.foldRecommandObj()

                    try:

                        self.assertIs(book_cover_obj.is_displayed(),True)
                        self.assertIs(book_publish_obj.text.strip(string.whitespace)==bookPublish.strip(string.whitespace),True)
                        self.assertIs(book_author_obj.text.strip(string.whitespace)==bookAuthor.strip(string.whitespace),True)
                        self.assertIs(book_name_obj.text.strip(string.whitespace)==bookname.strip(string.whitespace),True)
                        self.assertIs(book_recommand_obj.is_displayed(),True)

                        logger.info('执行书详页-书籍封面、书名、作者和出版社脚本成功!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult_book_detail, 'success', 'green')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time_book_detail, str(round((time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页--书籍封面、书名、作者和出版社脚本失败!用例不通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult_book_detail, 'fail', 'red')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time_book_detail, str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_book_comment(self):
        logger.info("开始执行书详页-书籍评论脚本...")

        #获取是否执行列
        isExecuteUser=testBookDetailNotNeedLogin.excelObj.get_col_values(book_isExecute_book_detail, sheet_name='基本信息验证书籍')
        pc = ParseConfigFile()

        for idx,i in enumerate(isExecuteUser[1:]):
            start_time=time.time()
            data_Type=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_type)
            if 'Y'==i :
                bookid=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_id)
                bookname=testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, book_name)

                logger.info("执行测试数据:%s,%s"%(bookid,bookname))
                try:

                    logger.info('启动浏览器,访问"书籍详情"页面...')
                    testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))
                    bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
                    api_book_comment_stars_count = int(BookDetai.getData(bookid)['star'])
                    api_book_comment_count = int(BookDetai.getData(bookid)['comment_count'])

                    try:
                        if api_book_comment_count > 0:

                            book_comment_stars_obj = bookDetailPage.activeCommentStarObj()
                            book_comment_count_obj = bookDetailPage.commentCountObj()
                            book_comments_count = int(
                                re.search(r'\d+', book_comment_count_obj.text.strip(string.whitespace)).group())

                            self.assertIs(api_book_comment_stars_count==len(book_comment_stars_obj),True)
                            self.assertIs(api_book_comment_count==book_comments_count,True)
                        else:
                            book_comment_text=bookDetailPage.commentCountObj().text
                            self.assertIs("暂无评分"==book_comment_text,True)

                        logger.info('执行书详页-书籍评论脚本成功!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult_book_detail, 'success', 'green')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time_book_detail, str(round((time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-书籍评论脚本失败!用例不通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_testResult_book_detail, 'fail', 'red')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, execute_time_book_detail, str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_activity(self):
        logger.info("开始执行书详页促销活动脚本...")

        pc = ParseConfigFile()

        try:

            # books_data=getDataList('双周特价')
            # books_data=getDataList('本周特价')
            #
            # bookid=str(books_data[0]['ebook_id'])
            testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookcity'))

            book_city_page=BookCityPage(testBookDetailNotNeedLogin.browser)
            book_city_page.discountButton().click()
            time.sleep(1)

            discount_page=WeeklyDiscountPage(testBookDetailNotNeedLogin.browser)
            discount_page.firstBook().click()
            time.sleep(1)
            bookid=re.search(r'[0-9]{8}', testBookDetailNotNeedLogin.browser.current_url).group()


            testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))

            logger.info('启动浏览器,访问"书籍详情"页面...')
            bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
            activity_obj = bookDetailPage.acivityObj()
            activity_text = activity_obj.text.strip(string.whitespace)
            api_activity=BookDetai.getData(bookid)['promotion_msg']

            try:

                self.assertIs(activity_text==api_activity, True)


                logger.info('书详页促销活动脚本执行成功!用例通过')

            except AssertionError as e:
                logger.debug('书详页促销活动脚本执行失败!用例通过')

                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_book_detail_comment(self):
        logger.info("开始执行书详页-书评列表验证脚本...")

        # 获取是否执行列
        isExecuteUser = testBookDetailNotNeedLogin.excelObj.get_col_values(book_isExecute, sheet_name='书详页书评验证书籍')
        pc = ParseConfigFile()

        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if 'Y' == i:
                bookid = testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, catagory_book_id)
                bookname = testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, catagory_book_name)
                username = testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, catagory_acount_username)
                password = testBookDetailNotNeedLogin.excelObj.get_cell_value(idx + 2, catagory_acount_password)

                logger.info("执行测试数据:%s,%s,%s,%s" % (bookid, bookname, username, password))
                try:

                    testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (bookid))

                    logger.info('启动浏览器,访问"书详页"页面...')
                    book_detail_page=BookDetailPage(testBookDetailNotNeedLogin.browser)
                    comment_title=book_detail_page.commentTitleObj()
                    testBookDetailNotNeedLogin.browser.execute_script("arguments[0].scrollIntoView();", comment_title)

                    api_comments=GetTwentycomments.getCommentsByPopular(bookid)
                    api_comments_num=len(api_comments)

                    try:

                        if api_comments_num == 0:
                            no_comment_text = book_detail_page.noCommentTextObj()
                            self.assertIs(no_comment_text.is_displayed(), True)

                        else:

                            if api_comments_num > 3:
                                all_comments_text=book_detail_page.allCommentsTextObj()
                                self.assertIs(all_comments_text.is_displayed(), True)

                            first_comment_user_head=book_detail_page.commentUserHeadImg()
                            first_comment_user_name=book_detail_page.commentUserNameObj()
                            first_comment_user_level=book_detail_page.commentUserLevelObj()
                            first_comment_content=book_detail_page.commentContentObj()
                            first_comment_time=book_detail_page.commentTimeObj()
                            check_result=first_comment_user_head.is_displayed() and \
                                         first_comment_user_name.is_displayed()and \
                                        first_comment_user_level.is_displayed() and \
                                        first_comment_content.is_displayed() and \
                                        first_comment_time.is_displayed()
                            self.assertIs(check_result, True)

                        logger.info('执行书详页-书评列表验证脚本成功!用例通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, catagory_execute_testResult, 'success',
                                                                 'green')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, catagory_execute_time,
                                                                             str(round((time.time() - start_time) / 1000, 2)) + 's')

                    except AssertionError as e:
                        logger.debug('执行书详页-书评列表验证脚本失败!用例不通过')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, catagory_execute_testResult, 'fail', 'red')
                        testBookDetailNotNeedLogin.excelObj.write_cell_value(idx + 2, catagory_execute_time,
                                                                             str(time.time() - start_time) + 'ms', 'red')
                        raise e

                except ElementNotVisibleException as e:

                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:

                    logger.error("数据问题..重试")

                except Exception as e:

                    logger.error(e)

                    raise e
            else:
                continue

    def test_recomment_books(self):
        logger.info("开始执行书详页相关书籍推荐脚本...")

        pc = ParseConfigFile()

        try:

            testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % ('30331055'))

            logger.info('启动浏览器,访问"书籍详情"页面...')
            bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)
            page_recommand_books=[ item for item in bookDetailPage.allRecommandBooksObj()]

            try:

                for i in page_recommand_books:
                    self.assertIs(i.is_displayed(), True)

                logger.info('书详页相关图书推荐脚本执行成功!用例通过')

            except AssertionError as e:
                logger.debug('书详页相关图书推荐脚本执行失败!用例通过')

                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_all_comments(self):
        logger.info("开始执行书详页全部评论脚本...")

        pc = ParseConfigFile()

        try:

            ebookid=30331055

            testBookDetailNotNeedLogin.browser.get(pc.getUrl('allcomments') % (ebookid))

            logger.info('启动浏览器,访问"书籍详情"页面...')
            all_comments_Page = AllCommentPage(testBookDetailNotNeedLogin.browser)
            all_comments_Page_title = all_comments_Page.allCommentsTitle()
            all_comments_Page_write_button = all_comments_Page.writeCommentButton()
            all_comments_page_comments_count = re.search(r'\d+', all_comments_Page.allCommentsCountObj().text).group()
            api_all_comments_count = GetTwentycomments.getData(ebookid)['total']
            check_count = str(all_comments_page_comments_count) == str(api_all_comments_count)
            all_comments_page_sort_by=all_comments_Page.allCommentsSortByObj()
            all_comments_sort_type_change_button=all_comments_Page.allCommentsSortTypeChangeButton()
            all_comments_sort_unselected=all_comments_Page.allCommentsSortUnSelected()
            all_comments_sort_selected=all_comments_Page.allCommentsSortSelected()


            try:

                self.assertIs(all_comments_Page_title.is_displayed(), True)
                self.assertIs(all_comments_Page_write_button.is_displayed(), True)
                self.assertIs(check_count, True)
                check_sort_by_default=all_comments_page_sort_by.text=="按热度"
                self.assertIs(check_sort_by_default, True)
                all_comments_sort_type_change_button.click()
                time.sleep(2)
                all_comments_sort_unselected.click()
                time.sleep(2)
                check_sort_by=all_comments_page_sort_by.text=="按时间"
                self.assertIs(check_sort_by, True)
                api_first_comment=GetTwentycomments.getCommentsByCreattime(ebookid)[0]['comment']
                page_first_comment=all_comments_Page.allCommentsContent()
                if api_first_comment==page_first_comment.text:
                    check_content=True
                else:
                    check_content=False
                self.assertIs(check_content, True)

                first_comment_user_head = all_comments_Page.allCommentsUserHead()
                first_comment_user_name = all_comments_Page.allCommentsUserName()
                first_comment_user_level = all_comments_Page.allCommentsUserLevel()
                first_comment_content = all_comments_Page.allCommentsContent()
                first_comment_time = all_comments_Page.allCommentsTime()
                check_result = first_comment_user_head.is_displayed() and \
                               first_comment_user_name.is_displayed() and \
                               first_comment_user_level.is_displayed() and \
                               first_comment_content.is_displayed() and \
                               first_comment_time.is_displayed()
                self.assertIs(check_result, True)

                logger.info('书详页全部评论脚本执行成功!用例通过')

            except AssertionError as e:
                logger.debug('书详页全部评论脚本执行失败!用例通过')

                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_book_messages(self):
        logger.info("开始执行书详页图书信息脚本...")

        pc = ParseConfigFile()

        try:

            ebookid='30331055'

            testBookDetailNotNeedLogin.browser.get(pc.getUrl('bookdetail') % (ebookid))

            logger.info('启动浏览器,访问"书籍详情"页面...')
            bookDetailPage = BookDetailPage(testBookDetailNotNeedLogin.browser)

            api_book_message={}.fromkeys(['file_size','isbn','publish_time','word_count','format','edition'])
            api_book_message['file_size']=str(BookDetai.getData(ebookid)['file_size'])+'M'
            api_book_message['isbn']=BookDetai.getData(ebookid)['isbn']
            api_book_message['publish_time']=BookDetai.getData(ebookid)['publish_time']
            api_book_message['word_count']=str(round(BookDetai.getData(ebookid)['word_count']/10000,1))+'万'
            api_book_message['format']=BookDetai.getData(ebookid)['format']
            api_book_message['edition']=str(BookDetai.getData(ebookid)['edition'])

            book_Message_Title=bookDetailPage.bookMessageTitle()
            testBookDetailNotNeedLogin.browser.execute_script("arguments[0].scrollIntoView();", book_Message_Title)
            book_File_Size_Label=bookDetailPage.bookFileSizeLabel()
            book_File_Size_Obj=bookDetailPage.bookFileSizeObj()
            book_File_Type_Label=bookDetailPage.bookFileTypeLabel()
            book_File_Type_Obj=bookDetailPage.bookFileTypeObj()
            book_ISBN_Code_Label=bookDetailPage.bookISBNCodeLabel()
            book_ISBN_Code_Obj=bookDetailPage.bookISBNCodeObj()
            book_Chars_Num_Label=bookDetailPage.bookCharsNumLabel()
            book_Chars_Num_Obj=bookDetailPage.bookCharsNumObj()
            book_Public_Time_Label=bookDetailPage.bookPublicTimeLabel()
            book_Public_Time_Obj=bookDetailPage.bookPublicTimeObj()
            book_Public_Times_Label=bookDetailPage.bookPublicTimesLabel()
            book_Public_Times_Obj=bookDetailPage.bookPublicTimesObj()


            try:

                self.assertIs(book_Message_Title.is_displayed(), True)
                self.assertIs(book_File_Size_Label.is_displayed(), True)
                self.assertIs(book_File_Type_Label.is_displayed(), True)
                self.assertIs(book_ISBN_Code_Label.is_displayed(), True)
                self.assertIs(book_Chars_Num_Label.is_displayed(), True)
                self.assertIs(book_Public_Time_Label.is_displayed(), True)
                self.assertIs(book_Public_Times_Label.is_displayed(), True)
                self.assertIs(api_book_message['file_size'] in book_File_Size_Obj.text, True)
                self.assertIs(api_book_message['isbn'] in book_ISBN_Code_Obj.text, True)
                self.assertIs(api_book_message['publish_time'] in book_Public_Time_Obj.text, True)
                self.assertIs(api_book_message['word_count'] in book_Chars_Num_Obj.text, True)
                self.assertIs(api_book_message['format'] in book_File_Type_Obj.text, True)
                self.assertIs(api_book_message['edition'] in book_Public_Times_Obj.text+'未知', True)

                logger.info('书详页相关图书推荐脚本执行成功!用例通过')

            except AssertionError as e:
                logger.debug('书详页相关图书推荐脚本执行失败!用例通过')

                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e
 def setUp(self):
     self.excelObj = ParseExcel()
     self.excelObj.load_workbook(dataFilePath001)
Beispiel #17
0
class GetRequestData(object):
    def __init__(self, filePath):
        # 创建解析Excel工具类的实例对象
        self.parseEx = ParseExcel()
        # 将数据文件Excel加载到内存
        self.parseEx.loadWorkBook(filePath)
        self.apiSheetFileName = ""
        self.apiName = ""
        self.requestMethod = ""
        self.requestUrl = ""
        self.paramsInfo = ""
        self.reponseDataStore = {}
        self.CheckPoint = {}

    def getApi(self):
        # 通过Excel工具类中提供的getSheetByName方法获取数据文件中存放api工作表的对象
        apiSheetObject = self.parseEx.getSheetByName(ApiSheetName)
        # 获取api表中是否需要执行列对象
        isExecColObj = self.parseEx.getColumn(apiSheetObject, API_isExecute)
        # print('isExecColObj=',isExecColObj)
        for idx, col in enumerate(isExecColObj[1:]):
            print('idx=', idx)
            if col.value == "y":
                # 如果单元格的值为y,说明该行的api需要被执行

                # 依次获取需要执行api的行对象,以便拿到请求api的相关数据
                rowObj = self.parseEx.getRow(apiSheetObject, idx + 2)
                # API_name等变量定义在GloableData里面
                self.apiName = rowObj[API_name - 1].value
                self.requestUrl = rowObj[API_requestUrl - 1].value
                self.requestMethod = rowObj[API_requestMothod - 1].value
                self.paramsInfo = rowObj[API_paramsInfo - 1].value
                apiTestCasefileName = rowObj[API_requestDataFile - 1].value
                print(self.apiName, self.requestUrl, self.requestMethod,
                      self.paramsInfo, apiTestCasefileName)
                self.getTestCase(apiTestCasefileName)
            else:
                print(u"接口【" + rowObj[API_name - 1].value + u"】被忽略执行")

    def getTestCase(self, testCaseSheetName):
        try:
            # 根据测试用例sheet名获取sheet对象
            testCaseObj = self.parseEx.getSheetByName(testCaseSheetName)
            # 获取测试用例表中是否执行列对象
            isExeccolObj = self.parseEx.getColumn(testCaseObj,
                                                  TestCase_isExecute)
            for t_idx, t_col in enumerate(isExeccolObj[1:]):
                # 依次遍历测试用例表中的测试用例行,需要执行则执行
                if t_col.value == "y":
                    # 如果测试用例单元格值为y,说明该行测试用例需要被执行
                    rowObj = self.parseEx.getRow(testCaseObj, t_idx + 2)
                    RequestHeaders = rowObj[TestCase_requestHeaders - 1].value
                    HeadersEncrypt = rowObj[TestCase_headersEncrypt - 1].value
                    RequestData = rowObj[TestCase_requestData - 1].value
                    # 如果没有内容,得到的将是None,如果有内容,根据我们自己定义的规则,得到将是一个字符串字典类型数据"{xxx}"
                    BodyEncrypt = rowObj[TestCase_bodyEncrypt - 1].value

                    ResponseDecrypt = rowObj[TestCase_responseDecrypt -
                                             1].value
                    DependDataStore = rowObj[TestCase_DependDataStore -
                                             1].value
                    self.CheckPoint = rowObj[TestCase_checkPoint - 1].value
                    print(RequestHeaders, RequestData, DependDataStore,
                          self.CheckPoint)

                    RequestHeaders = ast.literal_eval(RequestHeaders) if (
                        RequestHeaders) else None
                    RequestData = ast.literal_eval(RequestData) if (
                        RequestData) else None
                    print('111111111111', type(RequestData))
                    HeadersEncrypt = ast.literal_eval(HeadersEncrypt) if (
                        HeadersEncrypt) else None
                    BodyEncrypt = ast.literal_eval(BodyEncrypt) if (
                        BodyEncrypt) else None

                    if BodyEncrypt and RequestData:
                        # 对请求参数进行加密处理,如果需要的话
                        RequestData = paramsOper(RequestData, BodyEncrypt)
                        print("sdfd = ", type(RequestData))
                    if HeadersEncrypt and RequestHeaders:
                        # 对头信息进行加密处理,如果需要的话
                        RequestHeaders = paramsOper(RequestHeaders,
                                                    HeadersEncrypt)
                        print(RequestHeaders)
                    # 数据存储
                    if DependDataStore:
                        DependDataStore = ast.literal_eval(DependDataStore)
                        if isinstance(DependDataStore,
                                      dict) and "request" in DependDataStore:
                            requestDataStore = {
                                "request": DependDataStore["request"]
                            }

                            d = DataStore()
                            print("sdfd = ", type(RequestData))
                            # storage(self, fileName, ApiName, sourceData, sourceDataIndex, needStoreData)
                            d.storage(ApiSheetName, self.apiName, RequestData,
                                      t_idx + 1, requestDataStore)
                        elif isinstance(
                                DependDataStore,
                                dict) and "response" in DependDataStore:
                            self.reponseDataStore = {
                                "response": DependDataStore["response"]
                            }
                        else:
                            print(u"存储数据数据规则错误")
                    else:
                        print(u"不需要存储依赖数据")
                    # 处理完请求参数以及依赖数据存储后,接下来该发送接口请求了
                    self.sendRequest(RequestData, RequestHeaders, t_idx + 1)
                else:
                    print(u"测试用例文件【" + testCaseSheetName + "】中第%d条用例被忽略执行" %
                          (t_idx + 1))
        except Exception as e:
            raise e

    def sendRequest(self, RequestData, RequestHeaders, index):
        dataFormat, paramType, dataOper = "", "", ""
        res = self.paramsInfo.split("_")
        if len(res) == 3:
            dataFormat, paramType, dataOper = res
        elif len(res) == 2:
            dataFormat, paramType = res
            print('dataFormat, paramType=', dataFormat, paramType)
        elif len(res) == 1:
            dataFormat = res[0]
            print('dataFormat=', dataFormat)
        if dataOper == "json":
            RequestData = json.dumps(RequestData)
        elif dataFormat == 'data':
            if type(RequestData) == str:
                RequestData = ast.literal_eval(RequestData)

        httpC = HttpClient()
        # requestMethod, requesturl, paramMethod = None, requestData = None, headers = None, ** kwargs
        responseObj = httpC.request(self.requestMethod,
                                    self.requestUrl,
                                    paramType,
                                    RequestData,
                                    RequestHeaders,
                                    timeout=10)
        print(responseObj.json())
        print(responseObj.text)
        print(type(responseObj.text))
        self.ReponseDataStore(responseObj.text, index)

    def ReponseDataStore(self, responseObj, index):
        if self.reponseDataStore:
            d = DataStore()
            # fileName, ApiName, sourceData, sourceDataIndex, needStoreData
            if type(responseObj) == str:
                RequestData = ast.literal_eval(responseObj)
            d.storage(ApiSheetName, self.apiName, responseObj, index,
                      self.reponseDataStore)
        checkPoint = ast.literal_eval(
            self.CheckPoint) if self.CheckPoint else {}
    contactIsExecute as contactIsExecute,
    contactName as contactName,
    contactMail as contactMail,
    contactStar as contactStar,
    contactPhone as contactPhone,
    contactComment as contactComment,
    contactKeyWords as contactKeyWords,
    contactTestResult as contactTestResult
)
from util.ParseExcel import ParseExcel
from util.RecordLog import Logger
from pages.base import Base


log = Logger(__name__, logging.INFO)
do_excel = ParseExcel()
sheetName = do_excel.wb.sheetnames  # 获取所有的sheetname 是个列表


def test_mail_login():
    """测试用例"""
    driver = webdriver.Firefox()
    base = Base(driver)
    base.open_url()
    login_action = LoginAction(driver)
    add_contact = NewAction(driver)
    # 是否执行列数据
    is_execute = do_excel.get_column_value(sheetName[0], accountIsExecute)
    data_book = do_excel.get_column_value(sheetName[0], accountDataBook)
    for idx, value in enumerate(is_execute[:]):
        # print(idx, value) # 获取是否执行列数据列表的索引和数据
Beispiel #19
0
class executeScriptWithPC(object):
    #针对pc环境的脚本执行操作
    def __init__(self, FilePath):
        # 创建解析Excel对象
        self.excelObj = ParseExcel()
        self.excelFile = FilePath
        self.excelObj.loadWorkBook(FilePath)

    def executeStep(self, stepSheet, step, stepDescribe, keyWord, locationType,
                    locatorExpression, operateValue):
        #执行web主流程测试步骤,并记录测试结果到excel文件中
        #初始化执行语句表达式为空
        expressionStr = ""
        # 构造需要执行的python语句,
        # 对应的是PageAction.py文件中的页面动作函数调用的字符串表示
        if keyWord and operateValue and locationType is None and locatorExpression is None:
            expressionStr = keyWord.strip() + "('" + operateValue + "')"
        elif keyWord and operateValue is None and locationType is None and locatorExpression is None:
            expressionStr = keyWord.strip() + "()"
        elif keyWord and locationType and operateValue and locatorExpression is None:
            expressionStr = keyWord.strip() + "('" + locationType.strip(
            ) + "', '" + operateValue + "')"
        elif keyWord and locationType and locatorExpression and operateValue:
            expressionStr = keyWord.strip() + "('" + locationType.strip(
            ) + "', '" + locatorExpression.replace(
                "'", '"').strip() + "', '" + operateValue + "')"
        elif keyWord and locationType and locatorExpression and operateValue is None:
            expressionStr = keyWord.strip() + "('" + locationType.strip(
            ) + "', '" + locatorExpression.replace("'", '"').strip() + "')"
        print(expressionStr)
        try:
            eval(expressionStr)
            # 在测试执行时间列写入执行时间
            self.excelObj.writeCellCurrentTime(stepSheet,
                                               rowNo=step,
                                               colsNo=testStep_runTime)
        except Exception as err:
            # 截取异常屏幕图片
            capturePic = capture_screen()
            # 获取详细的异常堆栈信息
            errorInfo = traceback.format_exc()
            # 在测试步骤Sheet中写入失败信息
            writeTestResult(self.excelObj, stepSheet, step, "pc", "faild",
                            errorInfo, capturePic)
            info("步骤“%s”执行失败! 函数执行表达式为:%s" % (stepDescribe, expressionStr))
        else:
            # 在测试步骤Sheet中写入成功信息
            writeTestResult(self.excelObj, stepSheet, step, "pc", "pass")
            info("步骤“%s”执行通过!函数执行表达式为:%s" % (stepDescribe, expressionStr))

    def execute(self, caseStepSheetName):
        #根据测试sheetName,遍历表单中的测试步骤
        try:
            # 根据用例步骤名获取步骤sheet对象
            info('开始<%s>场景的测试...' % caseStepSheetName)
            stepSheet = self.excelObj.getSheetByName(caseStepSheetName)
            # 获取步骤sheet中步骤数
            stepNum = self.excelObj.getRowsNumber(stepSheet)
            for step in range(2, stepNum + 1):
                # 因为步骤sheet中的第一行为标题行,无需执行
                # 获取步骤sheet中第step行对象
                stepRow = self.excelObj.getRow(stepSheet, step)
                #获取测试步骤描述
                stepDescribe = stepRow[testStep_testStepDescribe - 1].value
                # 获取关键字作为调用的函数名
                keyWord = stepRow[testStep_keyWords - 1].value
                # 获取操作元素定位方式作为调用的函数的参数
                locationType = stepRow[testStep_locationType - 1].value
                # 获取操作元素的定位表达式作为调用函数的参数
                locatorExpression = stepRow[testStep_locatorExpression -
                                            1].value
                # 获取操作值作为调用函数的参数
                operateValue = stepRow[testStep_operateValue - 1].value
                # 将操作值为数字类型的数据转成字符串类型,方便字符串拼接
                if isinstance(operateValue, int):
                    operateValue = str(operateValue)
                #列出execute函数的入参
                args = stepSheet, step, stepDescribe, keyWord, locationType, locatorExpression, operateValue
                self.executeStep(*args)
        except Exception as err:
            # 打印详细的异常堆栈信息
            debug(traceback.print_exc())
        finally:
            eval("close_browser()")  #最终关闭浏览器

    def getOrderId(self):
        #获取订单号
        #参数在varConfig全局配置中定义
        return getAttr(expression_type, expression_str, expression_value)
Beispiel #20
0
# encoding=utf-8
from action.PageAction import *
from util.ParseExcel import ParseExcel
from config.VarConfig import *
import time
import traceback

#创建解析Excel对象

excelObj = ParseExcel()


#用例或用例步骤执行结束后,像excel中执行结果信息
def writeTestResult(sheetObj,
                    rowNo,
                    colsNo,
                    testResult,
                    errorInfo=None,
                    picPath=None):
    #测试通过结果为绿色,失败为红色
    colorDict = {"pass": "******", "failed": "red", "none": "green"}

    # 因为“测试用例”工作表和“用例步骤Sheet表”中都有测试执行时间和测试
    # 测试结果列,定义此字典对象是为了区分具体应该写哪个工作表
    colsDict = {
        "testCase": [testCase_runTime, testCase_testResult],
        "caseStep": [testStep_runTime, testStep_testResult],
        "dataSheet": [dataSource_runtime, dataSource_result]
    }
    try:
        # 在测试步骤sheet中,写入测试时间
Beispiel #21
0
import traceback
import logging

from action.PageAction import *
from config.VarConfig import (testCase_testIsExecute, testCase_testStepName,
                              testStep_testNum, testStep_testStepDescribe,
                              testStep_keyWord, testStep_elementBy,
                              testStep_elementLocator, testStep_operateValue,
                              testCase_testResult, smtp_server, port, sender,
                              psw, receiver, excelPath)
from util.log import Logger
from util.ParseExcel import ParseExcel

log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
p = ParseExcel()
sheetName = p.wb.sheetnames  # 获取到excel的所有sheet名称


def test_126_mail_send_with_att():
    try:
        test_case_pass_num = 0
        required_case = 0
        is_execute_column_values = p.get_column_value(
            sheetName[0], testCase_testIsExecute)  #获取该行是都需要执行
        print(is_execute_column_values)
        # print(columnValues)
        for index, value in enumerate(is_execute_column_values):
            print(index, value)
            # 获取对应的步骤sheet名称
            step_sheet_name = p.get_cell_of_value(sheetName[0], index + 2,
                                                  testCase_testStepName)
 def setUp(self):
     # 创建解析excel对象
     self.excelObj = ParseExcel()
     # 将excel数据加载到内存
     self.excelObj.load_workbook(dataFilePath002)
Beispiel #23
0
class TestCase(object):

    # 构造函数
    def __init__(self):
        self.parseExcel = ParseExcel()
        self.log = Log()
        self.select = SelectTheSorting()
        self.pa = PageAction()
        self.pj = ParseJson()
        self.rm = RequestMethod()

    # 加载测试用例
    # @app.task
    def ruCase(self, area, branch):
        '''

        :return: 运行测试用例
        '''
        # select = SelectTheSorting()
        self.select.selectSort(area, branch)
        startTime, excel_id, excel_step, excel_motion, excel_locatorExpression, \
        excel_hoverLocator, excel_value, excel_expect, excel_getText, \
        excel_locatorExpressionResult, excel_runResult = self.parseExcel.getCaseData()
        self.log.info("用例开始时间:" + startTime)
        # print(excel_id)
        # print(excel_step)
        # print(excel_motion)
        # print(len(excel_id))
        # print(excel_getText)
        caseNum = len(excel_id) - 1
        pass_count = []
        fail_count = []
        exception = []
        for i in range(len(excel_id)):
            # print(i)
            id = str(excel_id[i])
            step = excel_step[i]
            motion = excel_motion[i]
            # print(motion)
            locatorExpression = excel_locatorExpression[i]
            hoverLocator = excel_hoverLocator[i]
            value = excel_value[i]
            getText = excel_getText[i]
            # print(getText)
            expect = excel_expect[i]
            locatorExpressionResult = excel_locatorExpressionResult[i]
            # print(locatorExpressionResult)
            if motion == "click":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "click_bottom":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "click_top":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "input":
                if value == 'number':
                    self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression,
                                       value=self.pj.getJsonData(value))
                    result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                    try:
                        if self.pj.getJsonData(value) in result:
                            self.parseExcel.writeCell(i + 2, 10, "pass")
                            self.log.info("第" + id + "步:" + step + "-----pass")
                            pass_count.append(i)
                        else:
                            self.parseExcel.writeCell(i + 2, 10, "fail")
                            self.log.info("第" + id + "步:" + step + "-----fail")
                            fail_count.append(i)
                            self.pa.pageMotion(motion='quit')
                            break
                    except:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----exception")
                        exception.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                    self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)
                else:
                    self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression, value=value)
                    result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                    if isinstance(expect, int):
                        expect = str(expect)
                        try:
                            if expect in result:
                                self.parseExcel.writeCell(i + 2, 10, "pass")
                                self.log.info("第" + id + "步:" + step + "-----pass")
                                pass_count.append(i)

                            else:
                                self.parseExcel.writeCell(i + 2, 10, "fail")
                                self.log.info("第" + id + "步:" + step + "-----fail")
                                fail_count.append(i)
                                self.pa.pageMotion(motion='quit')
                                break
                        except:
                            self.parseExcel.writeCell(i + 2, 10, "fail")
                            self.log.info("第" + id + "步:" + step + "-----exception")
                            exception.append(i)
                            self.pa.pageMotion(motion='quit')
                            break
                        self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)
                    else:
                        try:
                            if expect in result:
                                self.parseExcel.writeCell(i + 2, 10, "pass")
                                self.log.info("第" + id + "步:" + step + "-----pass")
                                pass_count.append(i)

                            else:
                                self.parseExcel.writeCell(i + 2, 10, "fail")
                                self.log.info("第" + id + "步:" + step + "-----fail")
                                fail_count.append(i)
                                self.pa.pageMotion(motion='quit')
                                break
                        except:
                            self.parseExcel.writeCell(i + 2, 10, "fail")
                            self.log.info("第" + id + "步:" + step + "-----exception")
                            exception.append(i)
                            self.pa.pageMotion(motion='quit')
                            break
                        self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "hover":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "double_click":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break

                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break
                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "double_click_esc":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "enter":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "top":
                self.pa.pageMotion(motion=motion)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "click_esc":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "click_role":
                self.select.role()
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "步" + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "click_sleep":
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "click_await":
                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)
                self.pa.pageMotion(motion=motion, locatorExpression=locatorExpression)
                result = self.pa.pageMotion(motion=getText, locatorExpression=locatorExpressionResult)
                try:
                    if expect in result:
                        self.parseExcel.writeCell(i + 2, 10, "pass")
                        self.log.info("第" + id + "步:" + step + "-----pass")
                        pass_count.append(i)
                    else:
                        self.parseExcel.writeCell(i + 2, 10, "fail")
                        self.log.info("第" + id + "步:" + step + "-----fail")
                        fail_count.append(i)
                        self.pa.pageMotion(motion='quit')
                        break
                except:
                    self.parseExcel.writeCell(i + 2, 10, "fail")
                    self.log.info("第" + id + "步:" + step + "-----exception")
                    exception.append(i)
                    self.pa.pageMotion(motion='quit')
                    break

                self.rm.runMethod(caseCount=caseNum, startTime=startTime, casePresent=id)

            elif motion == "quit":
                self.parseExcel.writeCell(i + 2, 10, "pass")
                self.pa.pageMotion(motion=motion)

        excelstartTime, excelid, excelstep, excelmotion, excellocatorExpression, \
        excelhoverLocator, excelvalue, excelexpect, excelgetText, \
        excellocatorExpressionResult, runResult = self.parseExcel.getCaseData()

        # endTime = datetime.datetime.now()
        endTime = time.strftime('%Y-%m-%d %H:%M:%S')

        self.log.info("用例结束时间:" + endTime)
        # sumCase = len(pass_count) + len(fail_count)
        pr = len(pass_count) / caseNum
        # passingRate = '{:.0%}'.format(pr)
        passingRate = "%.2f" % pr
        fr = len(fail_count) / caseNum
        # failureRate = '{:.0%}'.format(fr)
        failureRate = "%.2f" % fr
        print(failureRate)
        self.log.info("用例通过条数" + str(len(pass_count)))
        self.log.info("用例失败条数:" + str(len(fail_count)))
        self.log.info("xpath定位失败:" + str(len(exception)))
        message = None
        if len(pass_count) == caseNum:
            message = 1  # 1代表成功

        if len(fail_count) > 0:
            message = 2  # 2代表失败

        if len(exception) > 0:
            message = 3  # 3代表未找到定位元素

        # print(message)
        return startTime, endTime, caseNum, len(pass_count), len(fail_count), passingRate, failureRate, \
               excel_id, excel_step, excel_motion, excel_locatorExpression, excel_value, excel_expect, excel_getText, \
               excel_locatorExpressionResult, runResult, message
Beispiel #24
0
 def __init__(self, FilePath):
     # 创建解析Excel对象
     self.excelObj = ParseExcel()
     self.excelFile = FilePath
     self.excelObj.loadWorkBook(FilePath)
class AddContract(unittest.TestCase):
    def setUp(self):
        # 创建解析excel对象
        self.excelObj = ParseExcel()
        # 将excel数据加载到内存
        self.excelObj.load_workbook(dataFilePath002)

    def tearDown(self):
        pass

    def launch_broswer(self):
        # 创建Chrome浏览器的一个Options实例对象
        chrome_options = Options()
        # 向Options实例中添加禁用扩展插件的设置参数项
        chrome_options.add_argument("--disable-extensions")
        # 添加屏蔽--ignore-certificate-errors提示信息的设置参数项
        chrome_options.add_experimental_option("excludeSwitches",
                                               ["ignore-certificate-errors"])
        # 添加浏览器最大化的设置参数项,一启动就最大化
        chrome_options.add_argument('--start-maximized')
        # 启动带有自定义设置的Chrome浏览器
        driver = webdriver.Chrome(chrome_options=chrome_options)
        # 访问51kaihui首页
        driver.get('https://www.51kaihui.com/login/index')
        sleep(3)
        return driver

    def test_add_contract(self):
        logging.info(u'添加联系人数据驱动测试开始')
        try:
            # 根据excel文件中sheet名称获取此sheet的对象
            user_sheet = self.excelObj.get_sheetbyname(u'账号')
            # 获取账号是否执行
            is_execute_user = self.excelObj.get_column(user_sheet,
                                                       account_isExecute)
            # 获取账号sheet中的数据表列
            data_book_column = self.excelObj.get_column(
                user_sheet, account_dataBook)
            for idx, i in enumerate(is_execute_user[1:]):
                # 循环遍历账号表中的账号,为需要执行的账号添加联系人
                if i == "y":  # 表示要执行
                    # 获取第i行的数据
                    user_row = self.excelObj.get_row(user_sheet, idx + 2)
                    # print(type(user_row))
                    # print(user_row[1])
                    # 获取第i行用户名
                    username = user_row[account_username - 1]
                    # 获取第i行密码
                    password = str(user_row[account_password - 1])

                    # 创建浏览器实例对象
                    driver = self.launch_broswer()
                    logging.debug(u'启动浏览器,访问主页')

                    # 登录邮箱
                    LoginAction.login(d=driver,
                                      username=username,
                                      password=password)
                    logging.debug(u'用户%s密码%s正在进行登录' % (username, password))
                    sleep(3)
                    try:
                        assert u'通讯录' in driver.page_source
                        logging.info(u'用户%s登录成功' % username)
                    except AssertionError as e:
                        logging.info(u'用户%s登录失败, 异常信息:%s' %
                                     (username, str(traceback.format_exc())))
                        self.excelObj.write_cell(
                            user_sheet,
                            'failed',
                            row_number=idx + 2,
                            column_number=account_testResult,
                            style='red')

                    # 获取第i行用户要添加的联系人数据表sheet名
                    data_book_name = data_book_column[idx + 1]
                    # 获取对应的数据表对象
                    data_sheet = self.excelObj.get_sheetbyname(data_book_name)
                    # 获取联系人数据表中联系人是否执行
                    is_execute_data = self.excelObj.get_column(
                        data_sheet, contracts_isExecute)

                    contract_num = 0  # 记录添加成功联系人个数
                    is_execute_num = 0  # 记录需要执行联系人个数

                    for id, data in enumerate(is_execute_data[1:]):
                        # 获取第id+2行对象
                        row_content = self.excelObj.get_row(data_sheet, id + 2)
                        # 获取联系人姓名
                        contract_person_name = row_content[
                            contracts_contractName - 1]
                        # 获取联系人电话
                        contracts_person_mobile = row_content[
                            contracts_contractMobile - 1]
                        # 获取联系人备注
                        contracts_person_email = row_content[
                            contracts_contractEmail - 1]
                        # 添加联系人后断言的关键字
                        assert_keywords = row_content[contracts_assertKeyWords
                                                      - 1]

                        # 寻黄遍历是否执行添加联系人列,如果被设置为添加,则进行添加
                        if data == 'y':
                            logging.debug(u'用户 %s 需要添加联系人对象 %s' %
                                          (username, contract_person_name))
                            # 如果第id行被设置为执行,则is_execute_num自增1
                            is_execute_num += 1

                            # 执行添加联系人操作
                            AddContractPerson.add(
                                d=driver,
                                contract_name=contract_person_name,
                                contract_mobile=contracts_person_mobile,
                                contract_memo=contracts_person_email)
                            sleep(1)
                            logging.debug(u'用户 %s 添加联系人对象名字%s电话%s邮箱%s' %
                                          (username, contract_person_name,
                                           contracts_person_mobile,
                                           contracts_person_email))

                            # 在联系人工作表写入添加联系人执行时间
                            self.excelObj.write_cell_currenttime(
                                data_sheet,
                                row_number=id + 2,
                                column_number=contracts_runTime)
                            try:
                                # 断言给定的关键字是否出现在页面中
                                assert assert_keywords in driver.page_source
                            except AssertionError as e:
                                # 断言失败,在联系人工作表中写入添加联系人测试失败信息
                                self.excelObj.write_cell(
                                    data_sheet,
                                    'failed',
                                    row_number=id + 2,
                                    column_number=contracts_testResult,
                                    style='red')
                                logging.info(
                                    u'用户 %s 添加联系人%s失败' %
                                    (username, contract_person_name), e)
                            else:
                                # 断言成功,写入添加联系人信息成功
                                self.excelObj.write_cell(
                                    data_sheet,
                                    'pass',
                                    row_number=id + 2,
                                    column_number=contracts_testResult,
                                    style='green')
                                contract_num += 1
                                logging.debug(u'用户 %s 添加联系人%s成功' %
                                              (username, contract_person_name))
                        else:
                            logging.debug(u'用户 %s 不需要添加联系人对象 %s' %
                                          (username, contract_person_name))

                        logging.debug(
                            '需要添加的联系人个数contractNum为 = %s, 添加成功的联系人个数isExecuteNum为 = %s'
                            % (contract_num, is_execute_num))

                        if contract_num == is_execute_num:
                            # 如果成功添加联系人个数等于需要添加的联系人个数,说明给第i个用户添加联系人的用力执行成功
                            # 在账号工作表写入成功信息,否则写入失败信息
                            self.excelObj.write_cell(
                                user_sheet,
                                'pass',
                                row_number=idx + 2,
                                column_number=account_testResult,
                                style='green')
                            logging.debug(u'为用户%s 添加 %d个联系人,测试通过' %
                                          (username, contract_num))
                        else:
                            self.excelObj.write_cell(
                                user_sheet,
                                'failed',
                                row_number=idx + 2,
                                column_number=account_testResult,
                                style='red')
                            logging.info(u'为用户%s 添加 %d个联系人,测试失败' %
                                         (username, contract_num))
                    driver.quit()

                    logging.info(u'为用户%s 添加 %d个联系人,测试通过' %
                                 (username, contract_num))

                else:
                    logging.info(u'用户%s被设置为忽略执行' %
                                 self.excelObj.get_cell_value(
                                     user_sheet,
                                     row_number=idx + 2,
                                     column_number=account_username))
        except Exception as e:
            logging.info(u'数据驱动框架主程序发生异常,异常信息为:', e)
            logging.info(traceback.print_exc())
Beispiel #26
0
class TestAddDoctor(unittest.TestCase):

    excelObj = ParseExcel(dataFilePath)

    @classmethod
    def setUpClass(cls) -> None:
        TestAddDoctor.browser = webdriver.Chrome()
        TestAddDoctor.browser.maximize_window()
        logger.info("开始登陆...")
        TestAddDoctor.browser.get(loginpageUrl)
        TestAddDoctor.login_cookie = LoginAction.login(account, password,
                                                       TestAddDoctor.browser)

    @classmethod
    def tearDownClass(cls) -> None:
        TestAddDoctor.browser.quit()

    def test_AddDoctor(self):
        logger.info("开始执行添加医生脚本...")
        #获取是否执行列
        isExecuteUser = TestAddDoctor.excelObj.get_col_values(
            adddoctor_isExecute, sheet_name='添加医师')
        pc = ParseConfigFile()
        for idx, i in enumerate(isExecuteUser[1:]):
            start_time = time.time()
            if i == 'Y':
                doctorName = TestAddDoctor.excelObj.get_cell_value(
                    idx + 2, doctor_name)
                doctorIDNumber = TestAddDoctor.excelObj.get_cell_value(
                    idx + 2, doctor_IdNumber)
                doctorNumber = TestAddDoctor.excelObj.get_cell_value(
                    idx + 2, doctor_Number)
                doctorPhoneNumber = TestAddDoctor.excelObj.get_cell_value(
                    idx + 2, doctor_phoneNumber)
                doctorEmail = TestAddDoctor.excelObj.get_cell_value(
                    idx + 2, doctor_email)
                doctorRemarks = TestAddDoctor.excelObj.get_cell_value(
                    idx + 2, doctor_remarks)
                logger.info("执行测试数据:%s,%s,%s,%s,%s,%s" %
                            (doctorName, doctorIDNumber, doctorNumber,
                             doctorPhoneNumber, doctorEmail, doctorRemarks))
                try:
                    TestAddDoctor.browser.get(pc.getUrl('AddDoctorPageUrl'))
                    logger.info('启动浏览器,访问添加医生页面...')
                    # 如果在在医生管理列表查询刚添加的医生,则通过测试用例,如果没找到该医生则测试用例未通过
                    queryDoctor = QueryDoctorAction(TestAddDoctor.browser)
                    # queryDoctor.QueryDoctorAutoAction()
                    queryDoctor.QueryDoctorAction(doctorName, doctorIDNumber,
                                                  doctorNumber,
                                                  doctorPhoneNumber,
                                                  doctorEmail, doctorRemarks)
                    doctormanagerpage = DoctorManagePage(TestAddDoctor.browser)
                    logger.info('在医生管理列表查询刚添加的医生')
                    try:
                        self.assertEqual(
                            doctormanagerpage.doctorQueryInfoTd().text,
                            doctorNumber, True)
                        # doctorNumberAuto = AddDoctorAction(TestAddDoctor.browser).get_doctorNumberAuto()
                        # self.assertEqual(doctormanagerpage.doctorQueryInfoTd().text, doctorNumberAuto, True)
                        logger.info('在医生管理列表查询到刚添加的医生,成功,用例通过')
                        TestAddDoctor.excelObj.write_cell_value(
                            idx + 2, adddoctor_testResult, 'success', 'green')
                        TestAddDoctor.excelObj.write_cell_value(
                            idx + 2, adddoctor_time,
                            str(round(
                                (time.time() - start_time) / 1000, 2)) + 's')

                    except Exception as e:
                        # self.assertTrue(1 == 2)
                        logger.debug('在医生管理列表查询不到刚添加的医生,失败,用例不通过')
                        TestAddDoctor.excelObj.write_cell_value(
                            idx + 2, adddoctor_testResult, 'fail', 'red')
                        TestAddDoctor.excelObj.write_cell_value(
                            idx + 2, adddoctor_time,
                            str(time.time() - start_time) + 's', 'red')
                        raise e

                except ElementNotVisibleException as e:
                    logger.error("数据问题,元素没有找到..")

                except NoSuchElementException as e:
                    logger.error("数据问题..重试")

                except Exception as e:
                    logger.error(e)
                    raise e
#encoding = utf-8
import traceback
from action.PageAction import *
import time
from config.VarConfig import *
from util.ParseExcel import ParseExcel
from util.Log import *

#创建解析Excel对象
excelObj = ParseExcel()
#将Excel数据文件加载到内存
excelObj.loadWorkBook(dataFilePath)


#用例或用例步骤执行结束后,向Excel中写执行结果信息
def writeTestResult(sheetObj,
                    rowNo,
                    colsNo,
                    testResult,
                    errorInfo=None,
                    picPath=None):

    #测试通过结果信息为绿色,失败为红色
    colorDict = {"pass": "******", "faild": "red"}

    #因为"测试用例"工作表和"用例步骤sheet表"中都有测试执行时间和测试结果列,定义此字典对象是为了区分具体应该写哪个工作表
    colsDict = {
        "testCase": [testCase_runTime, testCase_testResult],
        "caseStep": [testStep_runTime, testStep_testResult]
    }
    try:
Beispiel #28
0
class TestBookCity(unittest.TestCase):
    excelObj = ParseExcel(dataFilePath)

    @classmethod
    @set_phone_model(phone_model)
    def setUpClass(cls) -> None:
        TestBookCity.browser = webdriver.Chrome(chrome_options=options)
        logger.info("开始登陆...")
        TestBookCity.browser.get("https://plogin.m.jd.com/user/login.action")
        TestBookCity.login_cookie = LoginAction.login(not_vip_username,
                                                      not_vip_password,
                                                      TestBookCity.browser)

    @classmethod
    def tearDownClass(cls) -> None:
        TestBookCity.browser.quit()

    def setUp(self) -> None:
        pass

    def tearDown(self) -> None:
        pass

    def test_More_Tools_Button(self):
        logger.info("开始执行唤起更多工具按钮脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)

            logger.info('点击右上角更多按钮...')
            bookcityPage.toolButtonObj().click()

            try:

                self.assertIs(bookcityPage.firstPageButtonObj().is_displayed(),
                              True)
                logger.info('调起菜单成功!用例通过')

            except AssertionError as e:
                logger.debug('更多按钮操作失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_Switch_Channel_Button(self):
        logger.info("开始执行频道切换按钮脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)

            logger.info('点击频道折叠按钮...')
            bookcityPage.channelFoldDownButton().click()
            bookcityPage.channelVIPButton().click()
            TestBookCity.browser.refresh()
            titleText = bookcityPage.VIPText().text

            try:

                self.assertIs('开通京东读书VIP,海量书籍免费借阅' in titleText, True)
                logger.info('切换频道成功!用例通过')

            except AssertionError as e:
                logger.debug('切换频道失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_Check_Domain(self):
        logger.info("开始执行频道切换按钮脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)

            domainname = bookcityPage.domainName().text
            domainurl = bookcityPage.domainUrl().text

            try:

                self.assertIs(('e.m.jd.com' in domainurl)
                              and ('京东读书' in domainname), True)
                logger.info('检查域名成功!用例通过')

            except AssertionError as e:
                logger.debug('检查域名失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_More_Tools_Index_Button(self):
        logger.info("开始执行更多按钮首页按钮脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.toolButtonObj().click()
            index_image = bookcityPage.indexButtonImageInMoreTools()
            index_button = bookcityPage.firstPageButtonObj()
            if index_image.is_displayed() and index_button.is_displayed():
                index_button.click()

            # my_books_image=bookcityPage.myBooksButtonImageInMoreTools()
            # shop_cart_image=bookcityPage.shoppingCartButtonImageInMoreTools()
            # mine_image=bookcityPage.mineButtonImageInMoreTools()

            try:

                self.assertIs(bookcityPage.domainName().is_displayed(), True)

                logger.info('书城首页按钮点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城首页按钮点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")
            raise e

        except NoSuchElementException as e:

            logger.error("数据问题..重试")
            raise e

        except Exception as e:

            logger.error(e)

            raise e

    def test_More_Tools_My_Books_Button(self):
        logger.info("开始执行更多按钮-【我的书籍】按钮脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.toolButtonObj().click()
            my_books_image = bookcityPage.myBooksButtonImageInMoreTools()
            my_books_button = bookcityPage.myBookPageButtonObj()
            if my_books_image.is_displayed() and my_books_button.is_displayed(
            ):
                my_books_button.click()
            mybooksPage = MyBooksPage(TestBookCity.browser)
            # mybooks_title=mybooksPage.mybooksTitle()
            time.sleep(5)
            print(TestBookCity.browser.page_source)

            try:

                self.assertIs(mybooksPage.mybooksTitle().is_displayed(), True)

                logger.info('书城更多按钮-【我的书籍】点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城更多按钮-【我的书籍】点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")
            raise e

        except NoSuchElementException as e:

            logger.error("数据问题..重试")
            raise e

        except Exception as e:

            logger.error(e)

            raise e

    def test_More_Tools_Shopping_Cart_Button(self):
        logger.info("开始执行更多按钮-【购物车】按钮脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.toolButtonObj().click()

            shopping_cart_image = bookcityPage.shoppingCartButtonImageInMoreTools(
            )
            shopping_cart_button = bookcityPage.shoppingCartPageButtonObj()
            if shopping_cart_image.is_displayed(
            ) and shopping_cart_button.is_displayed():
                shopping_cart_button.click()
            # shop_cart_image=bookcityPage.shoppingCartButtonImageInMoreTools()
            # mine_image=bookcityPage.mineButtonImageInMoreTools()
            shoppingCartPage = ShoppingCartPage(TestBookCity.browser)
            time.sleep(5)

            try:

                self.assertIs(
                    shoppingCartPage.shoppingCartTitle().is_displayed(), True)

                logger.info('书城更多按钮-【购物车】点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城更多按钮-【购物车】点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")
            raise e

        except NoSuchElementException as e:

            logger.error("数据问题..重试")
            raise e

        except Exception as e:

            logger.error(e)

            raise e

    def test_More_Tools_Mine_Button(self):
        logger.info("开始执行更多按钮-【我的】按钮脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.toolButtonObj().click()

            mine_image = bookcityPage.mineButtonImageInMoreTools()
            mine_button = bookcityPage.minePageButtonObj()
            if mine_image.is_displayed() and mine_button.is_displayed():
                mine_button.click()
            minePage = MinePage(TestBookCity.browser)
            time.sleep(5)

            try:

                self.assertIs(minePage.title().is_displayed(), True)

                logger.info('书城更多按钮-【我的】点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城更多按钮-【我的】点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")
            raise e

        except NoSuchElementException as e:

            logger.error("数据问题..重试")
            raise e

        except Exception as e:

            logger.error(e)

            raise e

    def test_Banner_Click(self):
        logger.info("开始执行书城banner点击脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)

            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)
            bookcityPage.channelNewEraButton().click()
            time.sleep(2)
            bookcityPage.newEraBanner().click()
            time.sleep(5)
            collectionPage = CollectionPage(TestBookCity.browser)
            titleElement = collectionPage.title()

            try:

                self.assertIs(titleElement.is_displayed(), True)
                logger.info('书城banner点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城banner点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_Leaderboard_Button_Click(self):
        logger.info("开始执行五个圈-排行按钮点击脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)
            bookcityPage.channelFeaturedButton().click()
            time.sleep(2)
            bookcityPage.leaderBoardButton().click()

            time.sleep(2)
            leaderboardPage = LeaderboardPage(TestBookCity.browser)
            titleElement = leaderboardPage.title()
            title_text = titleElement.text

            try:

                self.assertIs('排行榜' == title_text, True)
                logger.info('书城五个圈-排行按钮点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城五个圈-排行按钮点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_Classification_Button_Click(self):
        logger.info("开始执行五个圈-分类按钮点击脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)
            bookcityPage.channelFeaturedButton().click()
            time.sleep(2)
            bookcityPage.classificationButton().click()

            time.sleep(2)
            classificationPage = ClassificationPage(TestBookCity.browser)
            titleElement = classificationPage.title()
            title_text = titleElement.text

            try:

                self.assertIs('分类' == title_text, True)
                logger.info('书城五个圈-分类按钮点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城五个圈-分类按钮点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_Discount_Button_Click(self):
        logger.info("开始执行五个圈-特价按钮点击脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)

            bookcityPage.channelFeaturedButton().click()
            time.sleep(2)
            bookcityPage.discountButton().click()

            time.sleep(2)
            discountPage = DiscountPage(TestBookCity.browser)
            titleElement = discountPage.title()
            title_text = titleElement.text

            try:

                # self.assertIs('特价专区'==title_text , True)
                result1 = '特价专区' == title_text
                result2 = re.search(r'\d+件[\s\S]+元', title_text)
                result3 = "双周特价" == title_text
                if result1:
                    self.assertIs('特价专区' == title_text, True)
                elif None != result2:
                    self.assertIs(None != result2, True)

                logger.info('书城五个圈-特价按钮点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城五个圈-特价按钮点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_Freebook_Button_Click(self):
        logger.info("开始执行五个圈-免费按钮点击脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)
            bookcityPage.channelFeaturedButton().click()
            time.sleep(2)
            bookcityPage.freebookButton().click()

            time.sleep(2)
            freePage = FreebookPage(TestBookCity.browser)
            time.sleep(2)
            titleElement = freePage.title()
            title_text = titleElement.text

            try:

                self.assertIs('免费专区' == title_text, True)
                logger.info('书城五个圈-免费按钮点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城五个圈-免费按钮点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_VIP_Button_Click(self):
        logger.info("开始执行五个圈-VIP按钮点击脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)
            bookcityPage.vipButton().click()
            time.sleep(2)
            titleElement = bookcityPage.VIPText()

            try:

                self.assertIs(titleElement.is_displayed(), True)
                logger.info('书城五个圈-VIP按钮点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城五个圈-VIP按钮点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    @set_phone_model(phone_model)
    def test_Discount_Collection_Title(self):
        logger.info("开始执行本周特价title点击脚本...")
        pc = ParseConfigFile()

        try:

            browser = webdriver.Chrome(chrome_options=options)

            browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(browser)

            collectionName = bookcityPage.firstCollectionTitle().text
            counterHour = bookcityPage.firstCollectionCounterHour().text
            counterMinute = bookcityPage.firstCollectionCounterMinute().text

            checkHour = str(24 - int(time.localtime().tm_hour) - 1).zfill(2)
            checkMinute = str(60 - int(time.localtime().tm_min) - 1).zfill(2)

            bookcityPage.firstCollectionTitle().click()
            time.sleep(5)

            weeklyDiscountTitleText = WeeklyDiscountPage(browser).title().text

            try:

                self.assertIs(checkHour == counterHour, True)
                self.assertIs(checkMinute == counterMinute, True)
                # self.assertIs("本周特价"==collectionName,True)
                # self.assertIs("本周特价"==weeklyDiscountTitleText,True)

                logger.info('书城本周特价title点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城本周特价title点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")
            raise e

        except NoSuchElementException as e:

            logger.error("数据问题..重试")
            raise e

        except Exception as e:

            logger.error(e)

            raise e

    @set_phone_model(phone_model)
    def test_Discount_Collection_List(self):
        logger.info("开始执行本周特价列表检查脚本...")
        pc = ParseConfigFile()

        try:

            browser = webdriver.Chrome(chrome_options=options)

            browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(browser)

            page_book_set = set([
                bookcityPage.firstCollectionFirstBookName().text.replace(
                    " ", ""),
                bookcityPage.firstCollectionSecondBookName().text.replace(
                    " ", ""),
                bookcityPage.firstCollectionThirdBookName().text.replace(
                    " ", "")
            ])
            collectionName = bookcityPage.firstCollectionTitle().text
            api_book_set = set(
                GetCollectionBooks.getBookNameDataList(collectionName))
            # print(page_book_set)
            # print(api_book_set)
            booklist_check = page_book_set.issubset(api_book_set)

            # api_firstbook_jd_price= str(int(float(GetCollectionBooks.getDataList(collectionName)[0]['jd_price']) * 100)) + "阅豆"
            # api_firstbook_price= str(int(float(GetCollectionBooks.getDataList(collectionName)[0]['price']) * 100)) + "阅豆"
            api_firstbook_jd_price = str(
                round(
                    GetCollectionBooks.getDataList(collectionName)[0]
                    ['jd_price'], 2))
            api_firstbook_price = str(
                round(
                    GetCollectionBooks.getDataList(collectionName)[0]['price'],
                    2))
            page_firstbook_jd_price = str(
                round(
                    float(bookcityPage.firstCollectionFirstBookNewPrice().text.
                          strip('¥')), 2))
            page_firstbook_price = str(
                round(
                    float(bookcityPage.firstCollectionFirstBookOldPrice().text.
                          strip('¥')), 2))

            try:

                self.assertIs(booklist_check, True)
                self.assertIs(
                    (api_firstbook_jd_price == page_firstbook_jd_price)
                    and (api_firstbook_price == page_firstbook_price), True)

                logger.info('书城本周特价列表检查成功!用例通过')

            except AssertionError as e:
                logger.debug('书城本周特价列表检查失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_First_Collection_Book_Click_Redirect(self):
        logger.info("开始执行本周特价书籍点击脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)
            bookcityPage.channelFeaturedButton().click()
            time.sleep(2)
            page_first_book_name = bookcityPage.firstCollectionFirstBookName(
            ).text
            bookcityPage.firstCollectionFirstBookName().click()
            time.sleep(3)
            book_detail_page_title = TestBookCity.browser.title

            try:

                self.assertIs(page_first_book_name == book_detail_page_title,
                              True)

                logger.info('书城本周特价书籍点击成功!用例通过')

            except AssertionError as e:
                logger.debug('书城本周特价书籍点击失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e

    def test_First_Collection_Detail_List(self):
        logger.info("开始执行本周特价合集页列表检查脚本...")
        pc = ParseConfigFile()

        try:

            TestBookCity.browser.get(pc.getUrl('bookcity'))

            logger.info('启动浏览器,访问"书城"页面...')
            bookcityPage = BookCityPage(TestBookCity.browser)
            bookcityPage.channelFoldDownButton().click()
            time.sleep(2)
            bookcityPage.channelFeaturedButton().click()
            time.sleep(2)
            collectionName = bookcityPage.firstCollectionTitle().text

            bookcityPage.firstCollectionTitle().click()

            collectionPage = CollectionPage(TestBookCity.browser)
            book_element_list = collectionPage.bookNameList()
            book_name_set = set([
                e.text.replace(" ", "") for e in book_element_list
                if e.text != ''
            ])
            api_book_name_set = set(
                GetCollectionBooks.getBookNameDataList(collectionName))
            book_name_set_check = book_name_set.issubset(api_book_name_set)

            api_thirdbook_name = GetCollectionBooks.getDataList(
                collectionName)[2]['name']
            api_thirdbook_old_price = str(
                GetCollectionBooks.getDataList(collectionName)[2]['price'])
            api_thirdbook_cur_price = str(
                GetCollectionBooks.getDataList(collectionName)[2]['jd_price'])
            api_thirdbook_catagory = GetCollectionBooks.getDataList(
                collectionName)[2]['category_third'][0]

            page_thirdbook_name = collectionPage.bookNameList()[2].text
            # page_thirdbook_old_price =collectionPage.bookOldPriceList()[2].text.strip('¥')
            # page_thirdbook_cur_price =collectionPage.bookCurPriceList()[2].text.strip('¥')

            try:

                self.assertIs(book_name_set_check, True)
                self.assertIs(api_thirdbook_name == page_thirdbook_name, True)
                # self.assertIs(api_thirdbook_catagory==page_thirdbook_catagory,True)
                # self.assertIs(api_thirdbook_cur_price==page_thirdbook_cur_price,True)
                # self.assertIs(api_thirdbook_old_price==page_thirdbook_old_price,True)

                logger.info('书城本周特价合集页列表检查脚本成功!用例通过')

            except AssertionError as e:
                logger.debug('书城本周特价合集页列表检查脚本失败!用例不通过')
                raise e

        except ElementNotVisibleException as e:

            logger.error("数据问题,元素没有找到..")

        except NoSuchElementException as e:

            logger.error("数据问题..重试")

        except Exception as e:

            logger.error(e)

            raise e