Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 35 ยท Projects

Project: Login Test Suite

Build a login test suite step by step: valid and invalid credentials, error messages, lockout, a page object and data-driven cases, with a runnable stand-in app.

Login is the first thing almost every team automates, and it is a perfect first project: a small page, clear rules, and lots of ways to go wrong. In this project you will design a suite for a login form. You will decide which cases to cover, put the page details in a page object, and drive many scenarios from a table of data.

Because this site cannot launch a browser, the project has two parts. The real Selenium code (Python with pytest) is shown in read-only blocks, ready to copy to your machine. A stand-in runs in the page: a tiny login app, a miniature driver with the same method names, a page object, and a runner. The stand-in is not Selenium, but the design (cases, page object, data table, isolation) is exactly the same.

What a login suite should cover

Happy path Valid credentials reach the account page.
Bad input Wrong password, unknown user, empty fields.
Lockout Repeated failures lock the account.
No leaks Errors must not reveal which part was wrong.

Four groups of cases, one small page object.

1 / 2

The application under test

The stand-in app follows rules you will find in many real systems:

  • Two accounts exist: alice and bob.
  • An empty username or password shows a "required" message.
  • A wrong password, or an unknown user, shows the same message ("Invalid username or password."). Different messages would let an attacker discover which user names exist.
  • After three failed attempts for a user, the account is locked, even for the correct password.

Before you write tests, explore the app by hand. That is the first step of any real project too.

JS Explore the login stand-in app

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the "wrong password" and "unknown user" results carry the identical message. That is a requirement worth testing, not a coincidence. Exploring like this also gives you the list of cases for the plan below.

The test plan

Write the plan before the code. For login, a good first table looks like this:

Case Username Password Expected
Valid login alice Wonder#1 Account page for alice
Wrong password alice nope "Invalid username or password."
Unknown user nobody Wonder#1 The same invalid message
Empty username (empty) Wonder#1 "Username is required."
Empty password alice (empty) "Password is required."
Lockout bob, three wrong tries, then the right password "Account locked. Try again later."

Each row is independent: it starts from a fresh app (or a fresh browser session) and does not rely on another row having run first. Independence is what lets you run the suite in parallel, as described in Running in CI.

The page object

Tests should talk about what the user does, not about locators. Put the locators and the low-level steps in a page object, as covered in The Page Object Model. Here is the real Selenium version in Python.

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


class LoginPage:
    USERNAME = (By.ID, "username")
    PASSWORD = (By.ID, "password")
    SUBMIT = (By.CSS_SELECTOR, "button[type='submit']")
    ERROR = (By.CSS_SELECTOR, "[data-testid='login-error']")
    WELCOME = (By.CSS_SELECTOR, "[data-testid='welcome']")

    def __init__(self, driver, base_url):
        self.driver = driver
        self.base_url = base_url
        self.wait = WebDriverWait(driver, 10)

    def open(self):
        self.driver.get(f"{self.base_url}/login")
        return self

    def log_in(self, username, password):
        user_field = self.driver.find_element(*self.USERNAME)
        pass_field = self.driver.find_element(*self.PASSWORD)
        user_field.clear()
        user_field.send_keys(username)
        pass_field.clear()
        pass_field.send_keys(password)
        self.driver.find_element(*self.SUBMIT).click()
        return self

    def error_message(self):
        return self.wait.until(EC.visibility_of_element_located(self.ERROR)).text

    def welcome_text(self):
        return self.wait.until(EC.visibility_of_element_located(self.WELCOME)).text

Notice three design choices. Locators are class constants, so a markup change means one edit. log_in returns self, which lets a test chain calls. And the read methods use an explicit wait (see Implicit, Explicit and Fluent Waits), because the message appears after a request, not instantly. Test ids (data-testid) are used for messages because they survive redesigns; see Choosing Stable Locators.

Data-driven tests with pytest

