Use Cases

CAPTCHA Solving for QA and Authorized Testing

Testing teams need to verify CAPTCHA-protected flows regularly. CaptchaAI lets you automate these tests without manual CAPTCHA interaction.


When QA Teams Need CAPTCHA Solving

Scenario Why CaptchaAI Helps
Regression testing Verify forms still work after deploys
End-to-end testing Test complete user journeys
Load testing Simulate realistic CAPTCHA flows at scale
Cross-browser testing Validate CAPTCHA renders across browsers
Accessibility testing Test alternative flows for disabled users

Pytest Integration

import pytest
import requests
import time


class CaptchaTestHelper:
    """Helper for solving CAPTCHAs in test environments."""

    def __init__(self, api_key):
        self.api_key = api_key

    def solve_recaptcha(self, sitekey, pageurl, timeout=120):
        """Solve reCAPTCHA and return token."""
        resp = requests.post("https://ocr.captchaai.com/in.php", data={
            "key": self.api_key,
            "method": "userrecaptcha",
            "googlekey": sitekey,
            "pageurl": pageurl,
            "json": 1,
        }, timeout=30)
        result = resp.json()
        assert result.get("status") == 1, f"Submit failed: {result}"
        task_id = result["request"]

        deadline = time.time() + timeout
        time.sleep(10)

        while time.time() < deadline:
            resp = requests.get("https://ocr.captchaai.com/res.php", params={
                "key": self.api_key, "action": "get",
                "id": task_id, "json": 1,
            }, timeout=15)
            data = resp.json()

            if data.get("status") == 1:
                return data["request"]
            if data["request"] != "CAPCHA_NOT_READY":
                raise RuntimeError(f"Solve error: {data['request']}")
            time.sleep(5)

        raise TimeoutError("CAPTCHA solve timeout")


@pytest.fixture(scope="session")
def captcha_helper():
    """Provide CaptchaAI helper for test session."""
    import os
    api_key = os.environ.get("CAPTCHAAI_API_KEY")
    if not api_key:
        pytest.skip("CAPTCHAAI_API_KEY not set")
    return CaptchaTestHelper(api_key)


class TestLoginFlow:
    """Test login flow behind reCAPTCHA."""

    SITEKEY = "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-"
    LOGIN_URL = "https://staging.example.com/login"

    def test_login_with_valid_credentials(self, captcha_helper):
        """Verify login succeeds with valid creds and solved CAPTCHA."""
        token = captcha_helper.solve_recaptcha(self.SITEKEY, self.LOGIN_URL)
        assert token and len(token) > 100

        resp = requests.post(self.LOGIN_URL, data={
            "username": "test_user",
            "password": "test_pass",
            "g-recaptcha-response": token,
        })
        assert resp.status_code == 200
        assert "Welcome" in resp.text

    def test_login_with_invalid_credentials(self, captcha_helper):
        """Verify login fails gracefully with bad creds but valid CAPTCHA."""
        token = captcha_helper.solve_recaptcha(self.SITEKEY, self.LOGIN_URL)

        resp = requests.post(self.LOGIN_URL, data={
            "username": "wrong_user",
            "password": "wrong_pass",
            "g-recaptcha-response": token,
        })
        assert resp.status_code in (200, 401)
        assert "Invalid" in resp.text or "error" in resp.text.lower()

    def test_login_without_captcha_fails(self):
        """Verify login rejects submissions without CAPTCHA."""
        resp = requests.post(self.LOGIN_URL, data={
            "username": "test_user",
            "password": "test_pass",
        })
        assert resp.status_code in (400, 403, 422)

Selenium E2E Test Pattern

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


@pytest.fixture
def browser():
    """Create browser for testing."""
    options = webdriver.ChromeOptions()
    options.add_argument("--window-size=1920,1080")
    driver = webdriver.Chrome(options=options)
    yield driver
    driver.quit()


