Programming for Test Automation Questions
General Java and Python language proficiency questions where the test-engineering framing is load-bearing: it changes what is actually being assessed, not just the flavor text. Covers designing for testability (polymorphism and interchangeable implementations so a test harness can substitute a fake), how exception-handling choices change what a test for that failure path looks like, choosing the right collection for test-result processing, methodology for testing concurrency correctness (writing a test that can actually reveal a race or a visibility bug, not just fixing one), serialization and diffing trade-offs for test fixtures and CI artifacts, detecting a hash/equality-contract violation through testing, memory-bounded generator and streaming I/O patterns for test data, and small test-engineering utilities (CI-config diffing, checksum-verified data sharding). Excludes writing or debugging the code inside a single automated test script (control flow, parameterization, translating a manual case, locator, wait, and retry mechanics), which belongs to test automation scripting. Excludes suite-wide or framework-wide structural and strategy decisions (Page Object Model, layering, tool or driver choice, CI wiring, governance, flaky-test-detection systems, scalable test infrastructure), which belongs to test automation framework architecture and design. Excludes classic array/string/graph technique problems with no real test-engineering judgment required, which belong to arrays, strings, and hashing. Also excludes generic OOP-principles surveys, generic concurrency-primitive implementation (singletons, thread pools, producer-consumer queues, lock-free structures) with no distinct testing angle, generic garbage-collection and memory-leak content, generic functional-programming surveys, and generic hash-function or hash-table design: each of these already has a dedicated, larger topic in the catalog (Object-Oriented Programming and Design, Concurrency Synchronization and Deadlock, Memory Management and Garbage Collection, Functional Programming, Hashing and Hash Tables), and a test-flavored costume on otherwise-identical content is not a reason to duplicate it here.
Implement a command-line tool that splits a large newline-delimited file into N shards, writes a checksum for each shard, and verifies integrity after splitting. Describe the unit and integration tests you would write to validate correctness and idempotency: running the tool twice on the same input must produce the same shards and the same checksums.
Sample Answer
Direct answer
Split the file into N shards, hash each shard with a streaming checksum as it is written so no shard is ever fully re-read just to compute its hash, then immediately re-hash every shard from disk and compare against the checksum just written, so integrity is verified against what is actually on disk, not just against what was in memory.
Structured elaboration
Three properties need explicit design attention:
- Sharding: divide the input's lines as evenly as possible across N shards (distributing the remainder across the first few shards rather than dumping it all into the last one, so shard sizes never differ by more than one line).
- Integrity verification: after writing a shard, compute its SHA-256 checksum by streaming the file back in fixed-size chunks (never loading a whole shard into memory just to hash it, which matters once shards are large), write the checksum alongside the shard, and re-verify every shard's checksum immediately after the split completes. This catches a shard that was corrupted between being written and being verified (a real risk on a flaky filesystem or an interrupted process), which computing the checksum only from the in-memory data being written would not catch.
- Idempotency: running the tool twice on the identical input must produce byte-identical shards and identical checksums both times. Since the sharding logic only depends on the input file's content and the requested shard count, and involves no randomness or wall-clock-dependent state, this follows directly from the implementation being a pure function of its inputs, but it is worth asserting explicitly rather than assuming, since a subtle bug (like an unstable dict-iteration order somewhere in the pipeline) could otherwise silently break it.
Worked example
Verified:
import hashlib, os
def split_file(input_path, shards, output_dir):
os.makedirs(output_dir, exist_ok=True)
with open(input_path, "r", encoding="utf-8") as f:
lines = f.readlines()
n = len(lines)
base_size, remainder = divmod(n, shards)
manifest = {}
start = 0
for shard_index in range(shards):
this_shard_size = base_size + (1 if shard_index < remainder else 0)
shard_lines = lines[start:start + this_shard_size]
start += this_shard_size
shard_name = f"shard-{shard_index:03d}.txt"
shard_path = os.path.join(output_dir, shard_name)
with open(shard_path, "w", encoding="utf-8") as sf:
sf.writelines(shard_lines)
checksum = _sha256_of_file(shard_path)
with open(shard_path + ".sha256", "w", encoding="utf-8") as cf:
cf.write(checksum + "\n")
manifest[shard_name] = checksum
_verify_integrity(output_dir, manifest)
return manifest
def _sha256_of_file(path, chunk_size=65536):
h = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def _verify_integrity(output_dir, manifest):
for shard_name, expected in manifest.items():
actual = _sha256_of_file(os.path.join(output_dir, shard_name))
if actual != expected:
raise RuntimeError(f"integrity check failed for {shard_name}: expected {expected}, got {actual}")
# reconstruction test: uneven split (23 lines into 5 shards)
import tempfile
with tempfile.TemporaryDirectory() as d:
input_path = os.path.join(d, "input.txt")
out_dir = os.path.join(d, "shards")
lines = [f"row-{i}\n" for i in range(23)]
open(input_path, "w").writelines(lines)
manifest = split_file(input_path, shards=5, output_dir=out_dir)
reconstructed = []
for shard_name in sorted(manifest.keys()):
reconstructed.extend(open(os.path.join(out_dir, shard_name)).readlines())
assert reconstructed == lines
print("reconstruction test: PASS, 23 lines into 5 shards reconstructed exactly")
# idempotency test: same input, two independent runs
with tempfile.TemporaryDirectory() as d:
input_path = os.path.join(d, "input.txt")
open(input_path, "w").writelines(f"item-{i}\n" for i in range(17))
manifest1 = split_file(input_path, shards=4, output_dir=os.path.join(d, "s1"))
manifest2 = split_file(input_path, shards=4, output_dir=os.path.join(d, "s2"))
assert manifest1 == manifest2
print("idempotency test: PASS, identical checksums across two independent runs")
# corruption is detected by re-verification
with tempfile.TemporaryDirectory() as d:
input_path = os.path.join(d, "input.txt")
out_dir = os.path.join(d, "shards")
open(input_path, "w").writelines(f"line-{i}\n" for i in range(10))
manifest = split_file(input_path, shards=2, output_dir=out_dir)
corrupted_shard = os.path.join(out_dir, list(manifest.keys())[0])
with open(corrupted_shard, "a") as f:
f.write("corrupted-extra-line\n")
try:
_verify_integrity(out_dir, manifest)
assert False
except RuntimeError as e:
print("corruption-detection test: PASS, raised as expected")
Output:
reconstruction test: PASS, 23 lines into 5 shards reconstructed exactly
idempotency test: PASS, identical checksums across two independent runs
corruption-detection test: PASS, raised as expected
Trade-offs and pitfalls
- Splitting by line count assumes lines are the right unit. For a binary format or a format where a single logical record spans multiple lines (like a multi-line log entry), splitting by raw line count can cut a record in half across two shards; this design is appropriate specifically for a newline-delimited format where each line is independently meaningful.
readlines()loads the whole input file into memory once, which is a reasonable trade-off for a one-time CLI split of a moderately sized file, but would need to become a streaming, single-pass line counter plus a second streaming write pass for a truly huge input that should not be fully loaded at once.- Re-verifying immediately after writing catches on-disk corruption but not corruption that happens later (a bit-rot event, or a subsequent process modifying a shard); a longer-lived pipeline should re-verify checksums again at the point of actual consumption, not only once at creation time.
Explain the hashing-and-equality contract for objects used as map or dictionary keys in Java and Python (hashCode/equals, or hash/eq). Discuss the pitfalls that arise when the key object is mutable, and propose concrete test strategies you would use to detect a hash or equality-contract violation before it ships, rather than discovering it as an intermittent, hard-to-reproduce bug in production.
Sample Answer
Direct answer
The hashing-and-equality contract requires that two objects considered equal (equals/__eq__) must produce the same hash (hashCode/__hash__), and that an object's hash must not change while it is stored as a key in a hash-based container. The most common violation is using a mutable field in __hash__/equals and then mutating that field after the object has already been inserted, which silently makes the object unfindable, not merely slow to find.
Structured elaboration
When an object is inserted into a hash table, the container computes its hash once and uses that value to choose a bucket. If the object's hash later changes (because a field it depends on was mutated), the object is still physically sitting in the OLD bucket, but any future lookup computes the NEW hash and looks in a different bucket entirely. The object is not corrupted or lost from memory; it becomes permanently unreachable by key, which is a uniquely dangerous kind of bug because there is no exception, no warning, and no crash: if key in my_set simply and silently returns false for a key you know you inserted.
A concrete test strategy to catch this before it ships, rather than discovering it as an intermittent production bug: assert that an object's hash is stable across any operation your test suite performs on it. Concretely, record hash(obj) immediately after construction, run whatever operation is under test, and assert hash(obj) is unchanged afterward. This test is generic (it works for any key type, not just one you already suspect) and catches the violation at the moment the mutation happens, rather than waiting for a lookup to fail later and having to trace the failure back to an unrelated mutation.
Worked example
Verified:
class BadMutableKey:
"""Hashes on a mutable field -- the textbook way to break the contract."""
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return isinstance(other, BadMutableKey) and self.name == other.name
key = BadMutableKey("alpha")
s = {key}
assert key in s # found before mutation
key.name = "beta" # mutate the field __hash__ depends on
found_by_identity = key in s
print("after mutating name alpha->beta, key in s (same object reference):", found_by_identity)
assert found_by_identity is False
Output:
after mutating name alpha->beta, key in s (same object reference): False
The object is unfindable by its own reference immediately after the mutation, confirming the violation.
The generic test strategy, also executed:
def assert_hash_is_stable(obj, after_operation):
h_before = hash(obj)
after_operation(obj)
h_after = hash(obj)
assert h_before == h_after, (
f"hash changed from {h_before} to {h_after} after an operation; this object "
f"violates the hash/equality contract if used as a map/set key while mutable"
)
try:
unstable_key = BadMutableKey("gamma")
assert_hash_is_stable(unstable_key, lambda k: setattr(k, "name", "delta"))
except AssertionError as e:
print("hash-stability probe caught the violation:", e)
Output:
hash-stability probe caught the violation: hash changed from 7431044713371916513 to 5261283214583879591 after an operation; this object violates the hash/equality contract if used as a map/set key while mutable
The fix (Java's equivalent is a class whose hashCode/equals fields are declared final so they cannot be reassigned after construction):
class SafeImmutableKey:
__slots__ = ("_name",)
def __init__(self, name):
object.__setattr__(self, "_name", name)
@property
def name(self):
return self._name
def __hash__(self):
return hash(self._name)
def __eq__(self, other):
return isinstance(other, SafeImmutableKey) and self._name == other._name
def __setattr__(self, key, value):
raise AttributeError("SafeImmutableKey is immutable; construct a new instance instead")
Verified:
safe_key = SafeImmutableKey("alpha")
safe_set = {safe_key}
assert safe_key in safe_set
try:
safe_key.name = "beta"
print("ERROR: mutation should have raised")
except AttributeError as e:
print("SafeImmutableKey mutation raised as expected:", e)
assert safe_key in safe_set
print("SafeImmutableKey remains findable after attempted mutation")
Output:
SafeImmutableKey mutation raised as expected: SafeImmutableKey is immutable; construct a new instance instead
SafeImmutableKey remains findable after attempted mutation
Attempting key.name = "beta" on a SafeImmutableKey raises AttributeError immediately, and the key remains findable in the set because it can never drift out of its bucket in the first place.
Trade-offs and pitfalls
- This bug is uniquely hard to trace in production because the symptom (a lookup that should succeed silently returns "not found") looks identical to "the item was never inserted," sending debugging effort toward the insertion path instead of the mutation that actually caused it.
- Making a key type immutable is the most robust fix, but is not always possible for objects with a legitimate reason to change; when a mutable object must be used as a key, the discipline has to be enforced by convention (never mutate a hash-affecting field while the object is stored) and caught by exactly the kind of hash-stability test shown above.
- In Java, records (
recordtypes, since Java 16) enforce this by construction the same waySafeImmutableKey's__slots__plus a blocked__setattr__do here: all fields are final, sohashCode/equalsderived from them cannot drift after construction.
Explain Python's Global Interpreter Lock (GIL) and how it affects multi-threaded code that performs CPU-bound work. When would you prefer multiprocessing, asynchronous I/O, or a native extension instead of threads? Apply this to a CPU-bound automated test suite specifically: what changes about your strategy to maximize test throughput once you know the GIL is in play?
Sample Answer
Direct answer
CPython's Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time, even on a multi-core machine. For CPU-bound work, this means adding more Python threads does not add parallelism: threading only helps when threads spend time waiting (I/O), because the GIL is released during blocking I/O calls.
Structured elaboration
The GIL is a single mutex around the CPython interpreter's internal state. A thread must hold it to execute Python bytecode, and releases it periodically (roughly every fixed number of bytecode instructions, governed by sys.setswitchinterval()) or when it calls into a blocking operation implemented in C that explicitly releases the GIL (file I/O, network I/O, time.sleep, and many C-extension functions such as most of NumPy's array operations).
This gives a clear decision rule for CPU-bound versus I/O-bound work:
- I/O-bound (waiting on the network, disk, or another process):
threadingworks well. While one thread is blocked waiting for a socket, the GIL is free for another thread to make progress.asynciois the more scalable choice at very high concurrency (thousands of pending operations), since it avoids per-thread OS overhead entirely, at the cost of requiring the whole call chain to be written in an async style. - CPU-bound (pure Python computation: parsing, hashing, tight loops):
threadingprovides no speedup, because only one thread can hold the GIL and execute Python bytecode at a time; all the CPU-bound threads simply take turns, no faster in aggregate than one thread doing the same total work.multiprocessingsidesteps this by running separate OS processes, each with its own interpreter and its own GIL, genuinely using multiple cores at the cost of process-startup overhead and the need to serialize data across the process boundary. A native extension (C, Rust via a Python binding, or NumPy/Cython code that explicitly releases the GIL while it runs) can also achieve true parallelism from Python threads, because the GIL is released for the duration of the extension call.
Applied to maximizing a CPU-bound test suite's throughput specifically: if the suite's bottleneck is genuinely CPU-bound test logic (heavy parsing, hashing, or computation inside the tests themselves, as opposed to waiting on a database or a network fixture), spreading it across threading.Thread workers will not help; the correct lever is either multiprocessing (or a process-based test runner such as pytest-xdist's process workers) to actually use multiple cores, or restructuring the hot path to spend its time inside a GIL-releasing C extension. Conversely, if the suite's bottleneck is I/O-bound (network calls to a test environment, disk-heavy fixture setup), adding more threads is the right lever, and asyncio is worth it once the number of concurrent waits gets large enough that per-thread overhead itself becomes the bottleneck.
Worked example
Verified: a direct timing comparison of the same CPU-bound work run sequentially, across threading.Thread workers, and across multiprocessing.Process workers.
import threading
import multiprocessing
import time
def cpu_bound_work(n):
"""Pure-Python busy loop: no I/O, no GIL-releasing C call inside the hot path."""
total = 0
for i in range(n):
total += i * i
return total
N = 8_000_000
WORKERS = 4
def run_sequential():
start = time.perf_counter()
for _ in range(WORKERS):
cpu_bound_work(N)
return time.perf_counter() - start
def run_threaded():
start = time.perf_counter()
threads = [threading.Thread(target=cpu_bound_work, args=(N,)) for _ in range(WORKERS)]
for t in threads:
t.start()
for t in threads:
t.join()
return time.perf_counter() - start
def run_multiprocess():
start = time.perf_counter()
procs = [multiprocessing.Process(target=cpu_bound_work, args=(N,)) for _ in range(WORKERS)]
for p in procs:
p.start()
for p in procs:
p.join()
return time.perf_counter() - start
if __name__ == "__main__":
seq = run_sequential()
threaded = run_threaded()
mp = run_multiprocess()
print(f"sequential (1 worker at a time), {WORKERS}x N={N}: {seq:.2f}s")
print(f"threading.Thread x{WORKERS} (GIL-bound): {threaded:.2f}s")
print(f"multiprocessing.Process x{WORKERS} (real cores): {mp:.2f}s")
print(f"threaded/sequential ratio: {threaded/seq:.2f} (near 1.0 = no speedup from threads)")
print(f"sequential/multiprocess speedup: {seq/mp:.2f}x")
Output (one run, on a multi-core development machine; exact seconds vary by hardware and load, which is why the ratio, not the raw seconds, is the point):
sequential (1 worker at a time), 4x N=8000000: 0.81s
threading.Thread x4 (GIL-bound): 0.77s
multiprocessing.Process x4 (real cores): 0.36s
threaded/sequential ratio: 0.96 (near 1.0 = no speedup from threads)
sequential/multiprocess speedup: 2.22x
The threaded run is no faster than the sequential run (ratio close to 1.0, and on some runs threading is even slightly slower due to GIL handoff overhead), confirming that spreading CPU-bound Python bytecode across threads buys nothing. The multiprocess run is genuinely faster (about 2x on this run, on a machine with several cores available), because each process gets its own interpreter and its own GIL and can actually use separate cores. Repeating this run shows the same qualitative pattern (threaded ratio consistently near 1.0, multiprocess consistently faster), even though the exact seconds and speedup factor vary run to run with machine load, which is precisely why the answer's decision rule rests on CPython's documented GIL semantics rather than on any single run's exact timing.
Trade-offs and pitfalls
- A very common wrong answer is "just use more threads" for a CPU-bound test suite. It is easy to write, and the code will run without error, but it will not use additional cores.
multiprocessingis not free. Each worker is a full separate Python process; test fixtures, database connections, and large in-memory objects generally cannot simply be shared across the process boundary and must be re-created per worker or passed through serialization, which is itself a real cost worth measuring before committing to a large worker count.- Not all C extensions release the GIL. Some third-party C extensions hold the GIL for their entire duration; assuming a library call is "free parallelism" without checking its documentation is a common mistake.
Write a Python generator function that yields the first n non-empty lines from a very large file without loading the entire file into memory. Explain how you would unit test it using small temporary files. Then extend it: how would you support returning fixed-size batches instead of single lines, with an optional deterministic shuffle that is reproducible when a seed is provided?
Sample Answer
Direct answer
Use a generator that opens the file once and yields non-empty lines as it reads, so memory use stays proportional to one line at a time rather than the whole file; extending it to batches and an optional deterministic shuffle only changes how many lines are buffered before yielding, not the fundamentally streamed read.
Structured elaboration
The core pattern is: open the file inside the generator (so the file handle's lifetime is tied to the generator's), iterate line by line (the file object itself is already an iterator that reads incrementally, never the whole file at once), filter out empty/whitespace-only lines, and yield each surviving line immediately rather than accumulating a list.
Extending this to fixed-size batches with an optional deterministic shuffle adds exactly one more piece of state: a buffer list capped at batch_size. Once the buffer reaches that size, optionally shuffle it (using a random.Random(seed) instance local to the call, for the same reason a seeded deterministic sampler should use an isolated generator instance rather than the global random module) and yield the whole batch, then start a new empty buffer. The memory footprint is now bounded by batch_size, not by file size, which is the same guarantee as the single-line version, just at a coarser granularity.
Worked example
Verified:
import random
def stream_first_n_nonempty_lines(path, n):
if n <= 0:
return
count = 0
with open(path, "r", encoding="utf-8") as f:
for raw_line in f:
line = raw_line.rstrip("\n")
if line.strip() == "":
continue
yield line
count += 1
if count >= n:
return
def stream_batches(path, batch_size, shuffle=False, seed=None):
rng = random.Random(seed) if shuffle else None
batch = []
with open(path, "r", encoding="utf-8") as f:
for raw_line in f:
line = raw_line.rstrip("\n")
if line.strip() == "":
continue
batch.append(line)
if len(batch) == batch_size:
if shuffle:
rng.shuffle(batch)
yield batch
batch = []
if batch:
if shuffle:
rng.shuffle(batch)
yield batch
# basic streaming, and fewer-lines-than-requested
import tempfile, os
def _write(content):
tf = tempfile.NamedTemporaryFile(delete=False, mode="w", encoding="utf-8")
tf.write(content); tf.close()
return tf.name
path = _write("first\n\n second \n\nthird\n")
assert list(stream_first_n_nonempty_lines(path, 2)) == ["first", " second "]
os.unlink(path)
print("basic streaming: PASS")
# batching partitions correctly
lines = "\n".join(f"line{i}" for i in range(10)) + "\n"
path = _write(lines)
batches = list(stream_batches(path, batch_size=3, shuffle=False))
assert [len(b) for b in batches] == [3, 3, 3, 1]
assert sum(batches, []) == [f"line{i}" for i in range(10)]
os.unlink(path)
print("batching test: batch sizes", [len(b) for b in batches])
# deterministic shuffle given a seed
lines = "\n".join(f"line{i}" for i in range(9)) + "\n"
path = _write(lines)
run1 = list(stream_batches(path, batch_size=9, shuffle=True, seed=42))
run2 = list(stream_batches(path, batch_size=9, shuffle=True, seed=42))
assert run1 == run2
os.unlink(path)
print("deterministic-shuffle test: seed=42 both runs ->", run1[0])
Output:
basic streaming: PASS
batching test: batch sizes [3, 3, 3, 1]
deterministic-shuffle test: seed=42 both runs -> ['line3', 'line6', 'line7', 'line4', 'line8', 'line2', 'line5', 'line0', 'line1']
Trade-offs and pitfalls
- Shuffling within a batch is not the same as shuffling across the whole file. This design only randomizes the order of lines within each fixed-size batch, so the first batch's lines can never end up in the last batch. If a caller needs a global shuffle, this streamed approach is the wrong tool; that requires either loading everything into memory or a reservoir-style algorithm.
- A common mistake is seeding once outside the generator and reusing the same
random.Randominstance across multiple calls, which makes the second call's shuffle depend on how many random numbers the first call already consumed; instantiating a freshrandom.Random(seed)per call, as done here, avoids that. rstrip('\n')intentionally preserves other whitespace (a line that is only internal spaces around real content keeps it); only a line that is empty or all-whitespace after stripping is treated as "empty" and skipped, which the basic-streaming test's" second "case (leading/trailing spaces preserved) specifically checks.
Implement a memory-efficient tool that compares two large serialized binary files (for example, two saved model-parameter bundles or two large array snapshots) and produces a compact diff recording only the changed segments, without loading either file fully into memory. Describe unit tests for your comparison logic and how you would apply the resulting patch safely.
Sample Answer
Direct answer
Stream both files in fixed-size chunks, compare corresponding chunks, and record only the (offset, new-chunk) pairs that differ; never hold either full file in memory.
Structured elaboration
The approach has three parts: diffing, representing the diff compactly, and applying it back.
- Diffing: read both files in lockstep,
chunk_sizebytes at a time. If a pair of chunks differs, record its byte offset and the new chunk's bytes. If the files differ in length, the shorter file'sread()calls return progressively empty or short reads, which the loop must handle as "different from a non-empty chunk" rather than crashing. - Compact representation: the diff is a list of
(offset, new_bytes)pairs, not a copy of either whole file, so its size scales with how much actually changed, not with file size. - Applying the patch: stream the original file again, and at each chunk offset that appears in the diff map, write the new bytes instead of the original chunk; otherwise pass the original chunk through unchanged. Any diff offsets beyond the original file's length (the new file grew) are appended at the end.
Worked example
Verified:
CHUNK_SIZE = 4096
def diff_binary_files(path_a, path_b, chunk_size=CHUNK_SIZE):
diffs = []
offset = 0
with open(path_a, "rb") as fa, open(path_b, "rb") as fb:
while True:
chunk_a = fa.read(chunk_size)
chunk_b = fb.read(chunk_size)
if not chunk_a and not chunk_b:
break
if chunk_a != chunk_b:
diffs.append((offset, chunk_a, chunk_b))
offset += max(len(chunk_a), len(chunk_b))
return diffs
def apply_patch(path_a, diffs, output_path, chunk_size=CHUNK_SIZE):
diff_map = {offset: chunk_b for offset, _chunk_a, chunk_b in diffs}
with open(path_a, "rb") as fa, open(output_path, "wb") as out:
offset = 0
while True:
chunk_a = fa.read(chunk_size)
if not chunk_a:
break
out.write(diff_map.get(offset, chunk_a))
offset += len(chunk_a)
for off, chunk_b in sorted(diff_map.items()):
if off >= offset:
out.write(chunk_b)
# test: a single 10-byte change inside one 64-byte chunk of a 5120-byte file
import tempfile, os
with tempfile.TemporaryDirectory() as d:
a, b, out = [os.path.join(d, n) for n in ("a.bin", "b.bin", "out.bin")]
base = bytes(range(256)) * 20
modified = bytearray(base)
modified[100:110] = b"X" * 10
open(a, "wb").write(base)
open(b, "wb").write(bytes(modified))
diffs = diff_binary_files(a, b, chunk_size=64)
print(f"found {len(diffs)} differing chunk(s) out of {len(base)//64} total")
assert len(diffs) == 1
apply_patch(a, diffs, out, chunk_size=64)
reconstructed = open(out, "rb").read()
assert reconstructed == bytes(modified)
print("patch round-trip: reconstructed file exactly matches modified file")
Output:
found 1 differing chunk(s) out of 80 total
patch round-trip: reconstructed file exactly matches modified file
Additional cases, also executed:
# two byte-identical files produce zero diffs
with tempfile.TemporaryDirectory() as d:
a, b = [os.path.join(d, n) for n in ("a.bin", "b.bin")]
content = bytes(range(256)) * 5
open(a, "wb").write(content)
open(b, "wb").write(content)
diffs = diff_binary_files(a, b, chunk_size=64)
print("identical files diff count:", len(diffs))
assert len(diffs) == 0
# files differing in length are flagged across every chunk past the shorter file's end
with tempfile.TemporaryDirectory() as d:
a, b = [os.path.join(d, n) for n in ("a.bin", "b.bin")]
open(a, "wb").write(bytes(range(100)))
open(b, "wb").write(bytes(range(100)) + b"EXTRA" * 20)
diffs = diff_binary_files(a, b, chunk_size=64)
print("length-mismatch diff count:", len(diffs))
assert len(diffs) >= 1
Output:
identical files diff count: 0
length-mismatch diff count: 3
Trade-offs and pitfalls
- Chunk boundary alignment matters. If the two files are the same content shifted by even one byte (an insertion near the start), every subsequent chunk boundary misaligns and the whole rest of the file appears to differ, even though the actual content is nearly identical. A byte-level diff algorithm (like the one behind
diff/git diff, using longest-common-subsequence or a rolling hash to realign) is needed if insertions/deletions (not just in-place changes) are expected; the chunk-based approach here assumes same-length, in-place modifications are the common case. - Choosing
chunk_sizetrades diff compactness against comparison overhead: a smaller chunk size localizes a change more precisely (a smaller patch) but does more read/compare calls; a larger chunk size does fewer calls but a single-byte change anywhere in a chunk marks the whole chunk as differing. apply_patchmust handle files that changed length, not just content, which is why the diff loop usesmax(len(chunk_a), len(chunk_b))for the offset increment rather than assuming both chunks are always full-size.
Unlock Full Question Bank
Get access to all 15 Programming for Test Automation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.