Cross-Browser and Cross-Platform Testing Questions
Verifying that a product behaves consistently across browsers, browser versions, operating systems, devices, and screen sizes. Covers building a browser and device coverage matrix, prioritizing platforms by real usage telemetry, deciding what to automate versus leave to manual exploratory checks, risk-based sampling between PR, nightly, and pre-release runs with escalation to the full matrix, wiring cross-browser suites into CI with parallel and selective runs, cloud grids versus self-hosted labs (Selenium Grid in Docker, on-prem device labs) versus emulators and simulators, real devices and native mobile apps, sizing infrastructure for large numbers of parallel sessions, running one suite across Chromium, Firefox, and WebKit (Playwright projects, driver factories driven by environment config), headless versus headed differences, feature detection versus user-agent sniffing, browser-specific defects (Safari timing and event ordering, cookie policy and third-party embeds, font and DPI rendering, input and event differences) and how to debug them on physical devices, and OS-level differences (filesystem, encoding, endianness, numeric behavior). Excludes framework and Page Object design, flaky-test management, locator and wait mechanics, and accessibility or visual-diff tooling, which are covered elsewhere.
Describe cloud-based cross-browser testing services such as BrowserStack and Sauce Labs and compare them to running a local Selenium Grid or an on-prem device lab. For each approach, discuss coverage, cost, latency, data privacy, maintenance overhead, and suitability for PR gating versus nightly regression runs.
Sample Answer
Direct answer
Use two tools for two jobs. Gate pull requests (PRs) on your own containers running Chromium, Firefox and WebKit: no queue, no per-minute fee, no network hop, and nothing leaves your network. Use a cloud service such as BrowserStack or Sauce Labs nightly for what you cannot own cheaply: real iPhones and Android phones, many OS and browser versions. Beyond those two, treat a self-hosted Selenium Grid as the right choice only when you already have a Selenium suite to scale (WebDriver is the standard protocol Selenium uses to remote-control a browser, and Selenium Grid is a router that sends those commands to browsers on many machines), and an on-prem device lab only when privacy rules or constant device use justify owning hardware.
What each approach is
- Cloud grid (BrowserStack, Sauce Labs). A vendor runs browsers and devices; your tests connect over the internet. BrowserStack's Automate documentation advertises "3500+ real desktop and mobile browsers" on its Selenium grid, and its Playwright page says tests can run on "an extensive list of browsers and mobile devices". Sauce Labs provides Sauce Connect, a tunnel client (documented as secure and encrypted over HTTP/2) that lets cloud browsers reach apps that are not public: localhost, staging behind a firewall, IP-allowlisted environments (ones that accept traffic only from approved addresses). HTTP/2 is a version of the web protocol that carries many requests over one connection.
- Selenium Grid. Per Selenium's documentation, Grid routes WebDriver commands from the client to remote browser instances on machines you operate, to run tests in parallel and across browser versions and platforms. You supply and maintain the machines.
- On-prem device lab. Physical phones and tablets you own, attached to hosts you maintain, usually behind a device-management layer (software that inventories the devices, resets them between runs, updates them and lets tests reserve one).
- Self-hosted containers (the baseline). Playwright's Linux image runs Chromium, Firefox and WebKit builds on your CI runners.
Comparison on the axes you asked about
| Axis | Cloud grid | Selenium Grid (self-hosted) | On-prem device lab | Containers (baseline) |
|---|---|---|---|---|
| Coverage | Widest: real devices, many OS and browser versions | Only the browsers and OSes you install | Only devices you bought; real hardware | Three engines on Linux; no real iOS or Android |
| Cost shape | Pay per parallel session or minute, grows with parallelism | Machines plus engineer time | Capital for devices plus replacement and staff time | Runner minutes you already pay for |
| Latency | Internet round trip on every command plus session start-up or queue wait | Local network | Local network | None beyond the container |
| Data privacy | Test traffic and data go to a third party; non-public apps need a tunnel | Stays inside your network | Stays inside your network | Stays inside your network |
| Maintenance | Vendor maintains devices and browsers; you maintain the tunnel and test config | You patch browsers, drivers, nodes and scale them | Heaviest: devices, OS updates, cables, battery, disconnects | Bump one image tag per Playwright release |
| PR gating | Poor to fair: queueing and per-minute cost on every PR | Good if sized for PR load | Poor: small fixed capacity serialises PRs | Best |
| Nightly regression | Best fit: bursty, wide, real devices | Good | Good if the lab is the point | Good for the three engines |
Recommendation and what would flip it
-
PRs: containers in CI. The speed and the cost of a PR run are the constraints; real devices add neither speed nor many extra catches per PR.
-
Nightly and release candidates: a cloud grid for iOS Safari, Android Chrome and one or two older OS versions, plus Safari on macOS. You pay for burst capacity only while it runs.
-
Flip to a self-hosted grid if you have a large Selenium suite and the privacy and cost of the cloud do not fit; Selenium Grid is a WebDriver routing layer, so it does not change what browsers you can reach.
-
Flip to an on-prem lab if regulation forbids sending pre-release data off-site even through a tunnel, or if device sessions run for many hours every day so that owning devices costs less than renting minutes. Compute it: lab cost per month (devices amortised over their life, plus staff time) against cloud cost per month at your measured parallel sessions and minutes.
Worked example with illustrative numbers (the cloud rate is an assumption, not a vendor quote; use your contract). Lab: 10 devices at $600 spread over 24 months is $250 a month, plus 8 hours of upkeep at $60 an hour is $480, so $730 a month. Cloud at an assumed $0.10 per device-minute breaks even with that at $730 / $0.10 = 7,300 minutes, about 122 hours of device time a month. A nightly run of 3 devices for 40 minutes on 22 working days is 3 x 40 x 22 = 2,640 minutes, $264 a month: rent. Four devices busy 6 hours a day for 22 days is 4 x 6 x 60 x 22 = 31,680 minutes, $3,168 a month: own, as long as the 10 owned devices cover the models you need.
Pitfalls
- Pointing a cloud grid at localhost or an internal staging site fails until a tunnel is running, and the tunnel is a new point of failure and a new place data travels.
- Cloud capacity is bought as a number of parallel sessions. A parallel session is one browser or device session running at the same time as others. Size the nightly job's parallelism to the plan, and check the vendor's behaviour for sessions above the limit (waiting or rejection) before the first big run.
- Playwright WebKit in your own container is not iOS Safari. Only real devices reproduce iOS-specific bugs, which is the best argument for keeping one cloud or lab row.
Your UI tests are green on Chrome, but several fail on Firefox and Safari. What kinds of rendering, input and event differences between browsers usually cause this, and what quick mitigation would you apply to each?
Sample Answer
Direct answer
When a suite is green on Chrome and red on Firefox and Safari, the cause is usually one of four things: the test hard-codes an assumption that only Chromium satisfies (an exact pixel value, a default font, a focus side effect), the engines really do render or handle input differently, the app uses a feature one engine lacks, or the environment differs. Triage each failure into one of those buckets before touching code, because the mitigation differs: loosen or rewrite the test, normalise the styling, add a fallback in the app, or pin the environment.
Differences that cause failures, and the quick mitigation for each
| Kind | What differs | Quick mitigation |
|---|---|---|
| Rendering: default styles | Each engine ships its own default stylesheet for form controls and body text | Set font: inherit on form controls and an explicit font stack on the page; self-host web fonts so all engines load the same file |
| Rendering: sub-pixel layout | Engines round fractional sizes differently, so an exact === on a measured size fails | Assert with a tolerance, or assert on structure (which row an item landed in) instead of raw pixels |
| Input: typing into form fields | Engines disagree on what a field accepts and what its value reads while text is invalid | Drive input the way the user does, then assert on the validated result or the error message, not on the raw value string |
| Input: native widgets | Date pickers, select popups and file choosers are drawn by the browser, not the page | Set values through the API (fill, selectOption, setInputFiles) rather than clicking inside native UI |
| Events: focus side effects | Whether a click moves focus onto a button varies by browser and OS | Do not assert on focus after a click; focus the element explicitly when the test needs it |
| Events: timing | Animations, transitions and layout settle at slightly different times | Wait for a condition (an element state, a response) instead of a fixed delay |
Evidence from a run
Run in the Playwright 1.48.2 image (Chromium 130.0, Firefox 131.0, WebKit 18.0, on Linux), a probe page printed:
- Sub-pixel width. A sub-pixel size is a fractional CSS pixel such as 33.33px; each engine stores layout sizes on its own fine grid, so the leftover fraction lands differently. Three
flex: 1items in a 100px container reported widths of33.328125for each item in Chromium and WebKit, and33.33332824707031,33.333343505859375,33.33332824707031in Firefox. 100px cannot be split into three equal whole parts, and the engines resolve the remainder differently: Chromium and WebKit report 33.328125, which is exactly 2133/64 (a whole number of 1/64-pixel steps, so three items total 99.984375), while Firefox reports numbers near 33.3333. A test assertingwidth === 33.328125passes on two engines and fails on Firefox.expect(width).toBeCloseTo(33.33, 1)(within 0.05) passes on all three. - Number input.
12e3is a valid number: theeintroduces an exponent, so it means 12 x 10^3 = 12000.validity.badInputis true when the user has typed something the browser cannot convert to a number, and an invalid number field reads as an emptyvalue(""). After clicking an<input type="number">and typing12e3abc, Chromium reportedvalue"12e3"withbadInputfalse (in the same run, typing onlyabcleft Chromium's value""withbadInputfalse, so Chromium discards the letters that cannot be part of a number as they are typed), while Firefox and WebKit reportedvalue""withbadInputtrue (they keep the text in the box, so it is invalid). That is why""and"12e3"differ: one means no usable number, the other a number the engine accepted. A test that reads.valueafter typing sees different strings. Mitigation: type only valid digits when the test is about something else, and test invalid input in a dedicated case that asserts the visible validation message. - Event order on a button click.
pointerdownis the press of a mouse, finger or pen,mousedownis the older mouse-only press event, andfocusfires when the element becomes the target of keyboard input. All three engines loggedpointerdown, mousedown, focus, pointerup, mouseup, click, so ordering of mouse events is not the usual culprit. - Focus on click. MDN documents that whether clicking a button focuses it varies by browser and OS, and that Safari does not focus it, by design. Playwright's Linux WebKit focused the button in the run above, which shows why a green WebKit project does not prove macOS Safari behaviour. A test that asserts
toBeFocused()after a click is a bad test; a keyboard-accessibility test should press Tab or callfocus()itself.
Triage order
- Open the failure's trace (Playwright's recorded timeline of actions, screenshots and page snapshots, opened with
npx playwright show-trace) or screenshot on the failing browser and read the assertion: is it an exact number, a string from a field, or a missing element? - Re-run that single test on that browser alone (
--project=firefoxruns only the Playwright config project named firefox, one browser setup) to rule out interference from parallel tests. - Classify: test assumption (loosen or rewrite), real cross-engine difference (normalise in CSS or code), missing feature (feature detection plus fallback), or environment (fonts, locale, time zone).
- Fix at the cheapest level. Normalising CSS fixes real users as well as the test, so prefer it when the difference is visible to users.
Pitfalls
- Do not skip a test on the failing browser to make CI green without a ticket; the skip hides a possible real bug.
- Playwright WebKit is not iOS Safari. Mobile-only failures need a real device or a cloud device.
You have traffic telemetry: 60% Chrome desktop, 15% Firefox desktop, 10% Safari desktop, 10% Chrome mobile, 5% Safari mobile. Design a prioritized cross-browser strategy for PR gating and nightly regression that covers at least 90% of user sessions in PR runs while staying cost-conscious. Show how you split tests between PR and nightly.
Sample Answer
Direct answer
Gate every PR (the check that must pass before a pull request can merge) on four runs: the full suite on Chromium desktop, plus a small tagged smoke subset on Firefox desktop, WebKit desktop and an emulated Chrome mobile viewport. That covers 95 percent of the sessions in the telemetry in PRs. Everything else, the full suite on all engines plus emulated Safari mobile, runs nightly, and real iPhone hardware runs before release. Coverage here means "a run exists whose browser engine and form factor match the session's", and a smoke subset covers a platform for gating purposes, not exhaustively.
Step 1: Choose the PR targets by coverage arithmetic
Sessions by platform (this telemetry is the product's own measurement of what browsers real visitors use): Chrome desktop 60 percent, Firefox desktop 15, Safari desktop 10, Chrome mobile 10, Safari mobile 5 (total 100). Add platforms in descending share until the sum reaches 90, but check that each added target is a distinct engine or form factor:
| Added target | Share | Running total |
|---|---|---|
| Chromium desktop | 60 | 60 |
| Firefox desktop | 15 | 75 |
| WebKit desktop (stands in for Safari desktop) | 10 | 85 |
| Chrome mobile (Chromium with a phone viewport and touch) | 10 | 95 |
| Safari mobile (WebKit with an iPhone viewport) | 5 | 100 |
Four targets reach 95 percent, which clears the 90 percent bar with margin; the fifth adds 5 points at the cost of another run, so it moves to nightly. Playwright (a test framework that drives real browsers) maps onto this directly: its Chromium build stands in for Chrome, its Firefox build for Firefox, and its WebKit build for Safari. Mobile is emulation: a device descriptor such as Pixel 7 sets the viewport, touch support, device pixel ratio (physical pixels per CSS pixel) and user-agent on the Chromium engine; iPhone 13 does the same on WebKit. Emulation checks responsive layout and touch handling, not the performance or quirks of a real phone, and Playwright's WebKit is not iOS Safari.
Step 2: Split tests between PR and nightly
Tag tests; the tag decides where they run. A smoke test is a quick check that the critical paths still work. Here a test is tagged @smoke, by putting that word in its title, if it covers a critical journey (sign-in, search, add to cart, checkout) or exercises something engine-sensitive (forms and date inputs, layout that changes by viewport, file upload, newer web APIs).
| Tier | Where it runs | What runs |
|---|---|---|
| PR gate | Chromium desktop | The full suite (this is where logic bugs are caught) |
| PR gate | Firefox desktop, WebKit desktop, Chrome mobile (emulated) | @smoke only |
| Nightly | All four PR targets plus Safari mobile (emulated WebKit) | The full suite on every target |
| Before release | Real iPhone and Android devices (cloud farm or lab), plus macOS Safari | @smoke plus the checks that only real hardware shows (touch feel, keyboard, camera, performance) |
Worked cost with 6 tests in the demo suite, 2 of them @smoke: a PR runs 6+2+2+2=12 test executions, nightly runs 5×6=30, and running the full suite on all five targets for every PR would be 30 as well. The PR gate costs 12/30=40% of that. The proportion is the point: it falls further as the full suite grows while the smoke subset stays small (for example, at 600 tests with 60 smoke tests: 600+3×60=780 against 5×600=3000, which is 26 percent).
Shipped configuration
The config below defines the PR projects and, with TIER=nightly, the full set. The isMobile fixture and the viewport meta tag matter: a page without <meta name="viewport" content="width=device-width"> is laid out at a wide default width on a mobile browser, so a phone-width media query never fires. Without the tag, the nav test fails in the Chrome mobile project for exactly that reason (the nav stays hidden because the layout width is wider than 600 px).
// playwright.config.js
import { defineConfig, devices } from '@playwright/test';
const smoke = /@smoke/;
const pr = [
{ name: 'chromium-desktop', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox-desktop', use: { ...devices['Desktop Firefox'] }, grep: smoke },
{ name: 'webkit-desktop', use: { ...devices['Desktop Safari'] }, grep: smoke },
{ name: 'chrome-mobile-emulated', use: { ...devices['Pixel 7'] }, grep: smoke },
];
const nightlyExtra = [
{ name: 'safari-mobile-emulated', use: { ...devices['iPhone 13'] } },
];
export default defineConfig({
testDir: '.',
reporter: 'list',
projects: process.env.TIER === 'nightly'
? [...pr.map(({ grep, ...p }) => p), ...nightlyExtra]
: pr,
});
Reading the configuration:
devices['Pixel 7']is a device descriptor, a bundle of settings (viewport size, pixel ratio, touch, user-agent,isMobile) that Playwright applies to the browser context, which is how emulation works.grep: smokeis a project option: Playwright runs only the tests whose name matches the regular expression, so the@smoketext in a test title is the tag. A project with nogrepruns every test.process.env.TIERreads the environment variable set on the command line (TIER=nightly npx playwright test). Anything else, including no value, selects the PR set.pr.map(({ grep, ...p }) => p)copies each PR project while dropping itsgrepproperty: the parameter pattern pullsgrepout and gathers every other property intop. Nightly projects therefore have no filter and run the full suite;nightlyExtraadds the iPhone project.
// checkout.spec.js
import { test, expect } from '@playwright/test';
const page_html = `data:text/html,<meta name="viewport" content="width=device-width"><style>nav{display:none}@media(max-width:600px){nav{display:block}}</style><nav>menu</nav><h1>Shop</h1>`;
const names = [
'renders heading @smoke', 'mobile nav follows viewport @smoke',
'sorts a list', 'filters a list', 'formats a price', 'shows empty state',
];
for (const name of names) {
test(name, async ({ page, isMobile }) => {
await page.goto(page_html);
await expect(page.locator('h1')).toHaveText('Shop');
if (name.startsWith('mobile nav')) {
await expect(page.locator('nav')).toBeVisible({ visible: isMobile });
}
});
}
Reading the test: isMobile is a built-in Playwright fixture that is true when the project's device descriptor is a phone (Pixel 7 here) and false for the desktop projects. toBeVisible({ visible: isMobile }) passes when the nav's visibility equals that boolean, so the nav must be visible on the phone project and hidden on desktop. The page is a data: URL, so the viewport meta tag is written into the page text itself; without it the phone project lays the page out at a wide default width and the 600 px rule never matches.
Result. The list reporter prints one line per test and ends with a total such as 12 passed (1.4s) (the time varies); the block below is that total with the per-project counts tallied from the per-test lines, not literal program output. The totals and the per-project split were identical on 10 consecutive runs:
TIER=pr: 12 passed (chromium-desktop 6, firefox-desktop 2, webkit-desktop 2, chrome-mobile-emulated 2)
TIER=nightly: 30 passed (6 tests in each of the 5 projects)
What would change the plan
- Revenue or contract weight: session share is not risk. If the 5 percent on Safari mobile is the paying segment, move emulated Safari mobile into the PR gate, and use real-device runs on every release.
- A bug that only shows on one engine: raise that engine's smoke subset, or run its full suite on PRs that touch the affected area.
- Telemetry is by sessions: re-read it each quarter, because the shares move with browser releases and traffic mix.
Pitfalls
- Calling Chrome mobile emulation "mobile coverage" for real Android; emulation does not reproduce hardware, keyboards or throttled CPUs.
- Letting the
@smoketag grow until it is the full suite, which silently removes the cost saving. - Counting WebKit on Linux as proof for iPhone Safari: it is the same engine family but not the same build.
Running the code
Files: package.json with { "private": true, "type": "module" } plus the two files above. Inside mcr.microsoft.com/playwright:v1.48.2-jammy:
npm i @playwright/test@1.48.2
TIER=pr npx playwright test
TIER=nightly npx playwright test
You have to cover a cross-browser web app with manual test cases and cannot test every browser, version and device combination. How do you choose which cases run where, and how do you record the intended coverage on each case?
Sample Answer
Direct answer
Rank every manual case by risk, then give each case a coverage tier that fixes how many browsers it runs on and which ones. High-risk and engine-sensitive cases (cases whose result depends on how a browser engine implements a feature, so different browsers can disagree) run on every target in the matrix; medium cases run on a rotating pair of targets so that each browser is hit over successive release cycles; low-risk cases run on one primary browser. Record the intended coverage on the case itself as structured fields (a tier and an explicit target list), and record the actual result per target on each run, so a reader can tell "not planned" from "planned and not yet run".
Step 1: Fix the target list from usage data
List the targets that real users have, not every combination that exists. For a typical consumer web app that is a short list such as: Chrome on Windows, Firefox on Windows, Safari on macOS, Safari on iPhone, Chrome on Android. Cut it to what your analytics shows carries most sessions (for example the top targets that together cover about 90 percent of sessions), and add any target a contract or support policy requires. Browsers outside the list get a best-effort statement, not a promise.
Step 2: Score each case and assign a tier
Score each case on two questions: how bad is a failure (business impact: payment, login, data loss), and how likely is it to differ by browser (engine sensitivity)? Engine-sensitive work includes date and file inputs, drag and drop, clipboard, video and audio, print stylesheets, sticky or grid-heavy layout, and anything using newer web APIs. A case can be tier A for either reason.
| Tier | Which cases | Runs on | Cadence |
|---|---|---|---|
| A | Critical journeys (sign-in, checkout) and engine-sensitive cases | All targets | Every release candidate |
| B | Important but ordinary functionality | A rotating pair of targets from two different engines, alternating between releases (see the worked example) | Every release, different pair each time |
| C | Low-risk, stable, rarely changed | The primary target only | Every release (primary target) |
Add an override rule: any case covering code changed in this release moves up one tier for that release, because change is where browser differences surface.
Step 3: Record intended coverage on the case
Put fields on every case in your test management tool (or the spreadsheet column set) so the plan is visible without opening a separate document:
id: CHK-042
title: Apply a discount code at checkout
risk: high # impact if it fails
engine_sensitive: no # uses date inputs, file upload, clipboard, media, print?
tier: A
targets_planned: [chrome-win, firefox-win, safari-mac, safari-iphone, chrome-android]
rotation: n/a # tier B only: pair-1 or pair-2
last_run:
chrome-win: pass 2026-09-30
safari-iphone: not run
A second card shows how the fields change. This one is tier B, so its planned targets are the pair for the current release:
id: CHK-088
title: Sort order history by date
risk: medium
engine_sensitive: no # plain table sorting, no browser-specific API
tier: B
targets_planned: [chrome-win, safari-mac]
rotation: pair-1 # next release: pair-2 = [firefox-win, safari-iphone]
last_run:
chrome-win: pass 2026-09-30
safari-mac: pass 2026-09-30
If the same case sorted with a native date picker, engine_sensitive would become yes and the tier would become A, because native date inputs render and validate differently in each engine.
The targets_planned list states the intent; last_run per target shows the gap. A report of cases whose last_run is older than two release cycles for any planned target is the coverage-gap list.
Worked example: counting the effort
Suppose 120 cases and 4 targets (Chrome on Windows, Firefox on Windows, Safari on macOS, Safari on iPhone). Tiering gives 20 tier-A cases, 40 tier-B cases and 60 tier-C cases.
| Tier | Cases | Targets each | Executions |
|---|---|---|---|
| A | 20 | 4 | 20 x 4 = 80 |
| B | 40 | 2 | 40 x 2 = 80 |
| C | 60 | 1 | 60 x 1 = 60 |
| Total | 120 | 220 |
Running everything everywhere is 120 x 4 = 480 executions, so the tiered plan is 220 / 480, about 46 percent of the effort. Tier B rotation alternates pair 1 (Chrome Windows plus Safari macOS: Blink and WebKit) and pair 2 (Firefox Windows plus Safari iPhone: Gecko and WebKit). Each pair mixes two engines, and the two pairs together are the four targets, so over two releases each tier-B case has run on all four. With only one Chromium target in this list, a rule that demanded a Chromium member in every pair could not cover Firefox and Safari iPhone; the rule that holds is two different engines per pair and every target reached within the rotation.
Spend part of the saving on exploratory sessions: a time-boxed, unscripted session per non-primary browser, guided by a charter (a one-line written goal) such as "forms, uploads and printing in Safari on iPhone", because scripted cases only find the differences someone predicted.
Trade-offs and pitfalls
- Tier by risk, not by feature owner: the loudest team's cases drift to tier A and the matrix grows back to full.
- A rotating pair misses a bug for one release: acceptable for tier B because tier A covers the critical paths on every target; if a tier-B area has a browser-specific defect in production, promote its cases to tier A.
- Recording only "tested on Chrome": with no target on the case, nobody can tell whether Safari was skipped by plan or by accident.
- Real devices: where a case depends on touch, keyboard or hardware behaviour, the target must be a real device, since an emulated browser in a desktop window is not iPhone Safari.
Your product runs on Linux, Windows and macOS and reads, writes and serialises files and binary data. What platform differences could break it, which concrete tests would you run on each OS, and how would you automate that validation in CI?
Sample Answer
Direct answer
Five families of platform difference break file and binary-data code: how paths and names are written and what is legal, whether names are case- and Unicode-sensitive, what text bytes are produced (encoding and line endings), how binary values are laid out (byte order, size, padding), and what the file system lets you do with open files and long paths. Defend against them by making the product's output explicit rather than platform-default (UTF-8, \n, little-endian standard-size struct formats), by running one portability suite on native Linux, Windows and macOS runners in CI, and by adding a big-endian job through emulation so byte-order assumptions fail loudly.
Terms used below. A code point is the number Unicode assigns to a character. A combining accent is a separate code point drawn over the letter before it, so é can be one code point (U+00E9) or two (e then U+0301); NFC (Normalization Form C) is the Unicode rule that merges such a pair into the single composed code point. Byte order (endianness) is the order a multi-byte number is stored in: little-endian stores the least significant byte first, so the 4-byte number 3 is 03 00 00 00; big-endian stores it last, 00 00 00 03. The locale encoding is the text encoding the operating system's settings pick when a program does not name one. A golden file is a stored known-good output that a test compares byte for byte, and a golden hex string is the same bytes written as hex digits inside the test. aarch64 is 64-bit ARM, s390x is IBM's mainframe CPU (big-endian), and QEMU is an emulator that lets one machine run programs built for another CPU. APFS is Apple's file system. MAX_PATH is the 260-character path limit of older Windows APIs, and the \\?\ prefix is a path spelling that asks Windows to skip that limit.
What differs, and the test that catches it
| Difference | What breaks | Documented fact | Test (run on all three OSes unless noted) |
|---|---|---|---|
| Illegal names | A file that saves on Linux fails or means a device on Windows | Windows forbids < > : " / \ | ? *, control characters, names ending in a space or period, and device names CON, PRN, AUX, NUL, COM1..LPT9, even with an extension such as NUL.txt (Microsoft Win32 naming docs) | Feed those names to the product's name check; assert rejection on every OS |
| Case sensitivity | Report.csv and report.csv are two files on one OS and one file on another | Windows docs: do not assume case sensitivity. The default APFS format on macOS is not case-sensitive, while an APFS (Case-sensitive) variant exists (Apple Disk Utility help) | Create a.txt and A.txt, count files; assert the product flags case-only collisions itself |
| Unicode spellings | é can be one code point or e plus a combining accent, giving two byte-different names that look identical | Normalisation (NFC) makes one canonical spelling | Create both spellings; assert the product normalises names before comparing |
| Line endings | Text written with the platform default differs between OSes | Python open() with newline=None translates \n to os.linesep when writing | Write the product's text output, compare raw bytes to a golden file |
| Text encoding | open() without encoding uses the locale encoding, so the same code writes different bytes | Python docs: default is platform-dependent, from locale.getencoding() | Write non-ASCII text; assert the raw bytes are UTF-8 |
| Binary layout | A struct written on a little-endian machine reads wrong on a big-endian one; native formats add padding | Python struct: @ uses native byte order, size and alignment; <, >, =, ! use standard sizes with no padding | Assert exact header bytes from a golden hex string; unpack a stored golden file |
| Path length | A deep output path works on Linux and fails on Windows | Windows MAX_PATH is 260 characters; since Windows 10 version 1607 lifting it needs a registry or policy change, and the \\?\ prefix bypasses parsing for APIs that support it | Assert generated paths stay under a budget (250 here) |
| Handles left open | Code that writes a file and forgets to close it works on Linux, then raises PermissionError on Windows when the next step replaces or deletes that file | Python's os.remove docs: on Windows, removing a file that is in use raises an exception; on Unix the directory entry is removed and the storage is freed once the file is no longer in use | Write a file, replace it with another, delete it, all straight after writing; run on all three OSes |
Names, case and text defaults (encoding and line endings) are the differences most teams meet first, because every developer laptop and the CI runner differ in them every day. Byte order and the 260-character limit appear later, when files move between machine types or the output directory gets deep. This ordering is a judgement from how the environments differ, not a measured count.
The portability suite
One small module with the product's rules, and one pytest file that checks each row. The Windows rules are checked on any OS through PureWindowsPath, a path class that applies Windows semantics without touching the disk.
# portability.py
import csv
import struct
import unicodedata
from pathlib import PureWindowsPath
BAD_CHARS = set('<>:"/\\|?*')
def portable_name(name):
"""Return a file name that is legal on Linux, macOS and Windows, or raise ValueError."""
n = unicodedata.normalize("NFC", name) # one spelling of "é", not two
if not n or any(c in BAD_CHARS or ord(c) < 32 for c in n):
raise ValueError(f"reserved character in {name!r}")
if n.endswith((" ", ".")):
raise ValueError(f"trailing space or period in {name!r}")
if PureWindowsPath(n).is_reserved(): # CON, NUL, COM1 ... even as NUL.txt
raise ValueError(f"reserved device name {name!r}")
return n
def case_collisions(names):
"""Names that would be the same file on a case-insensitive file system."""
seen = {}
for n in names:
seen.setdefault(unicodedata.normalize("NFC", n).casefold(), []).append(n)
return [group for group in seen.values() if len(group) > 1]
def write_csv(path, rows):
# Explicit encoding and newline: output bytes no longer depend on the OS or locale.
with open(path, "w", encoding="utf-8", newline="") as f:
csv.writer(f, lineterminator="\n").writerows(rows)
def pack_header(version, count):
return struct.pack("<HI", version, count) # standard sizes, little-endian, no padding
def check_path_budget(path, limit=250):
"""Fail early on paths that would approach the 260-character Windows MAX_PATH."""
if len(str(path)) > limit:
raise ValueError(f"path is {len(str(path))} characters, budget is {limit}")
return path
# test_portability.py
import locale
import os
import struct
import sys
from pathlib import PurePosixPath, PureWindowsPath
import pytest
from portability import case_collisions, check_path_budget, pack_header, portable_name, write_csv
@pytest.mark.parametrize("bad", ["NUL.txt", "con", "COM1.log", "a:b.csv", "what?.csv", "a|b.csv", "x*y.csv", "tab\there.csv", "name.", "name "])
def test_names_illegal_somewhere_are_rejected_everywhere(bad):
with pytest.raises(ValueError):
portable_name(bad)
def test_unicode_spellings_collapse_and_case_variants_are_flagged():
composed, decomposed = "caf\u00e9.csv", "cafe\u0301.csv"
assert portable_name(decomposed) == composed
assert case_collisions(["Report.csv", "report.csv", "other.csv"]) == [["Report.csv", "report.csv"]]
def test_this_file_system_probe(tmp_path):
(tmp_path / "a.txt").write_text("1")
(tmp_path / "A.txt").write_text("2")
(tmp_path / "caf\u00e9").write_text("3")
(tmp_path / "cafe\u0301").write_text("4")
print(f"\nsep={os.sep!r} byteorder={sys.byteorder} locale_encoding={locale.getencoding()} "
f"files_after_a/A_and_two_cafe_spellings={len(os.listdir(tmp_path))}")
def test_csv_bytes_are_identical_on_every_os(tmp_path):
out = tmp_path / "out.csv"
write_csv(out, [["id", "name"], [1, "caf\u00e9"]])
assert out.read_bytes() == b"id,name\n1,caf\xc3\xa9\n"
legacy = tmp_path / "legacy.csv" # what a Windows-locale default produces
with open(legacy, "w", encoding="cp1252", newline="\r\n") as f:
f.write("id,name\n1,caf\u00e9\n")
print("\nportable:", out.read_bytes(), "\nwindows-style:", legacy.read_bytes())
assert out.read_bytes() != legacy.read_bytes()
def test_binary_header_has_fixed_layout():
print("\n<HI ->", pack_header(1, 3).hex(), struct.calcsize("<HI"),
"| native @HI ->", struct.pack("@HI", 1, 3).hex(), struct.calcsize("@HI"),
"| >HI ->", struct.pack(">HI", 1, 3).hex())
assert pack_header(1, 3).hex() == "010003000000"
assert struct.unpack("<HI", bytes.fromhex("010003000000")) == (1, 3)
def test_windows_path_rules_checked_from_any_os():
a, b = PureWindowsPath("C:/Data/Out.CSV"), PureWindowsPath("c:/data/out.csv")
p, q = PurePosixPath("/data/Out.CSV"), PurePosixPath("/data/out.csv")
print(f"\nwindows paths equal: {a == b}; posix paths equal: {p == q}")
assert a == b and p != q
def test_output_path_budget():
assert check_path_budget("/out/" + "x" * 100 + "/report.csv")
with pytest.raises(ValueError):
check_path_budget("/out/" + "x" * 300 + "/report.csv")
def test_no_handle_is_left_open_after_writing(tmp_path):
out = tmp_path / "out.csv"
write_csv(out, [["id"], [1]])
replacement = tmp_path / "new.csv"
write_csv(replacement, [["id"], [2]])
os.replace(replacement, out) # replace over an existing file
os.remove(out) # delete straight after writing
assert not out.exists()
Run in python:3.12-slim containers, once natively on aarch64 (little-endian) and once on s390x (big-endian, emulated with QEMU), it prints on aarch64 (verbatim; the time in the last line varies from run to run):
...........
sep='/' byteorder=little locale_encoding=UTF-8 files_after_a/A_and_two_cafe_spellings=4
.
portable: b'id,name\n1,caf\xc3\xa9\n'
windows-style: b'id,name\r\n1,caf\xe9\r\n'
.
<HI -> 010003000000 6 | native @HI -> 0100000003000000 8 | >HI -> 000100000003
.
windows paths equal: True; posix paths equal: False
...
17 passed in 0.01s
and on s390x (also 17 passed) the lines that differ are:
sep='/' byteorder=big locale_encoding=UTF-8 files_after_a/A_and_two_cafe_spellings=4
<HI -> 010003000000 6 | native @HI -> 0001000000000003 8 | >HI -> 000100000003
How to read it:
- Byte by byte,
struct.pack("<HI", 1, 3)is:His a 2-byte unsigned number, so 1 becomes01 00;Iis a 4-byte unsigned number, so 3 becomes03 00 00 00; with no padding the 6 bytes are01 00 03 00 00 00, printed010003000000. The native@HIformat also aligns the 4-byte field to a multiple of 4, so 2 padding bytes (00 00) are inserted after theH:01 00+00 00+03 00 00 00, 8 bytes in all. On a big-endian machine the same native layout is00 01+00 00+00 00 00 03.>HIis00 01+00 00 00 03. - The explicit formats are identical on both machines:
<HIis010003000000(6 bytes),>HIis000100000003. The native format@HIis 8 bytes (two pad bytes) and is0100000003000000on little-endian but0001000000000003on big-endian. Any code that writes native layout to a file is wrong the moment the file moves. - The CSV written with
encoding="utf-8", newline=""and an explicit\nterminator isb'id,name\n1,caf\xc3\xa9\n'everywhere; the "Windows-style" bytes (\r\n, and\xe9from the cp1252 code page) show what unpinned defaults can produce. The cp1252 case is simulated, because a Windows runner is needed to see a real locale default. - The open-handle row has no output to read because on Linux nothing fails. The test passes since
write_csvcloses its file withwith. If someone changed it to keep the file object open, the same test would still pass on Linux but theos.replaceoros.removeline would raisePermissionErroron the Windows runner, which is the only place that regression shows. - On the Linux volume used here all four probe files exist (
a/A, and both spellings ofcafé), so Linux accepts what other file systems may merge; the product-level collision check is what protects it.
Automating it in CI
# .github/workflows/portability.yml
name: portability
on: [pull_request]
jobs:
native:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.12" }
- run: pip install pytest==8.3.3
- run: python -m pytest -q -s
big-endian:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
- run: >
docker run --rm --platform linux/s390x -v "$PWD":/w -w /w python:3.12-slim
sh -c "pip install -q pytest==8.3.3 && python -m pytest -q"
- GitHub's hosted runner labels include
ubuntu-latest(x64),windows-latest(x64) andmacos-latest(arm64, Apple M1 per the runner reference), plus arm64 Linux labels such asubuntu-24.04-arm; the matrix therefore also covers x64 versus arm64 for free. Pin the action versions to the current releases. - Treat red on any one OS as a blocker;
fail-fast: falselets all three report. - Keep golden files from being rewritten by checkout: mark them binary in
.gitattributesso Windows line-ending conversion cannot change the bytes you compare. - Run the same suite locally through the Linux container so developers see the Linux result before CI.
Trade-offs
Emulated big-endian is slow (use it for the small byte-layout suite only) and covers a rare target; if the product never runs on big-endian hosts the real requirement is a file format that is defined as little-endian, which the golden-bytes test enforces. Windows-only behaviours (reserved names, path length, locked files) can only be fully proven on a Windows runner, which is why the native matrix stays even though PureWindowsPath checks run anywhere.
Running the code
# put portability.py and test_portability.py in one folder, then (Linux or emulated big-endian):
docker run --rm --ulimit core=0 --platform linux/s390x -v "$PWD":/w -w /w python:3.12-slim sh -c \
'pip install -q pytest==8.3.3 && timeout 150 python -m pytest -q -s -p no:cacheprovider'
# drop --platform for the host architecture
Unlock Full Question Bank
Get access to all 16 Cross-Browser and Cross-Platform Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.