For websites requiring interactive operations, using pytest for API testing alone is insufficient as it doesn’t cover frontend interactions. Previously I used Selenium for browser control in web scraping tasks, but now I’ve found that Microsoft’s Playwright can also control browsers for automated testing, and it’s even simpler to use than Selenium since it supports automatic test case recording.
Installation
Using pixi makes Playwright installation quick, but after installation you still need to call Playwright to install browser dependencies. This differs from Selenium which directly uses browsers supported by the system.
1 | # Install firefox and chromium |
Using with Pytest
Playwright supports multiple languages and also works with Python’s Pytest framework. Using the command playwright codegen -b firefox http://127.0.0.1:8000
to open the browser, then selecting Pytest in the recording window allows you to record Pytest code. A recorded test would look like this:
1 | BASE_URL = 'http://127.0.0.1:8000' |
After creating test cases, you can run tests and see if any content needs trimming or adjustment.
Leveraging Pytest Features
When using Pytest for testing, Pytest’s fixture system and special conftest.py
files are all available, allowing information sharing between tests just like regular Pytest testing to make tests more efficient and stable.
Issues with Recording System
While the recording feature significantly speeds up test writing, automatic recording doesn’t always perfectly select page elements, especially when interactive elements are dynamically generated. Therefore, to write stable test cases, some frontend knowledge is still needed to uniquely identify target elements in the resource tree.