Recently, the front-end components of the system have been updated. I have made some modifications to the code of Web automation and optimized the use cases. Only a small number of test cases are reserved, and most of them are still in interface automation. There is one other point about PyTests that should be used more often, and I’ll cover it here.

I believe that some students will encounter a problem when using python unitTest framework to do web automation test, need to define the browser driver in the setUp method, in order to execute the case before opening the browser. If you’re executing a lot of cases, it’s going to take a lot of time to open the browser. Of course, you can open the browser one module at a time, but that’s still not what we want in the end.

1. The traditional way of using UnitTest

Here, using the UnitTest framework, open the browser before executing the use case under the previous DemoCase class.

class DemoCase(unittest.TestCase): def setUp(self): Print ('before test') self.driver = webdriver.Chrome() def test_demo1(self): XXXX def test_demo2(self): XXXX def tearDown(self): # self.driver.quit() if __name__ == '__main__': unittest.main()Copy the code

Use PyTest to open the browser once

You’ll need conftest.py and fixtures, as I covered in the previous article.

Another point is the principle of Web automation. In fact, our code sends an HTTP request to the browser under test, and the browser accepts the request, performs the corresponding action, and returns the execution status, return value and other information in Response. So when you start a browser you’re creating a session, so let’s implement the following.

Create confTest. py at the top of your case directory. If you’re not sure, put it in the project root directory. We then define a global browser driver in the confTest. py file, and take advantage of PyTest’s fixture feature to set the scope of the driver for the entire session in a few lines of code.

#conftest.py driver = None @pytest.fixture(scope='session', autouse=True) def browser(): Global driver if driver is None: driver = webdriver.chrome ()#GUI interface run driver.maximize_window() return driver #Copy the code

When used, pass in the driver where you need to launch the browser for page operations. Such as the following login operation

#test_demo.py def test_login_failed(browser, username, password, res): LP = LoginPage(browser) error_msg = lp.login_failed_and_return_error_msg (username, password) assert error_msg == resCopy the code

This is based on the page Object design pattern, and the corresponding LoginPage method encapsulates page operations.

Is not very simple, hurry to try it, welcome message exchange!