Skip to content

Localizing your first test in Playwright and Python

Matthew Heusser Feb 7, 2022 Localization

Developed by Microsoft, with support for all major browsers, a large number of programming languages, with grid computing out of the box, Playwright can look like a sleek, modern alternative to Selenium or Cypress. After you've followed our tutorial to Automate your Playwright test in Python, you might want to go forward to the next step – creating tests that change the location of the request, testing in different languages.

Today we'll tell you exactly how to integrate Playwright and WonderProxy, with examples in Python that you can follow along with. You'll only need three things to get started: A working test with Playwright, a (free!) WonderProxy Trial Account, and your proxy credentials.

Getting Started

Running the tutorial to automate a test in Playwright will get you a base installation of Python and Playwright. After that, head to WonderProxy and either log in to your existing account or create a free trial account. Your proxy server credentials will be your username and a proxy token, which you can generate in your account. You'll use the proxy token like a password. (You can read more about proxy tokens in our documentation.) Also, add the WonderProxy servers you want to connect to. The example below uses Lansing, Amsterdam, Venice and Tokyo.

Any test that runs through WonderProxy servers will need your proxy credentials. That means a line of code like username=_your_username_. Employees seeking help might cut and paste to StackOverflow, or accidentally put portfolio work in Github. Matt Heusser, one of our authors, once accidentally put a password in a LinkedIn Message. Most importantly, our examples are in Github, and we'd like to keep those passwords private. To avoid the password problem, we have our examples store passwords in environment variables.

export PROXY_USER=your_username
export PROXY_TOKEN=your_wonderproxy_token
echo $PROXY_USER
echo $PROXY_TOKEN

Running this from the command line will temporarily set environment variables in the current shell on Linux and Mac. For Windows, the setx command is equivalent (though permanent). Make the change permanent under Linux and Mac by editing the your login profile.

Once the accounts are set up, we can download and save the code and run it.

A localized test in Python

Our example test, in GitHub, uses WonderProxy to change the location (where the traffic is coming from) four different times. It then checks the text to make sure it changes by locale. If localization isn't the issue but consistency is, another technique is to use locators to reach elements, then loop through locales to make sure the application works in every language. Using a tool like Sauce Labs, it may be possible to record the tests and watch them, perhaps at accelerated speeds, to see if a difference of word length causes visual glitches.

To start, though, the code - test_world_tour.py.

import os
import pytest
 
# A list of locations to visit from:
locations = [
  { 'location': 'Lansing', 'server': 'lansing.wonderproxy.com', 'searchButtonText': 'Google Search', 'luckyButtonText': 'I\'m Feeling Lucky' },
  { 'location': 'Amsterdam', 'server': 'amsterdam.wonderproxy.com', 'searchButtonText': 'Google Zoeken', 'luckyButtonText': 'Ik doe een gok' },
  { 'location': 'Venice', 'server': 'venice.wonderproxy.com', 'searchButtonText': 'Cerca con Google', 'luckyButtonText': 'Mi sento fortunato' },
  { 'location': 'Tokyo', 'server': 'tokyo.wonderproxy.com', 'searchButtonText': 'Google 検索', 'luckyButtonText': 'I\'m Feeling Lucky' },
]

# This is the Python way to run a single test with multiple parameters:
@pytest.mark.parametrize("location", locations)
def test_visit_location(browser, location):
    # Create a context with the proxy server for current location:
    context = browser.new_context(proxy={
        "server": 'http://' + location['server'] + ':10000',
        "username": os.environ['PROXY_USER'],
        "password": os.environ['PROXY_TOKEN']
    })
 
    # Create a page from the context and visit Google home:
    page = context.new_page()
    page.goto("https://google.com")
 
    # Extract the text from the buttons on the page:
    input_selector = 'input[type="submit"]'
    input_list = page.evaluate("""(selector) => {
        // Playwright's browser engine evaluates this block as if it were Javascript running on the page you're testing
        const elements = Array.from(document.querySelectorAll(selector));
        return elements.map(element => element.defaultValue);
    }""", input_selector)
 
    # Assert values match current location:
    assert input_list[0] == location['searchButtonText']
    assert input_list[1] == location['luckyButtonText']

Once the code is on-disk and the environment variables are set, a simple pytest command will run the tests; the results look something like this.

4 passed in 14.25s
test_world_tour.py test results

That's it; your first localization test is running. These examples use the WonderProxy site; exactly what to do next depends on your needs.

Next Steps

Once the test runs, it's time to think about the goal of testing. Do you want to check everything once by looping through locales? Check that keywords translate in locations? Record videos in different languages? "Hit the highlights" of key workflows or write one test per micro-feature? For that matter, should the tests run as part of the continuous integration loop, or one some cadence? Should they be scheduled?

With those answers in hand, make your list of what to cover. This can be as simple as an Excel spreadsheet, long enough to have some real depth but short enough to be comprehensible. Make the first test. Ideally, it should run in under two minutes, certainly under five. It's common for people to create the first test that "hits the highlights" of a few key flows, then venture out into tests that cover small parts of the application in much more detail. In Python, a command-line call to pytest will execute every Python script in the current folder (and children, recursively) that starts with "test", ends in ".py", executing all the methods in those scripts that begin with "test."

So start with a test directory and a handful of scripts. Get some value. After that, it is time to think about structure.

Matthew Heusser

Among with David Hoppe

The managing director of Excelon Development, Matt Heusser writes and consults on software delivery with a focus on quality.