# 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.

Source: https://otpwatch.com/selenium-otp-testing
Updated: 2026-11-24
API key: https://otpwatch.com/agent/key

## Setup

This builds on the [Python client](https://otpwatch.com/python.md); copy `otp_client.py` into your test package. Then:

```env title=".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/agent/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/agent/key
SMS_API_KEY=
```

```bash title="shell"
# handler_api reference: https://otpwatch.com/selenium-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/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

```python title="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/agent/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

```python title="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/agent/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("qa+selenium@example.com")

    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:

```ini title="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/agent/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](https://otpwatch.com/service-codes.md).

## 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](https://otpwatch.com/csharp.md)'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](https://otpwatch.com/ci-sms-verification.md) has a full GitHub Actions workflow with a balance check before the run and a cleanup step after it.
