Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: A Shopping Cart Suite with Gestures, Data and a Device Matrix

Extend your Appium suite to a shopping cart: scrolling lists, swipe to delete, API test data, price checks, a cross-platform screen layer and a CI device matrix.

The second project grows the suite from one screen to a real journey: browse products, add them to a cart, change quantities, remove an item with a swipe, and check the totals. It adds what a login suite does not need: scrolling, gestures, money arithmetic, test data created through an API, a screen layer that works on Android and iOS, and a device matrix in CI.

Appium and devices cannot run on this site, so the Appium code is read-only. The runnable parts simulate the cart and check price calculations, which is where many real bugs live.

The app and the scenarios

The imaginary Shop app has a product list (name, price in cents), a product detail screen with an Add to cart button, and a cart screen with quantity steppers, a swipe-to-delete gesture, a coupon field and a total. Accessibility IDs: product-<sku> for list rows, add-to-cart, cart-tab, cart-row-<sku>, qty-plus-<sku>, qty-minus-<sku>, delete-<sku>, coupon, apply-coupon, cart-total.

Scenarios:

  1. Add one product, see it in the cart with the right total.
  2. Add the same product twice; quantity becomes 2 and the total doubles.
  3. Remove an item by swiping it away; the total updates.
  4. Apply coupon SAVE10 (10 percent off); an invalid coupon shows an error.
  5. A product far down a long list can still be found by scrolling.
  6. The cart survives sending the app to the background.

Test data through an API

Do not build the cart by tapping products in every test. Seed it by API, then use the UI for what you actually test:

Python
# api.py
import os, requests

BASE = os.environ["API_BASE"]          # the test backend, never production


def create_user():
    r = requests.post(f"{BASE}/test/users", json={}, timeout=10)
    r.raise_for_status()
    return r.json()                     # {"email": ..., "password": ..., "token": ...}


def seed_cart(token, items):
    headers = {"Authorization": f"Bearer {token}"}
    for sku, qty in items.items():
        requests.post(f"{BASE}/cart/items", json={"sku": sku, "qty": qty},
                      headers=headers, timeout=10).raise_for_status()

The endpoints are made up for this project; your team provides the real ones (or a test-only endpoint). A fixture combines them:

Python
@pytest.fixture
def user_with_cart(request):
    user = api.create_user()
    api.seed_cart(user["token"], getattr(request, "param", {"sku-sneaker": 1}))
    return user

Gestures

Scrolling and swiping are done with mobile: gesture commands, which are more reliable than raw touch sequences.

Python
# Android: scroll until an element is visible (UiScrollable), the simplest option
driver.find_element(
    AppiumBy.ANDROID_UIAUTOMATOR,
    'new UiScrollable(new UiSelector().scrollable(true).instance(0))'
    '.scrollIntoView(new UiSelector().description("product-sku-077"))',
)

# Android: swipe a row left to delete
row = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "cart-row-sku-sneaker")
driver.execute_script("mobile: swipeGesture", {
    "elementId": row.id, "direction": "left", "percent": 0.75,
})

# iOS: scroll and swipe
driver.execute_script("mobile: scroll", {"direction": "down", "predicateString": 'name == "product-sku-077"'})
driver.execute_script("mobile: swipe", {"elementId": row.id, "direction": "left"})

Wrap the difference in one screen method so tests only say cart.swipe_to_delete("sku-sneaker"):

Python
class CartScreen:
    def swipe_to_delete(self, sku):
        row = self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, f"cart-row-{sku}")
        if self.platform == "android":
            self.driver.execute_script("mobile: swipeGesture",
                {"elementId": row.id, "direction": "left", "percent": 0.75})
        else:
            self.driver.execute_script("mobile: swipe",
                {"elementId": row.id, "direction": "left"})
        WebDriverWait(self.driver, 10).until(EC.invisibility_of_element_located(
            (AppiumBy.ACCESSIBILITY_ID, f"cart-row-{sku}")))

After the gesture the method waits for the row to disappear, so the next assertion sees the final state.

Checking prices correctly

Money is where mobile bugs hide, and where tests are most often wrong. Do not compare floating-point numbers, and do not scrape "EUR 49.90" with string slicing in each test. Convert text to integer cents in one helper, and compute the expected total with integer math (round half up, as the app does).

Python Cart totals with integer cents (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A UI test then reads cart-total text, converts it with cents(), and compares with the independently computed expected value. When the app has a rounding bug (for example 21.573 rounded down instead of half up), this comparison finds it and a float-based check could hide it.

A cross-platform screen layer

If the accessibility IDs are the same on both platforms, one set of screen classes serves both, and only gestures and a few locators branch on the platform. The driver fixture selects options from a --platform command-line option:

Python
def pytest_addoption(parser):
    parser.addoption("--platform", default="android", choices=["android", "ios"])

@pytest.fixture
def driver(request):
    platform = request.config.getoption("--platform")
    options = android_options() if platform == "android" else ios_options()
    drv = webdriver.Remote(config.APPIUM_URL, options=options)
    drv.platform = platform              # simple attribute for screen objects to read
    yield drv
    drv.quit()

Putting the matrix in CI

Run the suite on each platform and a few device configurations using a matrix job (see Appium in CI and Parallel Runs and the Device Matrix):

YAML
jobs:
  ui:
    strategy:
      fail-fast: false
      matrix:
        include:
          - { platform: android, runner: ubuntu-latest, api: 34 }
          - { platform: android, runner: ubuntu-latest, api: 31 }
          - { platform: ios, runner: macos-latest }
    runs-on: ${{ matrix.runner }}
    steps:
      - run: pytest tests --platform ${{ matrix.platform }} --junitxml=report-${{ matrix.platform }}.xml

fail-fast: false matters: one failing platform should not cancel the other, because you want both results.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why seed the cart through an API instead of tapping through products in every test?

    UI setup repeats in every test and adds flakiness; API setup is quick and deterministic.
  2. 2. Why convert prices to integer cents in tests?

    Integer arithmetic gives exact, comparable money values.
  3. 3. After a swipe-to-delete gesture, what should the screen method do?

    Waiting for the final state makes the following assertion reliable.
  4. 4. Why set fail-fast: false in the CI matrix?

    Each device configuration is useful information, even when another fails.

Summary

  • Seed state through an API and use the UI for the flow under test.
  • Wrap platform-specific gestures in screen methods and wait for the result of each gesture.
  • Check money with integer cents and independently computed expectations.
  • Choose the platform with a command-line option, and cover platforms and device versions with a CI matrix.

Next: Practice Exercises and Review Questions