Django学习系列6:使用selenium测试用户交互

学习系列5中的单元测试有报错信息,这儿来编写functional_tests.py文件,扩充其中的功能测试

#  File: functional_test.py
#  Author: Rxf
#  Created on 2019.10.10 14:00 (first release)
#  Copyright (C) 2019 xxxxxx. All rights reserved.
#  please use python3.x
# -*- coding: UTF-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys  # 4
import time
import unittest

class NewVisitorTest(unittest.TestCase):
    def setUp(self):  # 1
        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(3)

    def tearDown(self):  # 1
        self.browser.quit()

# 伊迪丝听说了一个很酷的在线待办事项应用程序。她去看看它的主页
# Edith has heard about a cool new online to-do app. She goes to check out its homepage
    def test_start_a_list_and_retrieve_it_later(self):
        self.browser.get('http://localhost:8000')

        # 她注意到网页的标题和头部都包含“Django”.She notices the page title and header mention to-do lists
        self.assertIn('To-Do', self.browser.title)
        header_text = self.browser.find_element_by_tag_name('h1').text   # 2
        self.assertIn('To-DO', header_text)

        # 应用邀请她输入一个待办事项 She is invited to enter a to-do item straight away
        inputbox = self.browser.find_element_by_id('id_new_item')  # 2
        self.assertEqual(
            inputbox.get_attribute('placeholder'),
            'Enter a to-do item'
        )

        # 她在一个文本框中输入了“buy peacock feathers(购买孔雀羽毛)”,她的爱好时用假蝇做鱼饵钓鱼
        inputbox.send_keys('Buy peacock feather')  # 3

        # 她按回车后页面更新了
        inputbox.send_keys(Keys.ENTER)  # 4
        time.sleep(1)
        table = self.browser.find_element_by_id('id_list_table')
        rows = table.find_elements_by_tag_name('tr')  # 2
        self.assertTrue(
            any(row.text == '1: Buy peacock feathers' for row in rows)  # 5
        )

        self.fail("完成测试")
        # self.assertIn('Django', self.browser.title)

if __name__ == '__main__':
    unittest.main(warnings='ignore')

"""
代码解析:
    1、setUp()和tearDown()是特殊方法,分别在各个测试方法之前和之后运行
    2、使用selenium提供的几个用来查找网页内容的方法find_element_by_tag_name,find_element_by_id,find_elements_by_tag_name
    (注意有个s,也就是说这个方法会返回多个元素)
    3、使用send_keys,这是selenium在输入框中输入内容的方法
    4、使用Keys类(记得要先导入),它的作用时发送回车键等特殊的按键,还有ctrl等修改键
    5、any函数是python的原生函数,它是一个生成器表达式(generator expression)
"""

测试一下 python functional_tests.py

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: h1
测试错误,在页面中找不到<h1>元素

代码提交

$ git diff # should show changes to functional_tests.py会显示对functional_tests.py的改动
$ git commit -am "Functional test now checks we can input a to-do item——功能测试现在检查我们是否可以输入待办事项"

猜你喜欢

转载自www.cnblogs.com/ranxf/p/11647715.html