Given this simple pytest test file, what will be the output when running pytest -n auto?
import pytest import time def test_one(): time.sleep(1) assert True def test_two(): time.sleep(1) assert True def test_three(): time.sleep(1) assert True
Think about how -n auto uses all CPU cores to run tests in parallel.
The -n auto option runs tests in parallel using all available CPU cores. Since each test sleeps 1 second, running three tests sequentially would take about 3 seconds. Running in parallel reduces total time to about 1 second. There is no shared state causing failure here.
You want to write a test that checks if pytest-xdist is running tests in parallel using -n auto. Which assertion is correct?
import pytest import time import threading results = [] def test_parallel(): def worker(): time.sleep(1) results.append(threading.get_ident()) threads = [] for _ in range(3): t = threading.Thread(target=worker) t.start() threads.append(t) for t in threads: t.join() # Which assertion below correctly checks parallel execution?
Parallel execution means different threads run the tasks.
If tests run in parallel, the worker function runs in different threads, so threading.get_ident() returns different thread IDs. Checking that the set of thread IDs has length 3 confirms parallelism.
Consider this test file:
counter = 0
def test_increment():
global counter
counter += 1
assert counter == 1
When running pytest -n auto, tests fail intermittently. Why?
Think about how pytest-xdist runs tests in parallel processes.
Pytest-xdist runs tests in separate processes. Each process has its own memory space, so global variables are not shared. Incrementing a global variable in one process does not affect others, causing the assertion to fail.
You want to run tests in parallel using pytest -n auto. Which plugin must be installed?
Look for the official pytest plugin that supports -n option.
The pytest-xdist plugin provides the -n option to run tests in parallel across multiple CPUs.
When running tests with pytest -n auto that modify a shared database, what is a common limitation?
Think about shared resources and concurrency.
Running tests in parallel that modify the same database can cause race conditions and flaky tests because multiple tests write concurrently without isolation.