How to test SMS 2FA in Selenium with Python

· 5 min read · QuickInbox team

  • Selenium
  • Python
  • SMS

Two-factor login by SMS is where many Selenium suites give up and add a "skip 2FA" switch. You don't have to: read the code from a real test number instead.

Step 1: the helper

Install requests and selenium, put your API key in QI_KEY, and add:

# sms.py - read texts sent to your QuickInbox test number
import os, re, time, requests

BASE = "https://business.quickinbox.net"
HEADERS = {"X-API-Key": os.environ["QI_KEY"]}

def get_number():
    numbers = requests.get(f"{BASE}/api/business/sms/numbers", headers=HEADERS).json()["numbers"]
    return numbers[0]  # {"id": ..., "phone_number": "+1...", ...}

def list_messages(number_id):
    r = requests.get(f"{BASE}/api/business/sms/numbers/{number_id}/messages", headers=HEADERS)
    r.raise_for_status()
    return r.json()["messages"]  # newest first

def snapshot(number_id):
    return {m["id"] for m in list_messages(number_id)}

def wait_for_code(number_id, seen, timeout=90, pattern=r"\b(\d{4,8})\b"):
    deadline = time.time() + timeout
    while time.time() < deadline:
        for m in list_messages(number_id):
            if m["id"] not in seen and re.search(pattern, m["body"]):
                return re.search(pattern, m["body"]).group(1)
        time.sleep(3)
    raise TimeoutError("No new SMS code arrived in time")

The snapshot step matters: a test number keeps its older texts, so the test records which messages already exist before it asks for a code, then waits only for a new one. That way an old code can never pass the test by accident.

Step 2: the test

This assumes a test user whose 2FA phone is your QuickInbox number.

# test_login_2fa.py
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
import sms

def test_login_with_sms_code():
    number = sms.get_number()
    seen = sms.snapshot(number["id"])

    driver = webdriver.Chrome()
    try:
        driver.get("https://staging.example.com/login")
        driver.find_element(By.NAME, "email").send_keys("qa-user@example.com")
        driver.find_element(By.NAME, "password").send_keys("Correct-Horse-42")
        driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

        code = sms.wait_for_code(number["id"], seen)
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "code"))).send_keys(code)
        driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

        WebDriverWait(driver, 10).until(EC.url_contains("/dashboard"))
    finally:
        driver.quit()

Tips

  • Keep the test user's password in your CI secrets, not in the file.
  • Run 2FA tests one at a time if they share a number (pytest -p no:xdist or a separate job).
  • Email 2FA as well? See email verification in Selenium.

Related guides

Get a test number: every paid QuickInbox plan includes a real US phone number and a monthly SMS allowance, with plans from $9 a month. Extra packs start at $5 a month. See SMS testing and pricing.

← All articles