In test automation, capturing visual evidence of test executions can be invaluable for debugging, understanding behavior, and sharing results with stakeholders. While logging provides essential details, video recordings offer an additional layer of insight by showing what happened during a test. In this post, we'll explore how to easily record Selenium tests using Python, allowing us to visualize our automated test executions and make debugging more intuitive.
Video recording our Selenium test executions provides several advantages that can significantly enhance our testing workflow. Here are some key benefits:
By integrating video recording into our test automation process, we can improve both the quality of our debugging and the effectiveness of our communication with team members and stakeholders.
To record Selenium test executions, we'll be using Python along with the pyscreenrec library for capturing the screen. Let's break down the code step-by-step, starting with the necessary imports.
Importing Required LibrariesBefore we begin writing the test, we need to import the required libraries. We'll use selenium for browser automation, pyscreenrec for recording the screen, and a few additional Python modules for time management and threading.
from selenium import webdriver
import pyscreenrec
import time
from datetime import datetime
import threading
In this section, we set up the Selenium WebDriver. The WebDriver controls the browser and interacts with the web page. We also specify browser options, like the window size.
options = webdriver.ChromeOptions()
options.add_argument('--window-size=1280,720')
driver = webdriver.Chrome(options=options)
One of the key actions we want to capture in the video is scrolling. The scroll_page() function simulates scrolling by first going to the bottom of the page and then scrolling back to the top. This will give the test a dynamic flow, which can be useful for demonstrations.
def scroll_page(driver):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
driver.execute_script("window.scrollTo(0, 0);")
time.sleep(3)
The execute_script() method executes JavaScript to control the browser's scroll behavior. We add sleep() calls to ensure the browser has enough time to render the scroll actions.
Recording the Test SessionThe record_test function is designed to record a Selenium test execution, managing everything from setting up the recording environment to executing the test actions. It begins by handling the filename for the recording. If no filename is provided, it generates a default one based on the current timestamp, ensuring unique names for each test recording.
def record_test(driver, test_actions, max_duration=60, output_filename=None):
if output_filename is None:
output_filename = f"recording_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
Next, the function determines the coordinates of the browser's visible area using a helper function called get_browser_coordinates. This ensures that only the relevant portion of the screen, the browser viewport, is recorded. The returned coordinates include the browser's position and dimensions, adjusted to focus on the content displayed within the viewport.
coordinates = get_browser_coordinates(driver)
With the coordinates in hand, an instance of ScreenRecorder from the pyscreenrec library is initialized. This object controls the video recording process, allowing the function to define what portion of the screen to capture and at what frame rate.
recorder = pyscreenrec.ScreenRecorder()
To synchronize the test actions with the recording, the function uses a threading.Event. This event acts as a signal to indicate when the test actions have finished executing.
test_complete = threading.Event()
The test actions themselves are defined within an inner function called run_test. This function calls the provided test_actions callback to execute the Selenium test steps. Once the actions are complete, the event is set to signal their completion.
def run_test():
try:
test_actions()
finally:
test_complete.set()
The screen recording begins with the start_recording method, which is configured to capture the browser's viewport based on the calculated coordinates. The recording runs at 30 frames per second, focusing only on the primary monitor and the specified screen region.
recorder.start_recording(
output_filename,
30, # FPS
{
"mon": 1, # Primary monitor
"left": coordinates['left'],
"top": coordinates['top'],
"width": coordinates['width'],
"height": coordinates['height']
}
)
Finally, the function starts the test actions in a separate thread using the threading.Thread class. Running the test in a separate thread ensures that the recording process and the test execution can happen concurrently.
test_thread = threading.Thread(target=run_test)
test_thread.start()
After the test is complete or the maximum duration is reached, we stop the recording and save the video.
finally:
recorder.stop_recording()
test_thread.join(timeout=1)
print(f"Recording saved to: {output_filename}")
In the finally block, we stop the recording and ensure that the test thread completes. The recording file is saved with a timestamp to uniquely identify each video.
Running the TestThe final part of the script defines a simple test. The browser is opened, a URL is loaded, and the scroll_page() function is executed. The record_test() function is called to start the recording while the test runs.
def video_recording_test():
url = "https://www.example_website.com/"
driver = webdriver.Chrome(options=options)
try:
driver.get(url)
time.sleep(2) # Let the page load
def test_actions():
scroll_page(driver)
record_test(
driver=driver,
test_actions=test_actions,
max_duration=30,
output_filename="recording_test.mp4"
)
finally:
driver.quit()
The video_recording_test() function showcases the whole process: opening the browser, running the test actions, recording the test execution, and then saving the video. The URL of the test site can be changed, and additional actions can be added as needed.
Recording Selenium test executions adds immense value to QA automation by providing visual evidence of test runs, making debugging and reporting more efficient. In this post, we demonstrated how to easily integrate video recording into Python-based Selenium tests using pyscreenrec, offering a practical and lightweight solution. By adopting this approach, we can enhance collaboration, streamline troubleshooting, and add clarity to our automation efforts with minimal effort.
For the complete code example, please visit our GitHub page. Until next time 👋.