Sample code for selenium+unittest to implement web automation!

This article mainly introduces the sample code of selenium + unittest to realize web automation. The sample code is introduced in great detail and has certain reference learning value for everyone’s study or work. Friends who need it can follow the editor to learn together.

The purpose of learning unittest earlier is to use it to write Web automated test cases, so next we will combine unittest with Selenium to write an example of Web automated testing.

We still use Baidu search as an example to create the test_baidu.py file

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

twenty one

twenty two

twenty three

twenty four

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

# _*_ coding:utf-8 _*_

"""

name:zhangxingzai

date:2023/2/25

"""

import unittest

from time import sleep

from selenium import webdriver

from selenium.webdriver.common.by import By

class TestBaidu(unittest.TestCase):

def setUp(self):

self.driver = webdriver.Firefox()

self.baidu_url = 'https://www.baidu.com'

def test_search_key_unittest(self):

self.driver.get(self.baidu_url)

self.driver.find_element(By.ID, 'kw ').send_keys('unittest')

self.driver.find_element(By.ID, 'su ').click()

sleep(2)

title = self.driver.title

self.assertEqual(title, 'unittest_Baidu Search')

def test_search_key_selenium(self):

self.driver.get(self.baidu_url)

self.driver.find_element(By.ID, 'kw ').send_keys('selenium')

self.driver.find_element(By.ID, 'su ').click()

sleep(2)

title = self.driver.title

self.assertEqual(title, 'selenium_Baidu Search')

def tearDown(self):

self.driver.close()

if __name__ == '__main__':

unittest.main

Without going into too much detail about the above code, unittest is used to create test classes and methods. The code in the method is Selenium script. However, there are some problems with the code here, let’s improve them one by one.

First of all, observing the code, we can find that the steps in the two test cases are the same. The only difference is that the search keywords and assertion results are different. I have learned python modularization, so here I encapsulate the operation steps into a method.

code show as below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

twenty one

twenty two

twenty three

twenty four

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

# _*_ coding:utf-8 _*_

"""

name:zhangxingzai

date:2023/2/25

"""

import unittest

from time import sleep

from selenium import webdriver

from selenium.webdriver.common.by import By

class TestBaidu(unittest.TestCase):

def setUp(self):

self.driver = webdriver.Firefox()

self.baidu_url = 'https://www.baidu.com'

# Encapsulate the access and search process of Baidu homepage into a baidu_search() method

def baidu_search(self, search_key):

self.driver.get(self.baidu_url)

self.driver.find_element(By.ID, 'kw ').send_keys(search_key)

self.driver.find_element(By.ID, 'su ').click()

sleep(2)

def test_search_key_unittest(self):

search_key = 'unittest'

self.baidu_search(search_key)

self.assertEqual(self.driver.title, search_key + 'Baidu Search')

def test_search_key_selenium(self):

search_key = "selenium"

self.baidu_search(search_key)

self.assertEqual(self.driver.title, search_key + "Baidu Search")

def tearDown(self):

self.driver.close()

if __name__ == '__main__':

unittest.main

Here, the access and search process of Baidu homepage is encapsulated into a baidu_search() method, and the search_key parameter is defined as the search keyword, and searches for different contents are performed based on the received keywords. The baidu_search() method here will not be executed as a test case, because according to unittest’s rules for finding and executing test cases, it will only treat methods starting with “test” as test cases.

Now I have also found a lot of test friends and created a communication group to share technology, sharing a lot of technical documents and video tutorials we collected.
If you don’t want to experience the feeling of not being able to find resources when studying on your own, having no one to answer your questions, and persisting for a few days before giving up.
You can join us to communicate. And there are many technical experts who have made certain achievements in automation, performance, security, test development, etc.
Share their experience, and also share many live lectures and technical salons
You can learn for free! Focus on it! Open source! ! !
QQ group number: 110685036 [password: csdn999]

Another question worth discussing is whether the assertions of the test case should be written in the encapsulated method? As you can see from the previous code, the assertion points of the tests are the same. It is preferable to write assertions in each test case. Because many times even if the operation steps are the same, the assertion points are not exactly the same. From a design perspective, it will also be clearer if assertions are written in every test case.

In addition, we also found that each test case requires starting and closing the browser, which is very time-consuming. So how to reduce the number of browser startups and shutdowns? This problem can be solved by using the setUpClass/tearDownClass learned earlier.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

twenty one

twenty two

twenty three

twenty four

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

# _*_ coding:utf-8 _*_

"""

name:zhangxingzai

date:2023/2/25

"""

import unittest

from time import sleep

from selenium import webdriver

from selenium.webdriver.common.by import By

class TestBaidu(unittest.TestCase):

@classmethod

def setUpClass(cls):

cls.driver = webdriver.Firefox()

cls.baidu_url = 'https://www.baidu.com'

def baidu_search(self, search_key):

self.driver.get(self.baidu_url)

self.driver.find_element(By.ID, 'kw ').send_keys(search_key)

self.driver.find_element(By.ID, 'su ').click()

sleep(2)

def test_search_key_unittest(self):

search_key = 'unittest'

self.baidu_search(search_key)

self.assertEqual(self.driver.title, search_key + '_Baidu Search')

def test_search_key_selenium(self):

search_key = 'selenium'

self.baidu_search(search_key)

self.assertEqual(self.driver.title, search_key + '_Baidu Search')

@classmethod

def tearDownClass(cls):

cls.driver.close()

if __name__ == '__main__':

unittest.main

before fixing:

After modification:

You can see that as much as 16 seconds are saved after the modification. Although we define the driver here as cls.driver, it is still self.driver when used in each test case.

When all test cases in the entire test class have been run, cls.driver.quit() will be called to close the browser.

When there are multiple test cases in a test class, this method will greatly shorten the execution time of the test cases.

In this way, we get a simple automated test script for Baidu search. Readers can try other scenarios based on this example.

This concludes this article about the sample code for selenium + unittest to implement web automation.

Finally, I would like to thank everyone who has read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software testing interview document

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.