Automated testing: E-commerce management system element positioning exercise

In this topic, let's talk about the use of the Unittest framework in Python and how to realize the automatic generation of automated test reports through HTMLTestRunner. We still use the "e-commerce management system" deployed in classroom learning to implement the code in the case. This exercise includes the following operations:

l The overall structure design of the test case

l Realization of test cases

l Organization of test suites and generation of test reports

1. The overall structure design of the test case

Unittest, formerly known as PyUnit, is derived from Java's JUnit for writing and running repeatable tests. Based on the assertion mechanism to judge whether the actual output of the function or method is consistent with the expected output, the test case provides parameters to execute the function or method, obtains their execution results, and then uses the assertion method to judge whether the output of the function or method is consistent with the expectation Whether the output results are consistent, if they are consistent, the test is passed; if they are inconsistent, the test is not passed.

Unittest requires that the unit test class must inherit TestCase, and the test methods in this class should start with test, without parameters and return values. In addition, two special functions, setUp() and tearDown(), can be added to the unit test to implement specified actions before and after calling a test method, where setUp is executed before the test function is called, and tearDown is Execute after.

We first write a test case for the login function. The code structure is as follows. The demonstration includes three test methods:

insert image description here

2. Realization of test cases

Next we complete the implementation of the test case content. According to the above structure, a total of two test cases are implemented, one is a login test case, and the other is a test case for adding commodity types.

Login test case. Here, the opening and closing functions of the system login page are respectively encapsulated into the setUp and tearDown functions, so that the login page will be automatically opened before and after the execution of each subsequent method, and the login page will be closed after the test is executed.

The code is implemented as follows:

import unittest
from time import sleep
from selenium import webdriver


# 登录测试用例
class LoginTest(unittest.TestCase):
 # 每执行一个测试方法前,先打开登录页面
 def setUp(self):
 self.driver = webdriver.Firefox()
 self.driver.implicitly_wait(10)
 self.driver.get('http://39.96.181.61/qftest-ds/index.php?m=backend&c=main&a=index')

 # 每执行一个测试方法后,关闭浏览器
 def tearDown(self):
 self.driver.quit()

 # 测试方法1:无效用户名登录测试
 def test_01_invalid_username(self):
 self.driver.find_element_by_id("username").send_keys('abcdefg')
 self.driver.find_element_by_id("password").send_keys('qftestxxxxx')
 self.driver.find_element_by_link_text('登 陆').click()
        sleep(2)
 # 断言:如果登录失败,应该显示提示信息,包含文字:"错误的用户名或密码"
 self.assertIn('错误的用户名或密码', self.driver.page_source)

 # 测试方法2:无效密码登录测试
 def test_02_invalid_password(self):
 self.driver.find_element_by_id("username").send_keys('admin')
 self.driver.find_element_by_id("password").send_keys('123456')
 self.driver.find_element_by_link_text('登 陆').click()
        sleep(2)
 # 断言:如果登录失败,应该显示提示信息,包含文字:"错误的用户名或密码"
 self.assertIn('错误的用户名或密码', self.driver.page_source)

 # 测试方法3:有效用户名和密码登录测试
 def test_03_valid(self):
 self.driver.find_element_by_id("username").send_keys('admin')
 self.driver.find_element_by_id("password").send_keys('qftestxxxxxx')
 self.driver.find_element_by_link_text('登 陆').click()
        sleep(2)
 # 断言:如果登录成功,应该进入系统桌面,包含文字:"常用菜单"
 self.assertIn('常用菜单', self.driver.page_source)


if __name__ == "__main__":
    unittest.main()

增加商品类型测试用例。这里将系统登录和退出及关闭浏览器功能分别封装进setUp和tearDown函数内部,这样后续每个方法执行的前后会自动完成登录并在测试执行之后退出和关闭登录页面。
代码实现如下:
import random
import unittest
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.select import Select


