#67 · Errors and security

Find the bug · #67 · Errors and security Easy Python

Failed uploads report success

A bulk upload says everything went fine, even when some files were rejected.

On this page

The report

Bug report

A bulk upload sends each file to storage and lists the ones that failed. It always says “All files uploaded”, but some files never arrive, so users think their documents are safe when they aren’t.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
def upload_all(files, upload):
    """Uploads every file; returns the names of the ones that failed."""
    failed = []
    for name in files:
        try:
            upload(name)
        except Exception:
            pass
    return failed

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
def upload(name):
    if name.endswith(".exe"):
        raise ValueError("blocked file type")

print(upload_all(["a.png", "b.exe", "c.pdf"], upload))

It prints

[]

It should print

['b.exe']
Show the answer: the bug, the fix, and how you’d find it

The bug (line 8)

Line 8 catches every error and does nothing: pass. The failure is swallowed, the file is never added to failed, and the function reports success. An except must either handle the error properly or let it through; here, record which file failed.

The fix

5        try:6            upload(name)7        except Exception:8            pass8            failed.append(name)9    return failed

How you’d find it

  1. Reproduce with one file that the storage rejects: the result says nothing failed.
  2. So the error happened and vanished. Follow it: the except catches it and runs pass.
  3. Check that nothing else adds to failed: nothing does. The list is always empty.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

def upload(name):
    if name.startswith("bad"):
        raise OSError("storage refused it")

assert upload_all(["ok.txt", "bad.txt"], upload) == ["bad.txt"]
assert upload_all([], upload) == []

Where else this bites

  • JavaScript’s empty catch {} and Java’s empty catch blocks.
  • Promises with no .catch, where the failure disappears into the logs.
Your progress stays on this device.