With pytest, the table above becomes data, and one test function runs once per row. The driver comes from a fixture (see Selenium with pytest), and credentials come from the environment (see Security, Ethics and Scraping Limits).

Python
import os
import pytest

BASE_URL = os.environ["BASE_URL"]
GOOD_PASSWORD = os.environ["ALICE_PASSWORD"]

INVALID = "Invalid username or password."

CASES = [
    pytest.param("alice", "nope", INVALID, id="wrong-password"),
    pytest.param("nobody", GOOD_PASSWORD, INVALID, id="unknown-user"),
    pytest.param("", GOOD_PASSWORD, "Username is required.", id="empty-username"),
    pytest.param("alice", "", "Password is required.", id="empty-password"),
]


def test_valid_login(driver):
    page = LoginPage(driver, BASE_URL).open().log_in("alice", GOOD_PASSWORD)
    assert "alice" in page.welcome_text()


@pytest.mark.parametrize("username, password, expected", CASES)
def test_rejected_logins(driver, username, password, expected):
    page = LoginPage(driver, BASE_URL).open().log_in(username, password)
    assert page.error_message() == expected

The id= values appear in the report (test_rejected_logins[unknown-user]), so a failure names the scenario instead of a number. The lockout test is better written separately, because it needs a user that no other test touches, otherwise it would lock the account for everyone else.

Build the suite in the stand-in

Now the whole thing runs below: the app, a mini driver with Selenium-like names (find, send_keys, click, text, is_displayed), the page object, a data table, and a tiny runner that prints a report. It uses a fresh app for every test, which is the isolation rule in action.

JS Login suite: page object plus data-driven cases

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All eight tests pass. Try breaking the app on purpose: change >= 3 to >= 5 in the lockout rule and run again. The lockout test fails with a message that shows both the expected and the actual value, which is the kind of failure report you want from a real suite. You can also change the unknown-user message to "No such user." and watch the unknown-user case fail; that is how a test protects a security requirement.

In the real suite the same structure applies: createApp becomes the deployed test environment, createDriver becomes Selenium's webdriver.Chrome, and has becomes either find_elements (which returns an empty list instead of raising) or a try/except NoSuchElementException.

Extending the project

Once the core suite is green, add these in order:

  1. Keyboard login. Submit with the Enter key (send_keys(Keys.ENTER) on the password field) as a second path; see Clicking and Typing.
  2. Logout and session. After logging in, a logout must return to the login page, and the back button must not show the account page again.
  3. Remember me / redirects. If a protected URL redirects to login, a successful login should return the user there.
  4. Failure artifacts. Save a screenshot when a test fails, as shown in Reporting and Logging.
  5. API setup. Create and lock accounts through an API instead of the UI to keep tests fast and independent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do the wrong-password and unknown-user cases expect the same message?

    Different messages would reveal whether an account exists. Testing for identical messages protects that security requirement.
  2. 2. Why does every test in the stand-in start with a fresh app?

    Independent tests can run in any order and in parallel. Shared state, such as a locked account, causes failures that look random.
  3. 3. What is the main benefit of putting locators in a LoginPage class?

    A page object centralizes locators and low-level steps, so tests describe behavior and survive layout changes with minimal edits.
  4. 4. Why use pytest.param(..., id="unknown-user") in a parametrized test?

    The id becomes part of the test name in the output, which makes a failing case immediately recognizable.

Summary

  • Plan the cases first: happy path, bad input, lockout, and message hygiene (no hints about which part was wrong).
  • Put locators and low-level steps in a page object; let tests read like user actions.
  • Drive similar cases from a data table (pytest.mark.parametrize) and give each case a readable id.
  • Keep tests independent: fresh state per test, separate users for destructive cases such as lockout.
  • Read credentials from the environment and use explicit waits for messages that appear after a request.
  • The stand-in mirrors the structure of a real suite but is not Selenium; the real code is in the read-only blocks.

Next, extend these ideas to a multi-step flow in Project: Shopping Cart Checkout.