otpwatch handler_api.php recipes
Get API key

Selenium + pytest: SMS codes from a fixture

Selenium suites tend to be long-lived and shared across teams, so the SMS part should be boring: a pytest fixture that orders a number when the test asks for it, an explicit wait for the code field, and teardown that closes every order the test opened.

Get an API key Opens sign-up on SimAggregator, the marketplace this API belongs to. Key in the dashboard, balance in USD.

Setup

This builds on the Python client; copy otp_client.py into your test package. Then:

.env.example
# handler_api reference: https://otpwatch.com/selenium-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/key
SMS_API_KEY=
shell
# handler_api reference: https://otpwatch.com/selenium-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
python -m pip install selenium pytest requests
export SMS_API_KEY=...   # a key used only by this suite

Selenium 4 resolves the browser driver itself through Selenium Manager, so there is no driver download step.

The fixture

conftest.py
# handler_api reference: https://otpwatch.com/selenium-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
import os

import pytest
from selenium import webdriver

from otp_client import SmsClient

SERVICE = os.getenv("SMS_SERVICE", "tg")
COUNTRY = int(os.getenv("SMS_COUNTRY", "16"))
MAX_PRICE = float(os.getenv("SMS_MAX_PRICE", "2"))


@pytest.fixture(scope="session")
def sms_client():
    return SmsClient(os.environ["SMS_API_KEY"])


@pytest.fixture
def sms(sms_client):
    """Call sms() inside the test, right before the app sends the code."""
    opened = []

    def order(service=SERVICE, country=COUNTRY, max_price=MAX_PRICE):
        act = sms_client.order(service, country, max_price=max_price)
        opened.append(act)
        return act

    yield order
    for act in opened:            # runs after failures too
        act.close()               # setStatus 6 if a code was read, else cancel


@pytest.fixture
def driver():
    opts = webdriver.ChromeOptions()
    if os.getenv("CI"):
        opts.add_argument("--headless=new")
    d = webdriver.Chrome(options=opts)
    yield d
    d.quit()

The test

test_phone_signup.py
# handler_api reference: https://otpwatch.com/selenium-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
import os

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

BASE_URL = os.getenv("BASE_URL", "http://localhost:3000")


@pytest.mark.sms
def test_new_user_verifies_phone(driver, sms):
    wait = WebDriverWait(driver, 20)
    driver.get(f"{BASE_URL}/signup")
    wait.until(EC.element_to_be_clickable((By.NAME, "email"))).send_keys("[email protected]")

    act = sms()                                   # order now, the form is ready
    driver.find_element(By.NAME, "phone").send_keys(act.e164)
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

    code_field = wait.until(EC.visibility_of_element_located((By.NAME, "code")))
    code_field.send_keys(act.wait_code(timeout=180))

    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
    wait.until(EC.text_to_be_present_in_element((By.TAG_NAME, "h1"), "Welcome"))

Register the marker so pytest -m sms selects only paid tests and -m "not sms" skips them:

pytest.ini
# handler_api reference: https://otpwatch.com/selenium-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
[pytest]
markers =
    sms: uses a real phone number and costs money

Things that break Selenium SMS tests

  • Ordering in a session fixture. The activation window starts at getNumber. A session-scoped number shared by twenty tests closes before the last one needs it, and a failed test in the middle leaves the next one with a code meant for someone else. One test, one order.
  • Implicit waits plus polling. driver.implicitly_wait and the 3-second getStatus loop stack up. Use explicit WebDriverWait for elements and let wait_code handle the SMS.
  • Grid parallelism. pytest -n 8 with xdist means eight orders and eight polling loops on one key. Run the sms marker with -n 2, everything else as wide as you like.
  • The code as a number. send_keys(int(code)) drops leading zeros. wait_code returns a string; keep it that way.
  • Service code mismatch. The order only receives SMS from the service it names. The code has to match the sender of the SMS in your flow; see service codes.

Java or C# Selenium

The pattern carries over: a per-test resource that orders on demand and closes in teardown. In C#, the .NET client's Activation is IAsyncDisposable, so await using var act = await sms.OrderAsync(...) inside an NUnit or xUnit test gives you the same cleanup. In Java, implement AutoCloseable and use try-with-resources.

Running it on CI

CI=1 pytest -m sms -n 2 with the key in a secret. The CI page has a full GitHub Actions workflow with a balance check before the run and a cleanup step after it.

ready to run it?

Put otp_client.py next to conftest.py and add the sms fixture.

Get an API key

Install for your coding agent

terminal
# Agent skills index: https://otpwatch.com/.well-known/agent-skills/index.json
npx skills add https://otpwatch.com

Two skills: receiving an SMS code in your own app or test, and building a bot that sells numbers. Index: /.well-known/agent-skills/index.json

Updated