class TestRegistrationFlow:
    """Test registration form with CAPTCHA."""

    REG_URL = "https://staging.example.com/register"

    def test_registration_form_submits(self, browser, captcha_helper):
        """Full registration flow with CAPTCHA solving."""
        browser.get(self.REG_URL)

        # Fill form
        browser.find_element(By.ID, "email").send_keys("test@example.com")
        browser.find_element(By.ID, "password").send_keys("SecurePass123!")
        browser.find_element(By.ID, "confirm_password").send_keys("SecurePass123!")

        # Extract sitekey from page
        captcha_div = browser.find_element(By.CSS_SELECTOR, ".g-recaptcha")
        sitekey = captcha_div.get_attribute("data-sitekey")

        # Solve via API
        token = captcha_helper.solve_recaptcha(sitekey, browser.current_url)

        # Inject token
        browser.execute_script("""
            document.querySelector('[name="g-recaptcha-response"]').value = arguments[0];
        """, token)

        # Trigger callback if needed
        callback = captcha_div.get_attribute("data-callback")
        if callback:
            browser.execute_script(f"window['{callback}'](arguments[0]);", token)

        # Submit
        browser.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

        # Verify success
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, ".success-message"))
        )

    def test_captcha_renders_on_page(self, browser):
        """Verify CAPTCHA widget loads on registration page."""
        browser.get(self.REG_URL)
        captcha = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, ".g-recaptcha, iframe[src*='recaptcha']"))
        )
        assert captcha.is_displayed()

Test Configuration

# conftest.py
import os

# Mark tests that need CAPTCHA solving
def pytest_configure(config):
    config.addinivalue_line(
        "markers", "captcha: tests requiring CAPTCHA solving (may be slow)"
    )


# pytest.ini or pyproject.toml
"""
[tool.pytest.ini_options]
markers = [
    "captcha: tests requiring CAPTCHA solving (may be slow)",
]
"""

Run only CAPTCHA tests:

pytest -m captcha -v

Run without CAPTCHA tests (fast pipeline):

pytest -m "not captcha" -v

Cost-Effective Testing Tips

Strategy Benefit
Use staging environment Lower CAPTCHA difficulty
Run CAPTCHA tests on schedule, not every push Reduce API costs
Cache test results for flaky tests Avoid unnecessary re-solves
Use environment flag to skip CAPTCHAs locally Save costs during development
Batch CAPTCHA tests in dedicated CI job Control costs per pipeline

FAQ

How much does it cost to run CAPTCHA tests?

Each reCAPTCHA v2 solve costs ~$0.003. A test suite with 50 CAPTCHA tests costs ~$0.15 per run. Running daily costs ~$4.50/month.

Should I solve CAPTCHAs in unit tests?

No. Mock CAPTCHA responses in unit tests. Only solve real CAPTCHAs in integration and E2E tests against real environments.

Can I use CaptchaAI with other test frameworks?

Yes. CaptchaAI is HTTP-based, so it works with any test framework in any language — Jest, Mocha, JUnit, NUnit, etc.



Automate your QA pipeline — add CaptchaAI to your tests.

Discussions (0)

No comments yet.

Related Posts

Tutorials Pytest Fixtures for CaptchaAI API Testing
Build reusable pytest fixtures to test CAPTCHA-solving workflows with Captcha AI.

Build reusable pytest fixtures to test CAPTCHA-solving workflows with Captcha AI. Covers mocking, live integra...

Automation Python reCAPTCHA v2
Apr 08, 2026
Tutorials Build an Automated Testing Pipeline with CaptchaAI
Build a CI/CD testing pipeline that uses Captcha AI to handle CAPTCHAs in end-to-end tests.

Build a CI/CD testing pipeline that uses Captcha AI to handle CAPTCHAs in end-to-end tests. Covers pytest inte...

Automation Python reCAPTCHA v2
Jan 16, 2026
Use Cases Automated Form Submission with CAPTCHA Handling
Complete guide to automating web form submissions that include CAPTCHA challenges — re CAPTCHA, Turnstile, and image CAPTCHAs with Captcha AI.

Complete guide to automating web form submissions that include CAPTCHA challenges — re CAPTCHA, Turnstile, and...

