DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • AI Agent Harness Lock-In: 5 Portability Tests to Run Before You Commit
  • Does 100% Code Coverage Mean Tested?
  • Do We Test Just to Find Bugs?
  • Reading Playwright Traces When Browser Automation Fails

Trending

  • How to Build a Brand Monitoring Dashboard With SerpApi and Python
  • Database Normalization, ACID Properties, and SCDs: A Comprehensive Guide
  • Your Agent Trusts That Wiki. Should It?
  • Building Offline-First iOS Applications with Local Data Storage
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Green Unit Tests Are a Comfort Blanket

Green Unit Tests Are a Comfort Blanket

A green test suite checks only the inputs you imagined. Point Hypothesis at a parser and it finds the garbage you did not, before production does.

By 
Mikhail Golikov user avatar
Mikhail Golikov
·
Jul. 20, 26 · Analysis
Likes (0)
Comment
Save
Tweet
Share
464 Views

Join the DZone community and get the full member experience.

Join For Free

My converter has a test suite. It was green. Every example I could think of went in, the right pytest file came out, and I shipped it to PyPI as 1.0. Weeks later it sits there marked Production/Stable.

Then I pointed a fuzzer at it, and it stopped being so quiet.

The Blind Spot in Example Tests

Unit tests check the inputs you thought of. That is their whole nature: you sit down, you imagine how the code gets used, you write an example for each case. The cases you imagine tend to be the cases the code already handles, because you wrote the code and the test in the same afternoon, with the same blind spots.

A converter makes that worse. postman2pytest takes a Postman collection, a JSON file, and turns it into a runnable pytest suite. The input is not something I control. It is a file a stranger exports from a tool, edits by hand, truncates over a flaky download, or generates from a script that had a bug. The real test suite for a parser is the set of files you did not write.

So I stopped writing examples and let a machine write them for me.

Letting Hypothesis Do the Imagining

Hypothesis (hypothesis.readthedocs.io) is property-based testing for Python. Instead of one example, you describe the shape of the input and assert a property that must hold for all of them. It then generates hundreds of cases, including the mean ones you would never type out.

For a parser, the property is simple to state. Feed it any well-formed JSON, whatever its shape. It should do exactly one of two things: return a list of parsed tests, or raise a clear error that tells the user what is wrong. It must never fall over with a raw stack trace.

JSON
 
import json
from hypothesis import given, strategies as st

json_values = st.recursive(
    st.none() | st.booleans() | st.integers() | st.text(),
    lambda children: st.lists(children) | st.dictionaries(st.text(), children),
)

@given(value=json_values)
def test_parser_is_graceful_on_any_json(value, tmp_path):
    path = tmp_path / "in.json"
    path.write_text(json.dumps(value))
    try:
        result = parse_collection(path)
    except ValueError:
        return  # the one allowed failure: a clear, typed error
    assert isinstance(result, list)


Then I ran it.

What It Found

The parser handled every real Postman collection the same as before. The fuzzer never touched valid input. It broke my handling of garbage, in five distinct shapes.

A collection whose top level was a list instead of an object. A collection whose info block was a string. An item that was a bare number where the code expected a dict. A folder nested deep enough that the recursion bottomed out. And a payload so deeply nested that json.loads itself blew the stack before my code ran at all.

In each case the user would have seen an AttributeError, a TypeError, or a RecursionError, with an internal stack trace and no idea what to fix. None of those is a useful message. The tool knew the input was wrong. It just had no manners about saying so.

What sold me on the method was the shrinking. When Hypothesis finds a failure, it does not hand you the random 4KB blob that happened to trip the code. It shrinks the case to the smallest input that still fails, so the report is a two-line collection, not a wall of generated noise. That is the difference between a bug you can read and a bug you file under "investigate later". Each of the five failures arrived as a minimal reproducer I could paste straight into a regression test, which is how plugging them stayed a one-afternoon job rather than a week of bisecting.

The Fix Is a Contract, Not a Patch

Plugging the five holes was the boring part. The contract underneath them was the real work: valid collection in, pytest suite out; anything else, one clear ValueError that names the problem. Degrade, do not crash.

That turned into a few isinstance checks at the boundaries, a depth limit on folder recursion, and wrapping the top-level json.loads so a stack-busting document becomes a readable "this file is nested too deeply to parse" instead of a traceback. The same review on my other parser, secure-log2test, which reads Kibana log exports, turned up the same family of gaps in the same afternoon. Same shape of bug, same shape of fix.

What I Actually Learned

"Production/Stable" is a statement about the API, not about the input. It never promised to survive a corrupt file, and I had let people assume it did.

And finding bugs with a fuzzer is the fuzzer doing its job. Point Hypothesis at a parser and it finds nothing? You probably did not let it generate anything nasty enough. The bugs are the evidence the method works.

If your tool reads a file someone else made, your unit tests are a comfort blanket. Spend twenty lines on a property test before you trust them. The input you did not write is the one that finds you in production.

postman2pytest and secure-log2test are MIT-licensed on PyPI. The fuzz tests are in each repo if you want a template to copy.

This article was originally published on dev.to.

Testing

Published at DZone with permission of Mikhail Golikov. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • AI Agent Harness Lock-In: 5 Portability Tests to Run Before You Commit
  • Does 100% Code Coverage Mean Tested?
  • Do We Test Just to Find Bugs?
  • Reading Playwright Traces When Browser Automation Fails

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook