As equipes de teste precisam verificar regularmente os fluxos protegidos por CAPTCHA. CaptchaAI permite automatizar esses testes sem interação manual com CAPTCHA.
Quando as equipes de controle de qualidade precisam de solução CAPTCHA
| Cenário | Por que CaptchaAI ajuda |
|---|---|
| Teste de regressão | Verifique se os formulários ainda funcionam após a implantação |
| Teste de ponta a ponta | Teste jornadas completas do usuário |
| Teste de carga | Simule fluxos CAPTCHA realistas em escala |
| Teste entre navegadores | Valide renderizações CAPTCHA em navegadores |
| Teste de acessibilidade | Teste fluxos alternativos para usuários com deficiência |
Integração Pytest
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.staging.example.com/qa-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)
Padrão de teste Selênio E2E
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()
Configuração de teste
# 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)",
]
"""
Execute apenas testes CAPTCHA:
pytest -m captcha -v
Execute sem testes CAPTCHA (pipeline rápido):
pytest -m "not captcha" -v
Dicas de teste econômicas
| Estratégia | Benefício |
|---|---|
| Usar ambiente de teste | Diminuir dificuldade CAPTCHA |
| Execute testes CAPTCHA dentro do cronograma, não em cada push | Reduza os custos de API |
| Resultados de teste de cache para testes instáveis | Evite resoluções desnecessárias |
| Use sinalizador de ambiente para ignorar CAPTCHAs localmente | Economize custos durante o desenvolvimento |
| Testes CAPTCHA em lote em trabalho de CI dedicado | Controle os custos por pipeline |
Perguntas frequentes
Quanto custa para executar testes CAPTCHA?
Cada solução reCAPTCHA v2 custa aproximadamente US$ 0,003. Um conjunto de testes com 50 testes CAPTCHA custa aproximadamente US$ 0,15 por execução. Custos diários de funcionamento ~$4,50/month.
Devo resolver CAPTCHAs em testes unitários?
Não. Simule respostas CAPTCHA em testes unitários. Resolva apenas CAPTCHAs reais em integração e testes E2E em ambientes reais.
Posso usar CaptchaAI com outras estruturas de teste?
Sim. CaptchaAI é baseado em HTTP, portanto funciona com qualquer estrutura de teste em qualquer linguagem – Jest, Mocha, JUnit, NUnit, etc.
Guias Relacionados
Automatize seu pipeline de controle de qualidade -adicione CaptchaAI aos seus testes.