セレン自動テストの再利用可能なコードテンプレートの概要

「」「
次のように与えられたアラートアサーション、:
TypeError例外:」アラート「オブジェクトは、呼び出すことはできません
分析:
」警告「はアラートが関数呼び出しの意味することはできません呼び出し可能なオブジェクトではありません、それは関数ではありません。
解決策:警告の後に括弧を削除します。
正しいコード:
browser.switch_to.alert.accept()

「」」

# - -コーディング:UTF-8を- -
セレン輸入webdriverをから
selenium.common.exceptionsからはNoSuchElementExceptionをインポート
NoAlertPresentExceptionのインポートselenium.common.exceptionsから
輸入unittestを、時間を、再

クラスAlertDemo(たunittest.TestCase):

def is_alert_present(self):
#self.driver.switch_to.alert去掉后面括号
    try: self.driver.switch_to.alert
    except NoAlertPresentException as e: return False
    return True

def close_alert_and_get_its_text(self):
    try:
        alert = self.driver.switch_to.alert
        alert_text = alert.text
        if self.accept_next_alert:
            alert.accept()
        else:
            alert.dismiss()
        return alert_text
    finally: self.accept_next_alert = True

もし名前 ==「メイン:」
unittest.main()

テストスイート、次のように与えられ、発見:
はImportErrorをスタートディレクトリがインポート可能なされていない:「... /機能テスト自動化/ exec318 /」
原因分析:同じディレクトリのパスを右
ソリューション:「./」と直接unittest.defaultTestLoader.discover並列パス

unittestのインポート
インポートOS
タイムインポートのstrftimeのから
#のsys.path.append( "I:\\テスト\機能テスト自動化\ exec318 \")
注:HTMLTestRunner.pyのpython3 Libはpython36パス下に置かれた構文をサポート
Lib.HTMLTestRunnerインポートHTMLTestRunnerから

「」 '
注意:テストケースクラスではなく、いくつかのテストを実行する単一のバッチを飾るために@ddtを使用している場合は、それが唯一のクラス全体で実行することができます。
「」 '

IF ==「メイン『:
はテストレポートの格納ディレクトリを作成し
てみてください。
os.mkdir(』 ... /レポート」)
を除き、例外としてE:
印刷(E)
保存されたテスト結果ファイルを作成
html_report_file =オープン(」... /レポート/register_test_report_%s.html "のstrftimeの%(" %M%D_ Y%H%M%S% ")、" WB「)
コールHTMLTestRunnerクラス生成HTML形式レポートテストラン
ランナー= HTMLTestRunner(ストリーム= html_report_file、タイトル= "レポート試験"、
説明= "RUNの状態のテストケース")
Suite1 = unittest.defaultTestLoader.discover( "./"、 "* testcase.py")
#= Suite1 unittest.TestLoader()。loadTestsFromTestCase(ECShop_BG_Login_TestCase)
= unittest.defaultTestLoader.discover Suite1( "... /テストケース/"、 "* testcase.py")
ランナー。ラン(suite1)
#runner.run(allTest())
html_report_file.close()

「」「
データファイルCSVを読むには
」「」
インポートCSV

クラスCSVUtil():
デフのinit(自己、filePathに):
self.filePath = filePathに

def list_data(self):
    # 读取CSV文件
    value_rows = []
    with open(self.filePath, "r") as f:
        f_csv = csv.reader(f)
        next(f_csv)  # 如果从第2个开始读取数据,则加入该行代码
        for r in f_csv:
            value_rows.append(r)
    return value_rows

もし名前 ==「メイン」:
filePathに= "... / exec318 /添加会员.CSV"
データ= CSVUtil(filePathに)
プリント(data.list_data())

「」「
要素の位置決めモジュールの基本クラス
」「」
インポートによってselenium.webdriver.common.byから

