This post shows the full process – start to finish – by actually designing a tiny app while we go.…
If your role is linked with an area of business that impacts ROI, you can probably quite clearly tell in…
Designing user interfaces is no easy task. With countless choices around layout, spacing, typography, and colour, it’s easy to feel…
Post Content Source: Read MoreÂ
Amazon operations span the globe, touching the lives of millions of customers, employees, and vendors every day. From the vast…
In this post, we demonstrate how to build a multi-agent system using multi-agent collaboration in Amazon Bedrock Agents to solve…
1. Selenium Architecture & Core ConceptsQ1: Explain Selenium WebDriver’s architecture in detailAnswer:Selenium WebDriver follows a client-server architecture with these key components:Client Libraries (Language Bindings)Available in Java, Python, C#, JavaScript, etc.Convert test script commands into HTTP requests via JSON Wire Protocol (or W3C WebDriver Protocol)Browser DriversChromeDriver (for Chrome), GeckoDriver (Firefox), etc.Act as intermediaries that translate HTTP requests into browser-specific actionsEach browser has its own driver implementationReal BrowsersReceive commands from their respective driversExecute actions like click(), sendKeys() nativelyVisual Flow:Test Script → Language Binding → JSON Wire Protocol → Browser Driver → Actual BrowserKey Protocols:Legacy: JSON Wire Protocol (Selenium 3)Modern: W3C WebDriver Protocol (Selenium 4+)Q2: How does Selenium interact with headless browsers?Answer with Technical Details:Headless browsers execute without GUI for faster performance. Implementation:javaChromeOptions options = new ChromeOptions();
options.addArguments(“–headless”, “–disable-gpu”);
// ‘–disable-gpu’ avoids potential rendering issues
options.addArguments(“–window-size=1920,1080”);
// Sets viewport size for consistent rendering
WebDriver driver = new ChromeDriver(options);Why Use Headless?2-3x faster execution (no UI rendering overhead)Ideal for CI/CD pipelines (Jenkins, GitHub Actions)Better for Linux servers without GUI environmentsLimitations:Harder to debug (no visual feedback)Some anti-bot systems detect headless modeAlternatives:Firefox Headless: options.addArguments(“–headless”)PhantomJS (deprecated)2. Advanced WebDriver TechniquesQ3: How would you handle a StaleElementReferenceException?Deep Dive Solution:This occurs when the DOM changes after element location but before interaction. Robust handling:javapublic void safeClick(By locator, int maxRetries) {
int attempts = 0;
while (attempts < maxRetries) {
try {
driver.findElement(locator).click();
break;
} catch (StaleElementReferenceException e) {
attempts++;
if (attempts == maxRetries) throw e;
// Optional: Add small wait
try { Thread.sleep(200); } catch (InterruptedException ie) {}
}
}
}
// Usage:
safeClick(By.id(“dynamic-button”), 3);Root Causes:Page refresh/AJAX updatesDOM re-rendering (common in React/Angular apps)Navigation between pagesPrevention Strategies:Use Page Object Model with re-initialized elementsImplement custom ExpectedConditions for dynamic elementsPrefer relative locators over absolute XPathsQ4: Automate file download without third-party toolsComprehensive Solution:java// Chrome Configuration
ChromeOptions options = new ChromeOptions();
// Set download directory (escape backslashes in Windows)
String downloadPath = “C:\test_downloads”;
options.setExperimentalOption(“prefs”, Map.of(
“download.default_directory”, downloadPath,
“download.prompt_for_download”, false,
“download.directory_upgrade”, true,
“safebrowsing.enabled”, true // Disables security warnings
));
// Disable PDF viewer to force downloads
options.addArguments(“–disable-extensions”);
options.addArguments(“–disable-print-preview”);
WebDriver driver = new ChromeDriver(options);
// Trigger download
driver.get(“https://example.com/file.pdf”);
// Verification (Java 11+)
long waitTime = 30; // seconds
Path file = Path.of(downloadPath, “file.pdf”);
boolean isDownloaded = Files.waitUntilExists(file, waitTime);Key Considerations:Browser-specific configurations (Chrome vs Firefox)Network speed impacts download completionCleanup downloaded files between testsEdge Cases:Handling “Save As” dialogs (requires OS-level automation)Large file timeouts3. Framework Design & PatternsQ5: Explain the Hybrid Framework in SeleniumDetailed Architecture:Component Breakdown:Page Object Model (POM)Each page as a Java class (LoginPage.java)Elements stored as @FindBy annotationsMethods for page actions (login(String user, String pass))Data-Driven TestingExternalize test data to JSON/ExcelTestNG @DataProvider feeds multiple datasetsjava@DataProvider
public Object[][] loginData() {
return new Object[][] {
{“user1”, “pass123”},
{“user2”, “pass456”}
};
}Keyword-DrivenNon-technical test cases in Excel:ActionLocatorValueclickid=submit-btntypename=emailtest@demo.comAdvantages:60-70% less code maintenanceEnables parallel executionBusiness-readable test cases4. Performance OptimizationQ6: How to reduce flaky tests?Proven Strategies with Examples:Smart Waitsjavapublic WebElement waitForClickable(By locator, int timeout) {
return new WebDriverWait(driver, Duration.ofSeconds(timeout))
.until(ExpectedConditions.elementToBeClickable(locator));
}Retry Mechanismjava@Test(retryAnalyzer = RetryAnalyzer.class)
public void flakyTest() { … }Locator StabilityAvoid XPaths like //div[3]/button[1]Prefer CSS selectors: button.submit-btnTest IsolationClear cookies between testsUse fresh user sessionsMonitoring:Track flakiness percentageQuarantine unstable tests5. Real-World ScenariosQ7: Automate testing for a real-time stock dashboardSolution Architecture:Implementation Steps:WebSocket Testingjava// Using Java-WebSocket library
WebSocketClient client = new WebSocketClient(new URI(“wss://stocks”)) {
@Override
public void onMessage(String message) {
// Parse JSON and assert values
}
};
client.connect();Visual RegressionjavaBufferedImage current = new AShot()
.shootingStrategy(ShootingStrategies.viewportPasting(1000))
.takeScreenshot(driver)
.getImage();
ImageIO.write(current, “PNG”, new File(“current.png”));Database AssertionsjavaStatement stmt = dbConnection.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT price FROM stocks”);
assertTrue(rs.next());
assertEquals(150.25, rs.getDouble(“price”), 0.01);Challenges:High-frequency updatesTime synchronizationDynamic chart renderingQ8: Parallel Test Execution Implementation (Deep Dive)TestNG Parallel Execution Explained:The TestNG XML configuration enables parallel execution at multiple levels:xml<suite name=”ParallelSuite” parallel=”tests” thread-count=”4″ configfailurepolicy=”continue”>
<!– Suite-level parallel execution –>
<test name=”ChromeTests” parallel=”classes” thread-count=”2″>
<parameter name=”browser” value=”chrome”/>
<classes>
<class name=”com.tests.LoginTest”/>
<class name=”com.tests.CheckoutTest”/>
</classes>
</test>
<test name=”FirefoxTests”>
<parameter name=”browser” value=”firefox”/>
<packages>
<package name=”com.module1.tests.*”/>
</packages>
</test>
</suite>Key Attributes:parallel=”tests|classes|methods|instances”:tests: Parallel test tagsclasses: Parallel test classesmethods: Parallel test methodsthread-count: Maximum concurrent threadsconfigfailurepolicy=”continue”: Continue execution after failed configurationsImplementation Best Practices:Use @BeforeClass for browser initializationMake tests independent with proper cleanupUtilize ThreadLocal<WebDriver> for thread-safe driver managementBalance thread count with system resources (optimal is CPU cores × 1.5)Advanced Scenario: Cross-Browser Parallelismxml<test name=”CrossBrowser”>
<methods>
<include name=”testLogin” invocation-count=”3″>
<parameter name=”browser” value=”chrome”/>
<parameter name=”browser” value=”firefox”/>
<parameter name=”browser” value=”edge”/>
</include>
</methods>
</test>Q9: BDD Framework Advantages (Expanded)Cucumber/Gherkin Workflow:textFeature: Login functionality
Scenario: Successful login
Given I navigate to login page
When I enter valid “testuser” and “Pass123”
Then I should see dashboardTechnical Benefits:Living Documentation:Feature files serve as always-updated specsAutomated generation of documentation (e.g., with Pickles)Step Reusability:java@When(“I enter valid {string} and {string}”)
public void enterCredentials(String user, String pass) {
loginPage.enterCredentials(user, pass);
}CI/CD Integration:JSON/HTML reports integration with JenkinsTag-based execution (@smoke, @regression)Test Data Management:Scenario outlines with examples tables:textExamples:
| username | password |
| user1 | Password1! |
| user2 | Password2! |Collaboration Impact:Product owners can validate scenariosDevelopers and QA share step definitionsReduces misinterpretation of requirementsQ10: Flaky Test Solutions (Comprehensive Guide)Root Cause Analysis Matrix:CauseSolutionCode ExampleElement StalenessRe-locate element before interactionnew WebElementProxy(driver, locator).click()Timing IssuesSmart waits with custom conditionswait.until(d -> element.isDisplayed())Test Order DependencyIndependent test data@BeforeMethod void cleanCookies()Environment VarianceDockerized consistent environmentsdocker-compose up selenium-hubAdvanced Techniques:Retry Analyzer:javapublic class RetryAnalyzer implements IRetryAnalyzer {
private int count = 0;
private static final int MAX_RETRY = 2;
public boolean retry(ITestResult result) {
return count++ < MAX_RETRY &&
result.getThrowable() instanceof StaleElementReferenceException;
}
}Element State Monitoring:javapublic void safeClick(By locator) {
wait.until(d -> {
try {
WebElement el = d.findElement(locator);
return el.isDisplayed() && el.isEnabled();
} catch (StaleElementReferenceException e) {
return false;
}
}).click();
}Q11: Test Speed Optimization (Professional Approach)Performance Benchmarking Table:TechniqueSpeed GainImplementationHeadless Mode40-60% fasteroptions.addArguments(“–headless”)CDP Mocking30% faster API callsdevTools.send(Network.enable())Disable Images25% faster loadsprefs.put(“profile.managed_default_content_settings.images”, 2)DOM Freeze DetectionPrevent wasted waits((JavascriptExecutor)driver).executeScript(“return document.readyState”)Chrome DevTools Protocol Example:javaDevTools devTools = ((ChromeDriver)driver).getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
devTools.send(Network.emulateNetworkConditions(
false, 100, 5000, 2000,
Optional.of(ConnectionType.CELLULAR3G)
);Advanced Configurations:javaChromeOptions options = new ChromeOptions();
options.setCapability(“goog:loggingPrefs”, new LoggingPreferences());
options.addArguments(“–disable-extensions”);
options.addArguments(“–disable-notifications”);
options.addArguments(“–disable-web-security”);
options.setExperimentalOption(“excludeSwitches”,
new String[]{“enable-automation”});Q12: Jenkins Integration (Production-Grade Setup)Pipeline Script Example:groovypipeline {
agent any
stages {
stage(‘Checkout’) {
steps {
git branch: ‘main’, url: ‘https://github.com/your/repo.git’
}
}
stage(‘Test’) {
parallel {
stage(‘Chrome’) {
steps {
sh “mvn test -Dbrowser=chrome -Dgroups=smoke”
}
}
stage(‘Firefox’) {
steps {
sh “mvn test -Dbrowser=firefox -Dgroups=smoke”
}
}
}
}
stage(‘Report’) {
steps {
allure includeProperties: false, jdk: ”, results: [[path: ‘target/allure-results’]]
}
}
}
post {
always {
archiveArtifacts artifacts: ‘target/surefire-reports/**/*’, fingerprint: true
}
}
}Key Plugins:Allure Reporting: Trend analysis and historical comparisonsTest Results Analyzer: Identify flaky testsBuild Pipeline: Visualize test stagesSlack Notification: Alert on failuresQ13: Dockerized Selenium (Enterprise Architecture)Production-Ready docker-compose.yml:yamlversion: ‘3.8’
services:
hub:
image: selenium/hub:4.1.0
ports:
– “4442:4442” # Grid console
– “4443:4443” # Live sessions
environment:
– SE_EVENT_BUS_HOST=hub
– SE_NODE_MAX_SESSIONS=5
deploy:
resources:
limits:
cpus: ‘1’
memory: 2G
chrome:
image: selenium/node-chrome:4.1.0
shm_size: 2gb
environment:
– SE_EVENT_BUS_HOST=hub
– SE_NODE_MAX_SESSIONS=3
depends_on:
– hub
volumes:
– /dev/shm:/dev/shm # Critical for Chrome stabilityScaling with Kubernetes:bashkubectl create deployment selenium-hub –image=selenium/hub
kubectl scale deployment selenium-node –replicas=5Best Practices:Use –shm-size for Chrome containersImplement health checks with SE_NODE_HEALTHCHECK_INTERVALConfigure session timeout with SE_NODE_SESSION_TIMEOUTQ14: CAPTCHA Testing Strategies (Compliance-Friendly)Enterprise Solutions:Test Environment Bypass:Development flag: ?disable_captcha=trueMock service response:java@Mock
CaptchaService captchaService;
when(captchaService.verify(anyString())).thenReturn(true);Third-Party Services:2Captcha API integrationAnti-Captcha services with Selenium bindingsLegal Compliance:Whitelist test IPs in CAPTCHA configurationUse enterprise bypass tokensAutomation Workaround Example:javapublic void bypassCaptcha() {
if (isTestEnvironment()) {
driver.executeScript(
“document.getElementById(‘captcha’).value = ‘BYPASSED'”);
} else {
solveRealCaptcha();
}
}Q15: Real-Time Dashboard Testing (Financial Grade)WebSocket Testing Framework:javapublic class StockTickerTest {
private WebSocketClient client;
@BeforeMethod
public void connect() throws URISyntaxException {
client = new WebSocketClient(new URI(“wss://api.stock.com”)) {
@Override
public void onMessage(String message) {
StockData data = new Gson().fromJson(message, StockData.class);
assertTrue(data.getPrice() > 0);
}
};
client.connect();
}
@Test
public void testPriceUpdates() {
driver.findElement(By.id(“refresh”)).click();
await().atMost(5, SECONDS).untilAsserted(() -> {
assertNotNull(lastMessage);
});
}
}Visual Regression Pipeline:Baseline capture on releasePixel-by-pixel comparison with tolerance thresholdsDynamic element masking (timestamps, moving averages)AI-based anomaly detection (Applitools Eyes)Data Validation Approach:sqlSELECT stock_symbol, COUNT(*)
FROM price_updates
WHERE timestamp > NOW() – INTERVAL ‘1 minute’
GROUP BY stock_symbol
HAVING COUNT(*) < 10; — Expecting 10+ updates per minuteConclusionThese detailed explanations demonstrate deep technical understanding that interviewers value. These expanded explanations provide the technical depth and real-world implementation details that senior automation engineers having experience 4 to 10 years need during interviews.Pro Tip: Always relate answers to your project experience during interviews.#Selenium #Testing #InterviewPrep 🚀
IntroductionVisual testing is crucial for ensuring UI consistency across releases. While commercial tools exist, sometimes you need a custom solution tailored to your specific needs. This guide walks you through creating your own visual testing tool using Selenium and Python.Table of ContentsIntroductionWhy Build a Custom Visual Testing Tool?Core ComponentsImplementation GuideAdvanced FeaturesIntegration & ScalingReporting & AnalysisCommon Challenges & SolutionsLimitations & ConsiderationsConclusion & Next StepsWhy Build a Custom Solution?Specific requirements not met by commercial toolsCost savings for simple projectsComplete control over comparison logicLearning opportunity about image processingCore Components1. Screenshot Capture with Seleniumpythonfrom selenium import webdriver
import os
def capture_screenshot(url, filename):
“””Capture screenshot of a webpage”””
driver = webdriver.Chrome()
driver.get(url)
# Ensure screenshot directory exists
os.makedirs(“screenshots”, exist_ok=True)
screenshot_path = f”screenshots/{filename}”
driver.save_screenshot(screenshot_path)
driver.quit()
return screenshot_path2. Image Comparison Enginepythonfrom PIL import Image, ImageChops
import math
def compare_images(baseline_path, current_path, diff_path=None, threshold=0.95):
“””
Compare two images with similarity threshold
Returns: (is_similar, similarity_score)
“””
baseline = Image.open(baseline_path).convert(‘RGB’)
current = Image.open(current_path).convert(‘RGB’)
# Check dimensions
if baseline.size != current.size:
return False, 0
# Calculate difference
diff = ImageChops.difference(baseline, current)
diff_pixels = sum(
sum(1 for pixel in diff.getdata() if any(c > 0 for c in pixel))
)
total_pixels = baseline.size[0] * baseline.size[1]
similarity = 1 – (diff_pixels / total_pixels)
# Save diff image if needed
if diff_path and diff_pixels > 0:
diff.save(diff_path)
return similarity >= threshold, similarity3. Baseline Management Systempythonimport json
from datetime import datetime
class BaselineManager:
def __init__(self, baseline_dir=”baselines”):
self.baseline_dir = baseline_dir
os.makedirs(baseline_dir, exist_ok=True)
def save_baseline(self, name, image_path):
“””Save a new baseline with metadata”””
timestamp = datetime.now().isoformat()
baseline_path = f”{self.baseline_dir}/{name}.png”
metadata = {
“created”: timestamp,
“source”: image_path
}
# Save image
Image.open(image_path).save(baseline_path)
# Save metadata
with open(f”{baseline_dir}/{name}.json”, ‘w’) as f:
json.dump(metadata, f)
return baseline_pathAdvanced Features1. Region-Specific Comparisonpythondef compare_regions(baseline_path, current_path, regions, threshold=0.95):
“””
Compare specific regions of images
regions: List of (x, y, width, height) tuples
“””
baseline = Image.open(baseline_path)
current = Image.open(current_path)
results = []
for region in regions:
x, y, w, h = region
baseline_crop = baseline.crop((x, y, x+w, y+h))
current_crop = current.crop((x, y, x+w, y+h))
is_similar, score = compare_images(
baseline_crop, current_crop, threshold=threshold
)
results.append((region, is_similar, score))
return results2. Dynamic Content Maskingpythondef mask_dynamic_regions(image_path, regions, output_path=None):
“””
Mask dynamic content regions with black rectangles
“””
img = Image.open(image_path)
draw = ImageDraw.Draw(img)
for region in regions:
x, y, w, h = region
draw.rectangle((x, y, x+w, y+h), fill=’black’)
if output_path:
img.save(output_path)
return imgPutting It All Togetherpythondef run_visual_test(url, test_name, threshold=0.95):
“””Complete visual test workflow”””
# Setup
bm = BaselineManager()
current_path = capture_screenshot(url, f”current_{test_name}.png”)
# Check if baseline exists
baseline_path = f”baselines/{test_name}.png”
if not os.path.exists(baseline_path):
print(f”Creating new baseline for {test_name}”)
bm.save_baseline(test_name, current_path)
return True
# Compare images
diff_path = f”diffs/diff_{test_name}.png”
is_similar, score = compare_images(
baseline_path, current_path, diff_path, threshold
)
# Generate report
report = {
“test_name”: test_name,
“passed”: is_similar,
“similarity_score”: score,
“diff_image”: diff_path if not is_similar else None,
“timestamp”: datetime.now().isoformat()
}
return reportHandling Common ChallengesCross-Browser VariationsCreate separate baselines per browserAdjust similarity thresholds per browserResponsive TestingTest at multiple viewport sizesUse device emulation in SeleniumTest MaintenanceImplement baseline versioningAdd approval workflow for new baselinesPerformance OptimizationCache screenshotsParallelize testsIntegration with Test Frameworkspythonimport unittest
class VisualTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.bm = BaselineManager()
def test_homepage_layout(self):
report = run_visual_test(
“https://example.com”,
“homepage_desktop”,
threshold=0.98
)
self.assertTrue(report[‘passed’],
f”Visual regression detected. Similarity: {report[‘similarity_score’]}”)Reporting and Analysispythondef generate_html_report(test_reports):
“””Generate visual test HTML report”””
html = “””
<html><head><title>Visual Test Report</title></head>
<body><h1>Visual Test Results</h1>
<table border=”1″>
<tr>
<th>Test</th>
<th>Status</th>
<th>Similarity</th>
<th>Diff</th>
</tr>
“””
for report in test_reports:
status = “PASS” if report[‘passed’] else “FAIL”
color = “green” if report[‘passed’] else “red”
diff_link = f'<a href=”{report[“diff_image”]}”>View</a>’ if report[“diff_image”] else “None”
html += f”””
<tr>
<td>{report[‘test_name’]}</td>
<td style=”color:{color}”>{status}</td>
<td>{report[‘similarity_score’]:.2%}</td>
<td>{diff_link}</td>
</tr>
“””
html += “</table></body></html>”
return htmlScaling Your SolutionParallel ExecutionUse Selenium GridImplement multiprocessingBaseline ManagementStore baselines in cloud storageAdd metadata taggingCI/CD IntegrationAdd as a test step in your pipelineConfigure failure thresholdsLimitations to ConsiderMaintenance overhead for baseline updatesBrowser-specific rendering differencesPerformance impact of image processingLimited to pixel comparison (no semantic understanding)ConclusionBuilding a custom visual testing tool gives you flexibility but requires careful implementation. Start small with critical pages, then expand as needed. Consider these enhancements:Add machine learning for smarter diff detectionImplement cloud storage for baselinesCreate a dashboard for trend analysisAdd support for component-level testingRemember that commercial tools might become more cost-effective as your needs grow, but a custom solution can be perfect for specific requirements.
Visual testing is an essential part of UI validation, ensuring that web applications appear and function as intended across different browsers, devices, and screen resolutions. While Selenium is primarily used for functional testing, it can also be leveraged for visual regression testing with the help of additional tools and libraries.In this blog, we’ll explore how to perform visual testing using Selenium, covering key concepts, tools, and step-by-step implementation.Table of ContentsWhat is Visual Testing?Why Use Selenium for Visual Testing?Tools for Visual Testing with SeleniumStep-by-Step Guide to Perform Visual TestingPrerequisitesSetting Up Selenium WebDriverCapturing ScreenshotsComparing ScreenshotsGenerating Test ReportsGeneral Steps to Perform Visual TestingBest Practices for Visual TestingConclusion1. What is Visual Testing?Visual testing (or visual regression testing) compares screenshots of a web application’s UI against baseline images to detect unintended visual changes. It helps identify issues like:Layout shiftsBroken fonts or imagesOverlapping elementsResponsive design failuresUnlike functional testing, which verifies behavior, visual testing ensures the UI looks correct.2. Why Use Selenium for Visual Testing?Selenium WebDriver is widely used for automating browser interactions. While it doesn’t natively support visual comparisons, it can:Capture screenshots of web pages.Integrate with visual testing libraries (e.g., Applitools, Percy, or OpenCV).Run cross-browser tests to ensure consistency.3. Tools for Visual Testing with SeleniumHere are some popular tools for visual testing with Selenium:ToolDescriptionApplitoolsAI-powered visual testing with automatic baseline management.PercyCloud-based visual testing by BrowserStack.AShotJava-based screenshot comparison library.OpenCVOpen-source computer vision library for image processing.SikuliXUses image recognition for UI testing.We’ll use AShot (for Java) and Pillow (for Python) in this guide.4. Step-by-Step Guide to Perform Visual TestingPrerequisites Java/Python installedSelenium WebDriverMaven/Gradle (for Java) or pip (for Python)A testing framework (JUnit/TestNG for Java, pytest for Python)Setting Up Selenium WebDriverJava (Maven)xml<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>ru.yandex.qatools.ashot</groupId>
<artifactId>ashot</artifactId>
<version>1.5.4</version>
</dependency>Python (pip)bashpip install selenium pillow opencv-pythonCapturing ScreenshotsJava (Using AShot)javaimport org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import javax.imageio.ImageIO;
import java.io.File;
public class VisualTest {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get(“https://example.com”);
// Capture screenshot
Screenshot screenshot = new AShot().takeScreenshot(driver);
ImageIO.write(screenshot.getImage(), “PNG”, new File(“screenshot.png”));
driver.quit();
}
}Python (Using Pillow)pythonfrom selenium import webdriver
from PIL import Image
driver = webdriver.Chrome()
driver.get(“https://example.com”)
# Capture screenshot
driver.save_screenshot(“screenshot.png”)
driver.quit()Comparing ScreenshotsJava (Using AShot)javaimport java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class ImageComparator {
public static boolean compareImages(String img1Path, String img2Path) throws Exception {
BufferedImage img1 = ImageIO.read(new File(img1Path));
BufferedImage img2 = ImageIO.read(new File(img2Path));
if (img1.getWidth() != img2.getWidth() || img1.getHeight() != img2.getHeight()) {
return false;
}
for (int y = 0; y < img1.getHeight(); y++) {
for (int x = 0; x < img1.getWidth(); x++) {
if (img1.getRGB(x, y) != img2.getRGB(x, y)) {
return false;
}
}
}
return true;
}
}Python (Using OpenCV)pythonimport cv2
import numpy as np
def compare_images(img1_path, img2_path):
img1 = cv2.imread(img1_path)
img2 = cv2.imread(img2_path)
if img1.shape != img2.shape:
return False
difference = cv2.subtract(img1, img2)
return not np.any(difference)Generating Test Reports Use testing frameworks like TestNG (Java) or pytest (Python) to log results:java@Test
public void testVisualComparison() throws Exception {
Assert.assertTrue(ImageComparator.compareImages(“expected.png”, “actual.png”));
}5. General Steps When Using a Visual Testing PlatformWhen using a dedicated visual testing platform (e.g., Percy, Applitools), follow these steps:1. Set Up Your Selenium ProjectEnsure you have a working Selenium automation framework in your preferred language (Java, Python, C#, JavaScript, etc.).2. Integrate the Visual Testing SDKInstall the SDK provided by your chosen platform. Examples:Python (Percy)bashpip install percy-seleniumJavaScript (Percy)bashnpm install @percy/selenium-webdriver3. Capture BaselinesThe first time you run visual tests, the tool captures “baseline” screenshots (expected UI state).Example (Python with Percy)pythonfrom selenium import webdriver
from percy import percy_snapshot
driver = webdriver.Chrome()
driver.get(“https://your-application.com”)
percy_snapshot(driver, “Homepage – Initial State”)
# Perform actions
driver.get(“https://your-application.com/some-other-page”)
percy_snapshot(driver, “Another Page – After Interaction”)
driver.quit()4. Run Tests and CompareIn subsequent runs, the tool compares new screenshots against baselines.5. Review and Approve ChangesDifferences are highlighted in a dashboard.Approve intentional changes (updates baseline).Flag unintended changes as bugs.6. Integrate with CI/CDRun visual tests in pipelines (e.g., GitHub Actions, Jenkins) for continuous feedback.6. Best Practices for Visual Testing1. Strategic SnapshottingFocus on critical UI components (headers, forms, key interactions) rather than capturing every element.Prioritize page layouts and areas prone to visual regressions (e.g., responsive breakpoints).2. Handle Dynamic ContentIgnore/Mask dynamic elements (e.g., ads, timestamps, user-generated content) to avoid false positives.Use tools like Percy’s ignoreRegions or Applitools’ ignoreDisplacements to exclude volatile areas.3. Maintain BaselinesReview baselines regularly and update them only for intentional UI changes.Store baselines in version control (e.g., Git) to track historical changes.4. Cross-Browser & Device TestingTest across multiple browsers (Chrome, Firefox, Safari) and viewport sizes (desktop, tablet, mobile).Leverage cloud platforms (e.g., BrowserStack, Sauce Labs) for broader coverage.5. Configure Thresholds & SensitivityAdjust pixel-matching thresholds to balance between catching bugs and reducing noise.Example: Set a 5% difference threshold for minor anti-aliasing changes.6. Component-Level TestingTest isolated UI components (buttons, modals, cards) for design system consistency.Tools like Storybook + Percy enable visual testing of individual components.Bonus: CI/CD IntegrationRun visual tests automatically in pipelines (GitHub Actions, Jenkins) to catch regressions early.Fail builds on critical visual deviations but allows manual review for minor changes.7. ConclusionVisual testing with Selenium helps ensure UI consistency across releases. While Selenium itself doesn’t support visual comparisons, integrating tools like AShot, OpenCV, or Applitools makes it possible.By following this guide, you can implement automated visual regression testing and catch UI bugs early in development.🚀 Next Steps: Try integrating visual testing into your CI/CD pipeline for seamless validation!Have questions? Drop them in the comments!#Selenium #VisualTesting #Automation #QA
New TeamViewer Vulnerability Puts Windows Systems at Risk of Privilege Escalation
TeamViewer has shared a new security update for a flaw in TeamViewer Remote Management for Windows. The vulnerability, officially cataloged as CVE-2025-36537, allows a local, unprivileged user to esca …
Read more
Published Date:
Jun 25, 2025 (12 hours, 11 minutes ago)
Vulnerabilities has been mentioned in this article.
CVE-2025-36537
CVE-2025-49763
CVE-2025-37093
CVE-2024-42509
CVE-2024-26809
The DistroWatch news feed is brought to you by TUXEDO COMPUTERS. Doug Burks has announced the availability of and updated build of Security Onion, a specialist Linux distribution designed for threat hunting, enterprise security monitoring and log management. The new release, version 2.4.160, comes with several new alert response tools: “Security Onion 2.4.160 is now available and includes Playbooks….
Citrix bleeds again: This time a zero-day exploited – patch now
Hot on the heels of patching a critical bug in Citrix-owned Netscaler ADC and NetScaler Gateway that one security researcher dubbed “CitrixBleed 2,” the embattled networking device vendor today issued …
Read more
Published Date:
Jun 25, 2025 (1 hour, 54 minutes ago)
Vulnerabilities has been mentioned in this article.
CVE-2025-6543
CVE-2025-5777
CVE-2025-31324
CVE-2023-4966
Flaw in Notepad++ installer could grant attackers SYSTEM access (CVE-2025-49144)
A high-severity vulnerability (CVE-2025-49144) in the Notepad++ installer could be exploited by unprivileged users to gain SYSTEM-level privileges through insecure executable search paths.
There is cu …
Read more
Published Date:
Jun 25, 2025 (1 hour, 49 minutes ago)
Vulnerabilities has been mentioned in this article.
CVE-2025-49144
CVE ID : CVE-2025-6627
Published : June 25, 2025, 7:15 p.m. | 1 hour, 59 minutes ago
Description : A vulnerability has been found in TOTOLINK A702R 4.0.0-B20230721.1521 and classified as critical. This vulnerability affects unknown code of the file /boafrm/formIpv6Setup of the component HTTP POST Request Handler. The manipulation of the argument submit-url leads to buffer overflow. The attack can be initiated remotely. The exploit has been disclosed to the public and may be used.
Severity: 8.8 | HIGH
Visit the link for more details, such as CVSS details, affected products, timeline, and more…
CVE ID : CVE-2025-45333
Published : June 25, 2025, 8:15 p.m. | 2 hours, 45 minutes ago
Description : berkeley-abc abc 1.1 contains a Null Pointer Dereference (NPD) vulnerability in the Abc_NtkCecFraigPart function of its data processing module, leading to unpredictable program behavior, causing segmentation faults, and program crashes.
Severity: 0.0 | NA
Visit the link for more details, such as CVSS details, affected products, timeline, and more…
CVE ID : CVE-2025-36038
Published : June 25, 2025, 9:15 p.m. | 1 hour, 45 minutes ago
Description : IBM WebSphere Application Server 8.5 and 9.0 could allow a remote attacker to execute arbitrary code on the system with a specially crafted sequence of serialized objects.
Severity: 9.0 | CRITICAL
Visit the link for more details, such as CVSS details, affected products, timeline, and more…
CVE ID : CVE-2025-6665
Published : June 25, 2025, 9:15 p.m. | 1 hour, 45 minutes ago
Description : A vulnerability has been found in code-projects Inventory Management System 1.0 and classified as critical. Affected by this vulnerability is an unknown functionality of the file /php_action/editBrand.php. The manipulation of the argument editBrandStatus leads to sql injection. The attack can be launched remotely. The exploit has been disclosed to the public and may be used.
Severity: 7.3 | HIGH
Visit the link for more details, such as CVSS details, affected products, timeline, and more…
CVE ID : CVE-2025-6664
Published : June 25, 2025, 9:15 p.m. | 1 hour, 45 minutes ago
Description : A vulnerability, which was classified as problematic, was found in CodeAstro Patient Record Management System 1.0. Affected is an unknown function. The manipulation leads to cross-site request forgery. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used.
Severity: 4.3 | MEDIUM
Visit the link for more details, such as CVSS details, affected products, timeline, and more…
pa is a simple password manager. Encryption support is provided via age. It’s written in portable posix shell. The post…
Multiple Brother Devices Vulnerabilities Open Devices for Hacking
A comprehensive security research investigation has unveiled eight critical vulnerabilities affecting 742 printer and multifunction device models across four major manufacturers.
The discovery, stemmi …
Read more
Published Date:
Jun 25, 2025 (3 hours, 50 minutes ago)
Vulnerabilities has been mentioned in this article.
CVE-2024-51984
CVE-2024-51983
CVE-2024-51982
CVE-2024-51981
CVE-2024-51980
CVE-2024-51979
CVE-2024-51978
CVE-2024-51977