Python reCAPTCHA v2 Cloudflare Turnstile
Mar 21, 2026
Integrations Android CAPTCHA Testing with Espresso and CaptchaAI
Handle re CAPTCHA v 2 CAPTCHAs in Android Espresso UI tests by evaluating Java Script in Web Views, solving with Captcha AI API, and injecting tokens programmat...

Handle re CAPTCHA v 2 CAPTCHAs in Android Espresso UI tests by evaluating Java Script in Web Views, solving wi...

Python reCAPTCHA v2 Testing
Mar 02, 2026
Use Cases CAPTCHA Handling in Continuous Integration Testing
Integrate CAPTCHA solving into CI/CD pipelines — run end-to-end tests against CAPTCHA-protected pages in Git Hub Actions, Git Lab CI, and Jenkins with Captcha A...

Integrate CAPTCHA solving into CI/CD pipelines — run end-to-end tests against CAPTCHA-protected pages in Git H...

Python reCAPTCHA v2 Cloudflare Turnstile
Mar 28, 2026
Use Cases Multi-Step Checkout Automation with CAPTCHA Solving
Automate multi-step e-commerce checkout flows that include CAPTCHA challenges at cart, payment, or confirmation stages using Captcha AI.

Automate multi-step e-commerce checkout flows that include CAPTCHA challenges at cart, payment, or confirmatio...

Automation Python reCAPTCHA v2
Mar 21, 2026
Use Cases CAPTCHA Handling in Registration Flow Testing
Automate registration flow testing with CAPTCHA handling — verify sign-up forms, email validation, and account creation across environments with Captcha AI.

Automate registration flow testing with CAPTCHA handling — verify sign-up forms, email validation, and account...

Python reCAPTCHA v2 Cloudflare Turnstile
Mar 18, 2026
Integrations Selenium Wire + CaptchaAI: Request Interception for CAPTCHA Solving
Complete guide to using Selenium Wire for request interception, proxy routing, and automated CAPTCHA solving with Captcha AI in Python.

Complete guide to using Selenium Wire for request interception, proxy routing, and automated CAPTCHA solving w...

Python reCAPTCHA v2 Cloudflare Turnstile
Mar 13, 2026
Use Cases CAPTCHA Handling for University Course Registration Testing
Handle re CAPTCHA v 2 CAPTCHAs when testing university course registration systems — QA testing enrollment workflows, seat availability checks, and registration...

Handle re CAPTCHA v 2 CAPTCHAs when testing university course registration systems — QA testing enrollment wor...

Python reCAPTCHA v2 Testing
Mar 11, 2026
Use Cases CAPTCHA Solving for API Endpoint Testing in Web Forms
Test CAPTCHA-protected API endpoints and web forms programmatically — validate backend behavior, error responses, and rate limits without manual CAPTCHA solving...

Test CAPTCHA-protected API endpoints and web forms programmatically — validate backend behavior, error respons...

Python reCAPTCHA v2 Cloudflare Turnstile
Mar 03, 2026
Use Cases Retail Site Data Collection with CAPTCHA Handling
Amazon uses image CAPTCHAs to block automated access.

Amazon uses image CAPTCHAs to block automated access. When you hit their anti-bot threshold, you'll see a page...

Web Scraping Image OCR
Apr 07, 2026
Use Cases Multi-Step Workflow Automation with CaptchaAI
Manage workflows across multiple accounts on CAPTCHA-protected platforms — , action, and data collection at scale.

Manage workflows across multiple accounts on CAPTCHA-protected platforms — , action, and data collection at sc...

Automation Python reCAPTCHA v2
Apr 06, 2026
Use Cases Selenium CAPTCHA Handling with Python and CaptchaAI
Selenium automates browser interactions, but CAPTCHAs stop it cold.

Selenium automates browser interactions, but CAPTCHAs stop it cold. Captcha AI's API solves CAPTCHAs externall...

Python Cloudflare Turnstile Web Scraping
Jan 12, 2026