# 增加商品分类测试用例
class AddTypeTest(unittest.TestCase):

 def setUp(self):
 self.driver = webdriver.Firefox()
 self.driver.implicitly_wait(10)
 self.driver.get('http://39.96.181.61/qftest-ds/index.php?m=backend&c=main&a=index')
 self.driver.find_element_by_id("username").send_keys('admin')
 self.driver.find_element_by_id("password").send_keys('qftestxxxxxxx')
 self.driver.find_element_by_link_text('登 陆').click()
        sleep(3)

 def tearDown(self):
 self.driver.switch_to.default_content()
 self.driver.find_element_by_link_text("退出登录").click()
        sleep(2)
 self.driver.quit()

 # 测试方法1:是否可要正确打开商品分类页面
 def test_01_open_type(self):
        sleep(5)
 # 依次点击目录:商品管理 - 商品分类
 self.driver.find_element_by_xpath('/html/body/div[5]/div[1]/div[2]/h3/a').click()
 self.driver.find_element_by_partial_link_text('商品分类').click()
        sleep(5)
 # 切换到内部 iframe
 self.driver.switch_to.frame('main')
 # 断言:如果打开商品分类页面成功,应该包含显示文字:"分类名称"
 self.assertIn('分类名称', self.driver.page_source)

 # 测试方法2:是否可要新增商品分类,并且添加成功
 def test_02_add_type(self):
        sleep(5)
 # 依次点击目录:商品管理 - 商品分类
 self.driver.find_element_by_xpath('/html/body/div[5]/div[1]/div[2]/h3/a').click()
 self.driver.find_element_by_partial_link_text('商品分类').click()
        sleep(5)
 self.driver.switch_to.frame('main')
 # 点击“新增分类”按钮
 self.driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/a[1]/font').click()
        sleep(1)

 # 输入分类名称
 self.driver.find_element_by_id('cate_name').send_keys('奥里给')
        sleep(1)

 # 从下拉列表中随机选择一个上级分类
 father_type = self.driver.find_element_by_id('parent_id')
        father_type_opts = Select(father_type).options
        rom = random.randint(0, len(father_type_opts) - 1)
        Select(father_type).select_by_index(rom)
        sleep(1)

 # 点击“保存并提交”按钮
 self.driver.find_element_by_css_selector('html body div.content form div.box div.submitbtn button.ubtn.btn').click()
        sleep(5)

 # 断言:新增的分类名称,应该显示在返回的分类表格页面中
 self.assertIn('奥里给', self.driver.page_source)


if __name__ == "__main__":
    unittest.main()

3. Organization of test suites and generation of test reports

For the execution of test cases, we use the test suite class TestSuite under unittest. From its class definition, it can be understood that multiple independent test cases (test cases) can form a test suite.

If you want test cases to be executed in sequence, you need to use the addTest method of the TestSuite class. After calling the addTest method, the ones added first will be executed first, and the ones added later will be executed later. But I would like to draw your attention here. In PyCharm, the addTest method does not work. The reason is that in PyCharm, the unittest module is introduced, and it will be executed in unittest mode by default. At this time, the unittest mode needs to be converted to normal mode.

When we are doing automated testing, we hope to generate a beautiful test report to show the results of test case execution. Here we use HTMLTestRunner to achieve it. HTMLTestRunner is an extension to the unittest module of the Python standard library. It generates easy-to-use HTML test reports.

The code is implemented as follows:

import unittest
from HTMLTestRunner import HTMLTestRunner
from F01_login_test import LoginTest
from F02_add_type_test import AddTypeTest


# 定义测试套(包含要运行的测试用例及方法)
def test_suite():
    suite = unittest.TestSuite()

    # 添加第一个测试用例及所属测试方法
    suite.addTest(LoginTest('test_01_invalid_username'))
    suite.addTest(LoginTest('test_02_invalid_password'))
    suite.addTest(LoginTest('test_03_valid'))

    # 添加第二个测试用例及所属方法
    suite.addTest(AddTypeTest('test_01_open_type'))
    suite.addTest(AddTypeTest('test_02_add_type'))

    return suite


if __name__ == '__main__':
    # 设置测试报告输出文件
    with open('./test_report.html', 'wb') as f:
        runner = HTMLTestRunner(stream=f,
                                title="自动化测试报告",
                                description="电商系统自动化测试报告")
        # 运行测试套
        runner.run(test_suite())

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

insert image description here

Software testing interview applet

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too! 

Guess you like

Origin blog.csdn.net/lzz718719/article/details/132669917