Robot Framework email verification tests
Robot Framework tests that sign up a user need the code or link from the verification email. This guide gives you a small Python keyword library, AssertInboxLibrary.py, with five keywords: New Test Address, Wait For Email, Wait For Otp, Wait For Link and Delete Test Emails. A .robot suite with SeleniumLibrary uses them to fill in a sign-up form with a unique address, wait for the email through one HTTP call, and finish the verification.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, with otp, magic_link and links already extracted. Messages are deleted after 24 hours.
Get an API key
Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is the namespace. If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are listed in the limits page.
Install
pip install robotframework robotframework-seleniumlibrary
The keyword library
Save this next to your suite as AssertInboxLibrary.py. It uses only the Python standard library and the Robot Framework API that is already installed. Keywords are named with the @keyword decorator, so the names in your suite read as plain English. The library reads the key and namespace from the environment, so no secret appears in a test file.
"""AssertInboxLibrary: Robot Framework keywords for AssertInbox. Python standard library only."""
import json
import os
import random
import string
import time
import urllib.error
import urllib.parse
import urllib.request
from robot.api.deco import keyword, library
API = "https://assertinbox.com"
@library(scope="GLOBAL", auto_keywords=False)
class AssertInboxLibrary:
def __init__(self, key=None, namespace=None):
self.key = key or os.environ["ASSERTINBOX_KEY"]
self.namespace = namespace or os.environ["ASSERTINBOX_NAMESPACE"]
def _call(self, path, params, method="GET"):
query = urllib.parse.urlencode({k: v for k, v in params.items() if v})
req = urllib.request.Request(
API + path + "?" + query,
method=method,
headers={"Authorization": "Bearer " + self.key, "User-Agent": "assertinbox-robot/1.0"},
)
try:
with urllib.request.urlopen(req, timeout=40) as res:
return res.status, json.loads(res.read().decode("utf-8"))
except urllib.error.HTTPError as e:
return e.code, {}
@keyword("New Test Address")
def new_test_address(self, prefix="robot"):
"""Returns a unique tag and the address built from it, as a two-item list."""
rnd = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
tag = ("%s-%d-%s" % (prefix, int(time.time() * 1000), rnd)).lower()
return [tag, "%s.%s@assertinbox.com" % (self.namespace, tag)]
@keyword("Wait For Email")
def wait_for_email(self, tag, after=None, subject=None):
"""Returns the newest matching message as a dictionary. Retries 408 timeouts three times."""
for _ in range(3):
status, body = self._call(
"/v1/wait", {"tag": tag, "timeout": 25, "after": after, "subject": subject}
)
if status == 200:
return body
if status != 408:
raise AssertionError("AssertInbox returned HTTP %d" % status)
raise AssertionError("No email arrived for tag " + tag)
@keyword("Wait For Otp")
def wait_for_otp(self, tag, after=None):
mail = self.wait_for_email(tag, after)
if not mail.get("otp"):
raise AssertionError("No code found in: " + str(mail.get("subject")))
return mail["otp"]
@keyword("Wait For Link")
def wait_for_link(self, tag, after=None):
mail = self.wait_for_email(tag, after)
if not mail.get("magic_link"):
raise AssertionError("No link found in: " + str(mail.get("subject")))
return mail["magic_link"]
@keyword("Delete Test Emails")
def delete_test_emails(self, tag):
self._call("/v1/messages", {"tag": tag}, method="DELETE")
The suite
Save this as signup.robot. Replace the locators and the success text with those of your app. The setup keyword makes a new address for every test case, so cases never read each other's mail, and the teardown deletes the test's emails and closes the browser even when the test fails. Whitespace matters in Robot files: keep at least two spaces between a keyword and its arguments.
*** Settings ***
Documentation Sign-up email verification with the AssertInbox keyword library.
Library SeleniumLibrary
Library AssertInboxLibrary.py
Test Setup Start Sign Up
Test Teardown Run Keywords Delete Test Emails ${TAG} AND Close All Browsers
*** Variables ***
${APP_URL} http://localhost:3000
${BROWSER} headlesschrome
*** Test Cases ***
Sign Up Is Verified With The Code From The Email
${otp}= Wait For Otp ${TAG}
Input Text name:code ${otp}
Click Button css:button[type=submit]
Wait Until Page Contains Email verified timeout=15s
Sign Up Is Verified With The Magic Link
${link}= Wait For Link ${TAG}
Go To ${link}
Wait Until Page Contains Email verified timeout=15s
Resend Sends A New Code
${first}= Wait For Email ${TAG}
Click Button id:resend
${second}= Wait For Email ${TAG} after=${first}[id]
Should Not Be Equal ${second}[id] ${first}[id]
*** Keywords ***
Start Sign Up
${tag} ${email}= New Test Address robot
Set Test Variable ${TAG} ${tag}
Open Browser ${APP_URL}/signup ${BROWSER}
Input Text name:email ${email}
Click Button css:button[type=submit]
Run it with robot signup.robot. Robot Framework runs cases in one process in order. To run several suites at once, use pabot; the unique tags keep parallel runs apart.
Waiting for the page and for the email
Keywords such as Wait Until Page Contains poll the page until text appears. Wait For Email is a different kind of wait: it is one request that the server holds open until a matching message arrives, so it returns as soon as the email does. Wait for the email first, then for the field you need to type into.
Using the Browser library instead
The keywords do not depend on the browser library. With the Browser library, replace the SeleniumLibrary keywords in the suite with New Page, Fill Text and Click, and keep the AssertInbox keywords as they are. The email part runs in the Python process, not in the browser.
When the app sends a second email
A resend button sends another message to the same address, and the wait returns the newest one for the tag, which might still be the first. The third test case shows the fix: pass the id of the message you already read as after. The same keyword accepts subject when your app sends several kinds of email to one address.
Troubleshooting
- No keyword with name 'Wait For Otp' found. The library file is not next to the suite or not named in
Library. Give a path if it lives elsewhere. - KeyError: ASSERTINBOX_KEY. The variable is missing in the environment that starts Robot Framework.
- No email arrived. The app did not send the email or sent it to another address. Log the address and compare it with your app's logs.
- HTTP 401. The key is wrong. HTTP 429. The key used its 2,000 requests for the day; the
Retry-Afterheader gives the seconds until 00:00 UTC. - Syntax errors in the suite. Use at least two spaces, or a tab, between a keyword and each argument.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.