Selenium - POM mode, unittest framework

1, POM mode

POM structure:

Project name file:

common folder:
base.py file: secondary encapsulation of selenium:
1. Open browser
2. Open address
3. Element positioning
4. Element operation

page folder:
1. Encapsulate each page of the project

2.page folder: divide the page into three layers
Presentation layer: elements visible in the page
Operation layer: operation on visible elements
Business layer: the scenario / business is formed by the combination of operation layer

Class 3.page:
Content:
① Packaging presentation layer: making positioner
② Encapsulate the operation layer: operate each element in the positioner, and form the operation into a method
③ page class inherits Base

script folder:
Store test cases and use unittest to manage them
1. Only focus on the operation steps. If the test data is involved, temporarily write it as dead data
2. Confirm assertion
3. Focus on the flexibility of test data

2, unittest framework

1. role:
Specification of automatic test case writing
Manage the execution of automated test cases

2. Basic concepts
Test fixture: test fixture handles data preparation before test and data cleaning after test
test suite: test suite collects test cases to be executed in batch
Test case: the core part of test case. The test case conforms to the requirements of unittest framework
Test execution: test runner executes the test cases collected by the test suite

3. Special methods
setUp: in a py file, execute the test case before execution. How many test cases are there and how many times are they executed
tearDown: in a py file, the test cases are executed after execution. How many test cases are there and how many times are they executed
setUpClass: in a py file, execute the test class before it executes, requiring @ classmethod decoration
Teardown class: in a py file, execute after the test class is executed. It needs @ classmethod decoration

4. Notes for use case writing
① Test case file name starts with test
② Test case class name starts with Tset
③ Test case method name starts with test
④ Execution order of test cases: sort the case names by ASCII character set

5. assertion
Syntax:

assertEqual(a,b,msg="Output when assertion fails")
#Judge whether a and b are equal. If they are equal, the assertion succeeds. Otherwise, the assertion fails
assertTrue(x,msg="Output when assertion fails")
#When condition x is True, the assertion succeeds, otherwise the assertion fails -- > case execution fails

Where to add assertions: in test cases

Be careful:
For assertions, only those that fail will be prompted
Keyword of assertion failure: AssertionError, indicating that case execution failed, not code error

5. Test Suite & test execution
① Test suite:

unittest.defaultTestLoader

② Test execution

unittest.TxetTestRunner

Preparation steps:
Add test case storage path
Add test cases that need to be executed to the test suite
Execute test case

6. Test report
Generate test report in html format
Operation steps
① Copy the HTMLTestRunnerPlugins.py file to the python installation directory / lib directory
② Import unittest and htmltestrunner plugins
③ Determine test case storage path
④ Determine the storage path of test report
⑤ Name the test report, open the scheduled test report, and prepare to write
⑥ Put the test cases to be executed into the test suite
⑦ Execute test cases and generate test reports in html format
Give an example:

# 1. Import unittest and HTMLTestRunnerPlugins
import unittest
import HTMLTestRunnerPlugins
import time
import os
# 2. Determine the storage path of test cases
case_dir = "./script"
# 3. Determine the storage path of test report
report_dir = "./report"
# 4. Name the test report, open the scheduled test report, and prepare to write
# Name test report with current time
now = time.strftime("%Y-%m-%d %H_%M_%S")
report_name = now + "report.html"  # Test report name
with open(os.path.join(report_dir,report_name),"wb") as fp:
# 5. Put the test cases to be executed into the test suite
    discover = unittest.defaultTestLoader.discover(case_dir)
# 6. Execute test cases and generate test reports in html format
    runner = HTMLTestRunnerPlugins.HTMLTestRunner(title="ECShop Automated test report",
                                                  description="Sign in,register,Shopping cart function",
                                                  stream=fp,
                                                  verbosity=2)
    runner.run(discover)

7. Unit test parameterization
① Parameterization of ddt module
② Prepare test data
③ Use before testing the class: @ ddt.ddt
④ Use before test cases

@ddt.data(* data source)
def test case (self,data)
#Prepare data for list nested dictionary format
@ddt.data(* data source)
@ddt.unpark
 def test case (parameter)
#Applicable to list nested list format of data source

8. File version data source

"""
1.read csv file/excel form
2.Use pandas Module reading
3.download pandas Modular
    pip install pandas
    pip install xlrd
"""
import pandas
import os


class OperationData:
    def __init__(self,filename):
        """
        os.path.dirname(__file__)  # Represents the current path
        os.path.abspath(__file__)   # Absolute path
        os.path.dirname(os.path.dirname(__file__))  #  Indicates the parent directory of the file
        :param filename: file name
        """
        base_path = os.path.dirname(os.path.dirname(__file__)) + "/data"  # Go back to the root directory of the project and enter the data directory
        file_path = os.path.join(base_path,filename)
        if filename.split(".")[-1] == "csv":  # By judging whether the file suffix is a csv shunt
            self.file = pandas.read_csv(file_path)  # Read csv file
        else:
            self.file = pandas.read_excel(file_path)  # Read excel table

    def get_data_to_dict(self):
        """Read data into list nested dictionary format[{},{},{}]"""
        # data = []  # Create an empty list to store data
        # for i in self.file.index.values:  # Traverse all rows
        #     row_data = self.file.loc[i].to_dict()  # Convert the value of each row to dictionary format
        #     data.append(row_data)
        #
        # return data
        # List builder
        return [self.file.loc[i].to_dict() for i in self.file.index.values]

    def get_data_to_list(self):
        """Read data to list nested list format[[],[],[]]"""
        return self.file.values.tolist()


if __name__ == '__main__':
    oper = OperationData("userdata.xls")
    # data = oper.get_data_to_dict()
    data = oper.get_data_to_list()
    print(data)



Published 26 original articles, won praise 0, visited 280
Private letter follow

Keywords: Excel pip Selenium ascii

Added by micah1701 on Thu, 13 Feb 2020 23:44:15 +0200