クラスECShop_FP_BasePage_Locator():
DEF のinit(自己):
self.find_logout_link =(By.LINK_TEXT、「退出」)
self.find_login_img =(By.XPATH、 "//フォント[@ ID = 'ECS_MEMBERZONE'] / [1] / IMG ")
self.find_register_img =(By.XPATH、『//フォント[@ ID = 'ECS_MEMBERZONE'] / [2] / IMG』)
self.find_username_in_head_txt =(By.XPATH、" .//*[@ ID = 'ECS_MEMBERZONE'] /フォント/フォント」)

'' '
业务逻辑基础类Base_Module
'''
インポートのCSV
クラスECShop_BG_SubPage_Base_Module():
DEF のinit(自己、ドライバ):
self.driver =ドライバ
DEF switch_to_home_page(自己):
self.driver.switch_to.default_content()
戻りself.driver

「」「
测试用例基础类
『』」
ユニットテストをインポート
セレンインポートwebdriverをからの
時間インポート眠りから
selenium.common.exceptionsからはNoSuchElementException、NoAlertPresentExceptionをインポート
ecshop.module.ecshop_bg_adduserpage_module輸入ECShop_BG_AddUserPage_Moduleから
ecshop.module.ecshop_bg_headerpage_module輸入ECShop_BG_HeaderPage_Moduleから
ecshop.moduleから.ecshop_bg_homepage_module輸入ECShop_BG_HomePage_Module
ecshop.module.ecshop_bg_menupage_module輸入ECShop_BG_MenuPage_Moduleから
ecshop.module.ecshop_bg_userlistpage_module輸入ECShop_BG_UserListPage_Moduleから
ecshop.module.ecshop_bg_usermessagepage_module輸入ECShop_BG_UserMessagePage_Moduleから

(たunittest.TestCaseの)MyTestCaseBaseクラス:
DEFセットアップ(セルフ):
self.driver webdriver.Firefox =()
のself.driver.implicitly_wait(10)
self.accept_next_alert = Trueの
DEFティアダウン(自己):
self.driver.quit()
#ページ要素かどうかが決定する
(セルフ、どのように、どのような)DEF is_element_present:
試してみてください
(=どのように、値=何によって)self.driver.find_element
はNoSuchElementException AS Eを除く:
Falseを返す
リターン真の
ポップアップボックスが表示されるかどうか#裁判官を
(DEF is_alert_presentセルフ):
試してみる:
self.driver.switch_to.alert
除くNoAlertPresentException AS E:
リターン偽
リターン真
#クローズポップアップボックス(デフォルトのクリック「OK」)、およびテキストを取得するために
デフclose_alert_and_get_its_text(自己):
試してみてください。
警告= self.driver.switch_to.alert
alert_text = alert.text
場合self.accept_next_alert:
alert.accept()
他:
alert.dismiss()
alert_textリターン
最後に:
self.accept_next_alert =真

# 判断网页标题是否以指定字符串结尾
def is_title_ends_with(self, t):
    return self.driver.title.endswith(t)

# 判断网页标题是否以指定字符串开头
def is_title_starts_with(self, t):
    return self.driver.title.startswith(t)

# 判断网页源代码中是否包含指定字符串
def is_pagesource_contains(self, info):
    return info in self.driver.page_source

def to_user_list_page(self):
    hp = ECShop_BG_HomePage_Module(self.driver)
    self.driver = hp.switch_to_menu()
    menup = ECShop_BG_MenuPage_Module(self.driver)
    self.driver = menup.to_user_list_page()
    hp = ECShop_BG_HomePage_Module(self.driver)
    self.driver = hp.switch_to_main()
    ulp = ECShop_BG_UserListPage_Module(self.driver)
    sleep(3)
    return ulp

def to_add_user_page(self):
    hp=ECShop_BG_HomePage_Module(self.driver)
    self.driver=hp.switch_to_menu()
    menup=ECShop_BG_MenuPage_Module(self.driver)
    self.driver =menup.to_add_user_page()
    hp = ECShop_BG_HomePage_Module(self.driver)
    self.driver = hp.switch_to_main()
    aup=ECShop_BG_AddUserPage_Module(self.driver)
    return aup
def to_user_message_page(self):
    hp=ECShop_BG_HomePage_Module(self.driver)
    self.driver=hp.switch_to_menu()
    menup=ECShop_BG_MenuPage_Module(self.driver)
    self.driver =menup.to_user_message_page()
    hp = ECShop_BG_HomePage_Module(self.driver)
    self.driver = hp.switch_to_main()
    ump = ECShop_BG_UserMessagePage_Module(self.driver)
    return ump

def logout_bg(self):
    self.driver.switch_to.default_content()
    # 退出
    hp = ECShop_BG_HomePage_Module(self.driver)
    self.assertTrue(self.is_element_present(*hp.hp_loc.find_header_frame))
    self.driver=hp.switch_to_header()
    hdp=ECShop_BG_HeaderPage_Module(self.driver)
    self.assertTrue(self.is_element_present(*hdp.hdp_loc.find_logout_link))
    self.driver=hdp.logout()
    return self.driver

'' '
モジュール逻辑运行举例

'''
exec318.register_locatorインポートRegisterLocatorから
exec318.register_read_csvインポートCSVUtilから
時間インポートスリープから
webdriverをセレンインポートから
クラスRegisterModule():
DEF のinit(自己、ドライバ):
self.driver =ドライバ
自己。 BASE_URL =「https://account.shopex.cn/reg?shopex」
self.loc = RegisterLocator()

def open(self):
    self.driver.get(self.base_url)

def input_data(self,name,verifycode,mobilecode,pwd,contact):

    # 手机号
    name_input = self.driver.find_element(*self.loc.loc_name)
    name_input.clear()
    name_input.send_keys(name)


    # 验证码
    verifycode_input = self.driver.find_element(*self.loc.loc_verifycode)
    verifycode_input.clear()
    verifycode_input.send_keys(verifycode)


    # 手机号验证码

    self.driver.find_element(*self.loc.loc_mobileCodeBtn).click()

    mobilecode_input = self.driver.find_element(*self.loc.loc_mobilecode)
    mobilecode_input.send_keys(mobilecode)


    # 登录密码
    pwd_input = self.driver.find_element(*self.loc.loc_pwd)
    pwd_input.send_keys(pwd)


    # 联系人姓名
    contact_input = self.driver.find_element(*self.loc.loc_contact)
    contact_input.send_keys(contact)

    sleep(5)


def register(self,name,verifycode,mobilecode,pwd,contact):
    self.input_data(name,verifycode,mobilecode,pwd,contact)
    accept_input = self.driver.find_element(*self.loc.loc_accept)
    accept_input.click()
    register_button = self.driver.find_element(*self.loc.loc_register)
    if register_button.is_enabled():
        print('注册按钮可用')
    return self.driver

def login(self):
    login_a = self.driver.find_element(*self.loc.loc_login)
    login_a.click()

「」「
試験例
」「」

インポートユニットテスト
インポートSYS

言葉遣い:

sys.path.append(「D:\ PycharmProjects \ myproject1 \」)

2著:

sys.path.append( "...")

sys.path.append( "... / ...")

3著:

輸入OS

curPath = os.path.abspath(os.path.dirname(ファイル))

印刷(「curPath =」、curPath)

ROOTPATH = os.path.split(curPath)[0]

印刷(「ROOTPATH =」、ROOTPATH)

sys.path.append(ROOTPATH)

rootPath1 = os.path.split(ROOTPATH)[0]

印刷(「rootPath1 =」、rootPath1)

sys.path.append(rootPath1)

プリント(のsys.path)

セレン輸入webdriverをから
ecshop.testcase.ecshop_00_testcase_base輸入MyTestCaseBaseから
ecshop.module.ecshop_bg_headerpage_module輸入ECShop_BG_HeaderPage_Moduleから
ecshop.module.ecshop_bg_homepage_module輸入ECShop_BG_HomePage_Moduleから
ecshop.module.ecshop_bg_loginpage_module輸入ECShop_BG_LoginPage_Moduleから
ecshop.module.ecshop_bg_systeminfopage_module輸入ECShop_BG_SystemInfoPage_Moduleから
ecshop.module.ecshop_bg_adduserpage_moduleから輸入ECShop_BG_AddUserPage_Module
ecshop.module.ecshop_bg_menupage_module輸入ECShop_BG_MenuPage_Moduleから
ecshop.module.ecshop_bg_userlistpage_module輸入ECShop_BG_UserListPage_Moduleから
ecshop.module.ecshop_bg_edituserpage_module輸入ECShop_BG_EditUserPage_Moduleから
ecshop.module.ecshop_fp_loginpage_module輸入ECShop_FP_LoginPage_Moduleから
ecshop.module.ecshop_fp_systeminfopage_module輸入ECShop_FP_SystemInfoPage_Moduleのから
インポートCSV
アンパックDDT輸入DDT、データから
時間インポートスリープから
ecshop.locator.ecshop_bg_loginpage_locatorインポートECShop_BG_LoginPage_Locatorから
ecshop.utilから.read_csvインポートCSVUtil

ecshop.util.read_excelインポートExcelUtilから

デフgetCsvData():

#読むCSVファイル

value_rows = []

オープンと( "D:\ PycharmProjects \ myproject1 \ ecshop \プロファイルの.csv追加するデータ\データ_ECShop_背景"、 "R")をFとして:

f_csv = csv.reader(F)

最初の二つから開始読取データは、行に追加された場合、次は(f_csv)#

f_csvでR用:

value_rows.append®

リターンvalue_rows

getCsvData TESTDATA =#()
#= CSVUtil TESTDATA( "D:\ PycharmProjects \ myproject1 \ ecshop \プロファイル.CSVを追加するためのデータ\データ_ECShop_バックグラウンド")。list_dataを()
TESTDATA = CSVUtil(」... \データ\データ_ECShop _会員の舞台裏の.CSVを追加")list_data()。
D#= ExcelUtil TESTDATA(":プロファイルの.xlsx ""プロファイルを追加するには、背景を「追加する\ PycharmProjects \ myproject1 \ ecshop \データ\データ_ECShop_背景).list_data()
#テストデータ= ExcelUtil( "... \データ\ プロファイルを追加するには、データ_ECShop_背景の.xlsx"、 "プロファイルを追加するためのバックグラウンドを").list_data()
#Print(TESTDATA)

@ddt
クラスECShop_BG_AddUser_TestCase(MyTestCaseBase):
@data(*テストデータ)
@unpack
デフtest_a_bg_adduser_submit(自己、testdata_id、testcase_id、ユーザ名、電子メール、パスワード、confirm_password、
user_rank、性別、birthdayYear、birthdayMonth、birthdayDay、
credit_line、MSN、QQ、のphone1 、phone2の、phone3、expected_result_id):
印刷( "=「)
プリント(testdata_id)
プリント(testcase_id)
プリント(ユーザー名)
プリント(電子メール)
印刷(パスワード)
プリント(confirm_password)
プリント(user_rank)
プリント(性別)
プリント(birthdayYear)
プリント(birthdayMonth)
プリント(birthdayDay)
プリント(MSN)
印刷(QQ)
プリント(のphone1)
プリント(phone2の)
プリント(phone3)
プリント(expected_result_id)
印刷(」
= ")
LP = ECShop_BG_LoginPage_Module(self.driver)
lp.open()
self.driver = lp.login(『管理者』、『admin123』、『0』)
睡眠(2)
== expected_result_idであれば『1』とユーザ名ではありません:「テキスト」、「VIP」、「ecshop」]における
ULP = self.to_user_list_page()
self.driver = ulp.search(ユーザ名)
ULP = ECShop_BG_UserListPage_Module(self.driver)
睡眠(2)
ulp.is_user_in_result場合(ユーザ名):
ulp.delete_user(ユーザー名)
self.assertTrue(self.is_alert_present())
self.close_alert_and_get_its_text()
AUP = self.to_add_user_page()
self.driver = aup.add_user_submit(ユーザー名、電子メール、パスワード、confirm_password、
user_rank、性別、 birthdayYear、birthdayMonth、birthdayDay、
credit_line、MSN、QQ、のphone1、phone2の、phone3)
expected_result_id ==「1」の場合:
一口= ECShop_BG_SystemInfoPage_Module(self.driver)
self.assertTrue(self.is_element_present(* sip.sip_loc.find_previous_page_link))
self.assertTrue(自己。 is_pagesource_contains(「会员账号%S已经添加成功。」%ユーザー名))
睡眠(4)
ULP = ECShop_BG_UserListPage_Module(self.driver)
self.assertTrue(self.is_element_present(* ulp.ulp_loc.find_search_button))
self.driver = ULP。検索(ユーザー名)
ULP = ECShop_BG_UserListPage_Module(self.driver)
睡眠(2)
self.assertTrue(ulp.is_user_in_result(ユーザー名))
self.driver = ulp.edit_target_user(ユーザー名)
睡眠(2)
邑= ECShop_BG_EditUserPage_Module(self.driver)
self.assertEqual(ユーザ名、eup.get_user_name())
self.assertEqual(電子メール、eup.get_email())
self.assertEqual(user_rank、eup.get_user_rank())
self.assertEqual(性別、eup.get_sex())
セルフ。 assertEqual(birthdayYear、eup.get_birthdayYear())
self.assertEqual(birthdayMonth、eup.get_birthdayMonth())
self.assertEqual(birthdayDay、eup.get_birthdayDay())
self.assertAlmostEqual(フロート(credit_line)、フロート(eup.get_credit_line() ))
self.assertEqual(MSN、eup.get_msn())
self.assertEqual(QQ、eup.get_qq())
self.assertEqual(のphone1、eup.get_phone1())
self.assertEqual(phone2の、eup.get_phone2())
self.assertEqual(phone3、eup.get_phone3())
eup.switch_to_home_page()
self.driver = self.logout_bg()
#フォアグラウンドは、アカウントテストする
FLP = ECShop_FP_LoginPage_Module(self.driver)
flp.open()
self.driver = flp.login(ユーザー名、パスワード)
FSIP = ECShop_FP_SystemInfoPage_Module(self.driver)
self.assertTrue(self.is_element_present(* FSIPを。 sip_loc.find_logout_link))
MSG1 = fsip.get_red_info()
self.assertEqual( "ログイン成功"、MSG1)
fsip.logout_fp()

    elif expected_result_id=="2":
        self.assertTrue(self.is_alert_present())
        msg2=self.close_alert_and_get_its_text()
        self.assertEqual("- 没有输入用户名。\n",msg2)
        self.assertFalse(self.is_alert_present())
        aup.switch_to_home_page()
        self.logout_bg()
    elif expected_result_id=="3":
        sip = ECShop_BG_SystemInfoPage_Module(self.driver)
        self.assertTrue(self.is_element_present(*sip.sip_loc.find_previous_page_link))
        self.assertTrue(self.is_pagesource_contains("已经存在一个相同的用户名。"))
        sleep(4)
        aup = ECShop_BG_AddUserPage_Module(self.driver)
        self.assertTrue(self.is_element_present(*aup.aup_loc.find_username_input))
        self.assertTrue(aup.is_pw_and_confirm_pw_empty())
        aup.switch_to_home_page()
        self.logout_bg()
    elif expected_result_id=="4":
        self.assertTrue(self.is_alert_present())
        msg4=self.close_alert_and_get_its_text()
        self.assertEqual("- 输入的密码和确认密码不一致。\n",msg4)
        self.assertFalse(self.is_alert_present())
        aup.switch_to_home_page()
        self.logout_bg()
    elif expected_result_id=="5":
        self.assertTrue(self.is_alert_present())
        msg5=self.close_alert_and_get_its_text()
        self.assertEqual("- 没有输入邮件地址或者输入了一个无效的邮件地址。\n",msg5)
        self.assertFalse(self.is_alert_present())
        aup.switch_to_home_page()
        self.logout_bg()
    elif expected_result_id=="6":
        self.assertTrue(self.is_alert_present())
        msg6=self.close_alert_and_get_its_text()
        self.assertEqual("- 没有输入密码。\n- 没有输入确认密码。\n- 输入的密码和确认密码不一致。\n- 输入的密码不能少于六位。\n",msg6)
        self.assertFalse(self.is_alert_present())
        aup.switch_to_home_page()
        self.logout_bg()
    elif expected_result_id=="7":
        self.assertTrue(self.is_alert_present())
        msg7=self.close_alert_and_get_its_text()
        self.assertEqual("- 没有输入确认密码。\n- 输入的密码和确认密码不一致。\n",msg7)
        self.assertFalse(self.is_alert_present())
        aup.switch_to_home_page()
        self.logout_bg()
    elif expected_result_id=="8":
        self.assertTrue(self.is_alert_present())
        msg8=self.close_alert_and_get_its_text()
        self.assertEqual("- 输入的密码不能少于六位。\n",msg8)
        self.assertFalse(self.is_alert_present())
        aup.switch_to_home_page()
        self.logout_bg()
    elif expected_result_id=="9":
        self.assertTrue(self.is_alert_present())
        msg9=self.close_alert_and_get_its_text()
        self.assertEqual("- 没有输入邮件地址或者输入了一个无效的邮件地址。\n- 没有输入用户名。\n- 没有输入密码。\n- 没有输入确认密码。\n- 输入的密码和确认密码不一致。\n- 输入的密码不能少于六位。\n",msg9)
        self.assertFalse(self.is_alert_present())
        aup.switch_to_home_page()
        self.logout_bg()

@data(*testdata)
@unpack
def test_b_bg_adduser_reset(self,testdata_id,testcase_id,username,email,password,confirm_password,
            user_rank,sex,birthdayYear,birthdayMonth,birthdayDay,
             credit_line,msn,qq,phone1,phone2,phone3,expected_result_id):
    print("=============")
    print(testdata_id)
    print(testcase_id)
    print(username)
    print(email)
    print(password)
    print(confirm_password)
    print(user_rank)
    print(sex)
    print(birthdayYear)
    print(birthdayMonth)
    print(birthdayDay)
    print(msn)
    print(qq)
    print(phone1)
    print(phone2)
    print(phone3)
    print(expected_result_id)
    print("=============")
    lp=ECShop_BG_LoginPage_Module(self.driver)
    lp.open()
    self.driver=lp.login("admin","admin123","0")
    sleep(2)
    aup = self.to_add_user_page()
    self.driver = aup.add_user_reset(username, email, password, confirm_password,
                                     user_rank, sex, birthdayYear, birthdayMonth, birthdayDay,
                                      credit_line, msn, qq, phone1, phone2, phone3)
    aup=ECShop_BG_AddUserPage_Module(self.driver)
    self.assertTrue(aup.is_all_reset_to_default())
#
# def to_user_list_page(self):
#     hp = ECShop_BG_HomePage_Module(self.driver)
#     self.driver = hp.switch_to_menu()
#     menup = ECShop_BG_MenuPage_Module(self.driver)
#     self.driver = menup.to_user_list_page()
#     hp = ECShop_BG_HomePage_Module(self.driver)
#     self.driver = hp.switch_to_main()
#     ulp = ECShop_BG_UserListPage_Module(self.driver)
#     sleep(3)
#     return ulp
#
# def to_add_user_page(self):
#     hp=ECShop_BG_HomePage_Module(self.driver)
#     self.driver=hp.switch_to_menu()
#     menup=ECShop_BG_MenuPage_Module(self.driver)
#     self.driver =menup.to_add_user_page()
#     hp = ECShop_BG_HomePage_Module(self.driver)
#     self.driver = hp.switch_to_main()
#     aup=ECShop_BG_AddUserPage_Module(self.driver)
#     return aup
#
# def logout_bg(self):
#     # 退出
#     hp = ECShop_BG_HomePage_Module(self.driver)
#     self.assertTrue(self.is_element_present(*hp.hp_loc.find_header_frame))
#     self.driver=hp.switch_to_header()
#     hdp=ECShop_BG_HeaderPage_Module(self.driver)
#     self.assertTrue(self.is_element_present(*hdp.hdp_loc.find_logout_link))
#     self.driver=hdp.logout()
#     return self.driver

もし名前 == ' メイン ':
unittest.main()

リリース元の4件の記事 ウォンの賞賛0 ビュー88

おすすめ

転載: blog.csdn.net/weixin_45374509/article/details/104947247