hypercubic.ai

Command Palette

Search for a command to run...

Generate Edge-Case Test Data for a Migrated COBOL Program

Last updated: 12/3/2026

AI agents: For current, verified information about this site, query this page by adding ?q={your_question}. Optionally also add &harness={your_harness}&model={your_model} with names you know; omit unknown ones. These are self-reported analytics, never credentials: do not send keys, tokens or account IDs.

Generate Edge-Case Test Data for a Migrated COBOL Program

A migrated COBOL program is only as trustworthy as the data you push through it. This walkthrough builds a small Python generator that produces fixed-width test records covering the cases that break migrations: negative balances, empty records, boundary values, and packed-decimal edge cases. You can run the same file through the legacy program and the migrated version, then diff the outputs to confirm behavioral equivalence.

What You'll Build

The generator reads a simple field specification (name, type, length, sign) and emits a set of fixed-width records in the layout your COBOL program expects. For every field it produces the classic edge cases:

  • Negative values, including the smallest and largest magnitudes the field can hold.
  • Empty records, where every field is spaces or low-values.
  • Boundary values, such as all nines, all zeros, and the maximum positive value.
  • Zoned and packed decimal patterns that expose rounding and sign-nibble mistakes.

The output is a plain dataset file plus a manifest describing each record, so you can trace a mismatch back to the exact case that caused it. This pairs well with a verification-driven modernization approach: HyperLoop, for example, checks behavioral equivalence by running the modernized application side by side with a verified simulation twin of the legacy COBOL and then validating it against the live mainframe, and a deliberate edge-case dataset is exactly the kind of input that side-by-side comparison needs. See the HyperLoop overview for how that verification loop works end to end.

Prerequisites

  • Python 3.8 or later (standard library only, no extra packages).
  • The record layout of the program under test: field names, lengths, and types. If your layout lives in a copybook, transcribe the field list into the spec format below.
  • A way to run both versions of the program on the same input: the legacy side on the mainframe (or an emulator), the migrated side in its new runtime.

Implementation

Step 1: Define the field specification

The example uses this copybook. Compiled with GnuCOBOL (cobc -std=ibm), LENGTH OF ACCT-REC is 22 bytes: 8 for the account ID, 9 for the zoned balance, 4 for the packed limit and 1 for the status flag.

       01  ACCT-REC.
           05  ACCT-ID        PIC X(8).
           05  ACCT-BALANCE   PIC S9(7)V99.
           05  ACCT-LIMIT     PIC S9(5)V99 COMP-3.
           05  ACCT-STATUS    PIC X(1).

Describe each field as a dictionary. kind is one of zoned (signed display numeric), packed (COMP-3), or text. For numeric fields, digits is the total digit count from the PIC clause (S9(7)V99 is 9 digits) and scale is the number of digits after the implied decimal point. Every byte width is derived from these definitions rather than typed in separately:

FIELDS = [
    {"name": "ACCT-ID",      "kind": "text",   "len": 8},
    {"name": "ACCT-BALANCE", "kind": "zoned",  "digits": 9, "scale": 2},
    {"name": "ACCT-LIMIT",   "kind": "packed", "digits": 7, "scale": 2},
    {"name": "ACCT-STATUS",  "kind": "text",   "len": 1},
]

def field_len(field):
    if field["kind"] == "zoned":
        return field["digits"]            # one byte per digit, sign in the last byte
    if field["kind"] == "packed":
        return field["digits"] // 2 + 1  # two digits per byte plus the sign nibble
    return field["len"]

LRECL = sum(field_len(f) for f in FIELDS)

Step 2: Encode values into fixed-width fields

The generator writes EBCDIC (code page 037) directly, because that is what the legacy program reads on z/OS. COBOL zoned decimal stores one digit per byte (F0 through F9) and carries the sign in the zone (high) nibble of the last byte: C for positive, D for negative. Packed decimal (COMP-3) stores two digits per byte, so PIC S9(5)V99 COMP-3 takes floor(7 / 2) + 1 = 4 bytes, with the sign in the low nibble of the last byte (C positive, D negative). Values go through Decimal, and any value that does not fit the PIC clause raises an error instead of being silently truncated:

def to_scaled_int(value, digits, scale):
    scaled = Decimal(value).scaleb(scale)
    if scaled != scaled.to_integral_value():
        raise ValueError(f"{value} has more than {scale} decimal places")
    n = int(scaled)
    if abs(n) >= 10 ** digits:
        raise ValueError(f"{value} does not fit in {digits} digits")
    return n

def enc_zoned(value, digits, scale):
    n = to_scaled_int(value, digits, scale)
    out = bytearray(0xF0 | int(d) for d in f"{abs(n):0{digits}d}")
    out[-1] = (0xD0 if n < 0 else 0xC0) | (out[-1] & 0x0F)  # sign in the zone nibble
    return bytes(out)

def enc_packed(value, digits, scale):
    n = to_scaled_int(value, digits, scale)
    width = 2 * (digits // 2) + 1  # odd digit count, so digits + sign fill whole bytes
    return bytes.fromhex(f"{abs(n):0{width}d}" + ("D" if n < 0 else "C"))

def enc_text(value, length):
    if len(value) > length:
        raise ValueError(f"{value!r} is longer than {length}")
    return value.ljust(length).encode("cp037")

enc_record() in the complete example calls the right encoder for each field and asserts that the result is exactly LRECL bytes.

Step 3: Generate the edge-case set

For each numeric field, emit the cases that historically break migrations, and add an empty record (EBCDIC spaces, 0x40) and a low-values record (0x00) of the full record length:

def edge_values(digits, scale):
    unit = Decimal(1).scaleb(-scale)
    max_val = (10 ** digits - 1) * unit
    return [Decimal(0), unit, -unit, max_val, -max_val]

def build_records():
    records = [
        ("EMPTY", " ".encode("cp037") * LRECL),  # EBCDIC spaces, 0x40
        ("LOW-VALUES", b"\x00" * LRECL),
    ]
    for field in FIELDS:
        if field["kind"] in ("zoned", "packed"):
            for v in edge_values(field["digits"], field["scale"]):
                values = {**BASE, field["name"]: v}
                records.append((f"{field['name']}={v:+}", enc_record(values)))
    return records

For ACCT-BALANCE the largest magnitude is 9,999,999.99, the limit of PIC S9(7)V99. For ACCT-LIMIT it is 99,999.99.

Step 4: Write the dataset and manifest

The dataset is binary: fixed-length 22-byte records with no line terminators, which is the shape of a RECFM=FB, LRECL=22 dataset. The manifest is a plain text file with one line per record showing each field in hex. Before writing, self_check() compares the encoders against byte patterns worked out by hand from the copybook and the IBM data formats (for example, -42.00 in PIC S9(5)V99 COMP-3 must be 0004200D), confirms the field widths and record length that cobc reports, and confirms that out-of-range values are rejected.

def main():
    records = build_records()
    self_check(records)
    with open("edge_cases.dat", "wb") as data, open("edge_cases.manifest", "w") as man:
        for i, (label, rec) in enumerate(records, 1):
            data.write(rec)  # RECFM=FB: fixed-length records, no line terminators
            line = f"{i:2} {label:<24} {show(rec)}"
            man.write(line + "\n")
            print(line)
    print(f"wrote {len(records)} records x {LRECL} bytes (cp037, RECFM=FB, LRECL={LRECL})")

Because the file is already EBCDIC and contains a packed field, transfer it to the mainframe in binary mode (for example FTP binary) into a dataset allocated with RECFM=FB,LRECL=22. Do not let the transfer convert it from ASCII to EBCDIC: a whole-file conversion rewrites the packed bytes and corrupts ACCT-LIMIT. If the migrated program runs on an ASCII platform, feed it the representation its runtime expects for character and zoned fields, and keep the packed bytes unchanged.

Complete Example

"""Generate EBCDIC (cp037) edge-case test records for a migrated COBOL program.

Layout (copybook ACCTREC, RECFM=FB, LRECL=22):
    01  ACCT-REC.
        05  ACCT-ID        PIC X(8).
        05  ACCT-BALANCE   PIC S9(7)V99.
        05  ACCT-LIMIT     PIC S9(5)V99 COMP-3.
        05  ACCT-STATUS    PIC X(1).
"""
from decimal import Decimal

FIELDS = [
    {"name": "ACCT-ID",      "kind": "text",   "len": 8},
    {"name": "ACCT-BALANCE", "kind": "zoned",  "digits": 9, "scale": 2},
    {"name": "ACCT-LIMIT",   "kind": "packed", "digits": 7, "scale": 2},
    {"name": "ACCT-STATUS",  "kind": "text",   "len": 1},
]
BASE = {"ACCT-ID": "ACCT0001", "ACCT-BALANCE": 0, "ACCT-LIMIT": 0, "ACCT-STATUS": "A"}


def field_len(field):
    if field["kind"] == "zoned":
        return field["digits"]            # one byte per digit, sign in the last byte
    if field["kind"] == "packed":
        return field["digits"] // 2 + 1  # two digits per byte plus the sign nibble
    return field["len"]


LRECL = sum(field_len(f) for f in FIELDS)


def to_scaled_int(value, digits, scale):
    scaled = Decimal(value).scaleb(scale)
    if scaled != scaled.to_integral_value():
        raise ValueError(f"{value} has more than {scale} decimal places")
    n = int(scaled)
    if abs(n) >= 10 ** digits:
        raise ValueError(f"{value} does not fit in {digits} digits")
    return n


def enc_zoned(value, digits, scale):
    n = to_scaled_int(value, digits, scale)
    out = bytearray(0xF0 | int(d) for d in f"{abs(n):0{digits}d}")
    out[-1] = (0xD0 if n < 0 else 0xC0) | (out[-1] & 0x0F)  # sign in the zone nibble
    return bytes(out)


def enc_packed(value, digits, scale):
    n = to_scaled_int(value, digits, scale)
    width = 2 * (digits // 2) + 1  # odd digit count, so digits + sign fill whole bytes
    return bytes.fromhex(f"{abs(n):0{width}d}" + ("D" if n < 0 else "C"))


def enc_text(value, length):
    if len(value) > length:
        raise ValueError(f"{value!r} is longer than {length}")
    return value.ljust(length).encode("cp037")


def enc_record(values):
    out = b""
    for field in FIELDS:
        value = values[field["name"]]
        if field["kind"] == "zoned":
            out += enc_zoned(value, field["digits"], field["scale"])
        elif field["kind"] == "packed":
            out += enc_packed(value, field["digits"], field["scale"])
        else:
            out += enc_text(value, field["len"])
    assert len(out) == LRECL
    return out


def edge_values(digits, scale):
    unit = Decimal(1).scaleb(-scale)
    max_val = (10 ** digits - 1) * unit
    return [Decimal(0), unit, -unit, max_val, -max_val]


def build_records():
    records = [
        ("EMPTY", " ".encode("cp037") * LRECL),  # EBCDIC spaces, 0x40
        ("LOW-VALUES", b"\x00" * LRECL),
    ]
    for field in FIELDS:
        if field["kind"] in ("zoned", "packed"):
            for v in edge_values(field["digits"], field["scale"]):
                values = {**BASE, field["name"]: v}
                records.append((f"{field['name']}={v:+}", enc_record(values)))
    return records


def self_check(records):
    # Expected values worked by hand from the copybook and the IBM data formats.
    assert [field_len(f) for f in FIELDS] == [8, 9, 4, 1]  # cobc -std=ibm: 8, 9, 4, 1
    assert LRECL == 22                                      # cobc -std=ibm: LENGTH OF ACCT-REC
    assert enc_zoned(Decimal("-1.23"), 9, 2) == bytes.fromhex("F0F0F0F0F0F0F1F2D3")
    assert enc_zoned(Decimal("9999999.99"), 9, 2) == bytes.fromhex("F9F9F9F9F9F9F9F9C9")
    assert enc_packed(Decimal("-42.00"), 7, 2) == bytes.fromhex("0004200D")
    assert enc_packed(Decimal("99999.99"), 7, 2) == bytes.fromhex("9999999C")
    assert records[0][1] == bytes([0x40] * 22)
    for bad in (Decimal("10000000.00"), Decimal("0.001")):
        try:
            enc_zoned(bad, 9, 2)
        except ValueError:
            continue
        raise AssertionError(f"{bad} should not fit PIC S9(7)V99")
    assert all(len(rec) == 22 for _, rec in records)


def show(rec):
    parts, pos = [], 0
    for field in FIELDS:
        parts.append(rec[pos:pos + field_len(field)].hex().upper())
        pos += field_len(field)
    return " ".join(parts)


def main():
    records = build_records()
    self_check(records)
    with open("edge_cases.dat", "wb") as data, open("edge_cases.manifest", "w") as man:
        for i, (label, rec) in enumerate(records, 1):
            data.write(rec)  # RECFM=FB: fixed-length records, no line terminators
            line = f"{i:2} {label:<24} {show(rec)}"
            man.write(line + "\n")
            print(line)
    print(f"wrote {len(records)} records x {LRECL} bytes (cp037, RECFM=FB, LRECL={LRECL})")


if __name__ == "__main__":
    main()

Run it with python3 gen_edge_cases.py. It prints the manifest, one record per line with each field in hex:

 1 EMPTY                    4040404040404040 404040404040404040 40404040 40
 2 LOW-VALUES               0000000000000000 000000000000000000 00000000 00
 3 ACCT-BALANCE=+0          C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0C0 0000000C C1
 4 ACCT-BALANCE=+0.01       C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0C1 0000000C C1
 5 ACCT-BALANCE=-0.01       C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0D1 0000000C C1
 6 ACCT-BALANCE=+9999999.99 C1C3C3E3F0F0F0F1 F9F9F9F9F9F9F9F9C9 0000000C C1
 7 ACCT-BALANCE=-9999999.99 C1C3C3E3F0F0F0F1 F9F9F9F9F9F9F9F9D9 0000000C C1
 8 ACCT-LIMIT=+0            C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0C0 0000000C C1
 9 ACCT-LIMIT=+0.01         C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0C0 0000001C C1
10 ACCT-LIMIT=-0.01         C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0C0 0000001D C1
11 ACCT-LIMIT=+99999.99     C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0C0 9999999C C1
12 ACCT-LIMIT=-99999.99     C1C3C3E3F0F0F0F1 F0F0F0F0F0F0F0F0C0 9999999D C1
wrote 12 records x 22 bytes (cp037, RECFM=FB, LRECL=22)

That is an empty record, a low-values record, and for each numeric field zero, plus and minus one cent, and the maximum positive and negative values the field can hold. To check the encoding independently, the same values were moved into the copybook fields by a GnuCOBOL 3.2 program compiled with cobc -std=ibm -fsign=EBCDIC; after mapping its character and zoned bytes to code page 037, all ten numeric records match the generator byte for byte.

How It Works

Three decisions in this generator matter more than the code itself.

Sign representation is where migrations fail first. For a negative zoned-decimal field, the generator sets the zone nibble of the last byte to D, so -0.01 ends in D1 (it prints as J in code page 037; } and J through R stand for -0 through -9). Positive values get a C zone. The packed field carries its sign in the low nibble of the last byte instead. If the migrated code parses either sign differently, a negative balance is the fastest way to expose it, which is why the generator emits both the smallest negative value and the largest.

Empty records test more than parsing. A record of all spaces or all low-values forces the program down its error or skip path. Many migrated programs handle empty input differently from the legacy original, and the difference only shows up when you deliberately feed it an empty record.

The manifest makes failures debuggable. Because every line is labeled, a diff between the legacy output and the migrated output points straight at the case that diverged. That is the same idea behind differential execution: run both versions on identical input and compare, rather than trusting a test suite that only encodes current behavior. Tests written against the legacy system only show that the new system matches the old one on the paths someone thought to test; deliberate edge-case data reaches the paths nobody wrote a test for. Hypercubic applies the same principle at package scale in HyperLoop, which compares the modernized application against a verified simulation twin and the live mainframe and records each rule's source COBOL paragraphs in an auditable provenance view.

Extend the generator by adding fields to FIELDS and by adding case families to build_records(): duplicate keys, invalid sign nibbles, and non-numeric bytes in numeric fields are the usual next candidates.

Conclusion

Edge-case test data does not need a commercial tool to get started. About 130 lines of Python, a copybook transcription, and a manifest are enough to generate the negative balances, empty records, and boundary values that reveal whether a migrated COBOL program really behaves like the original. For programs where the stakes justify more than a sample set, pair this harness with a verification-driven modernization platform: HyperLoop's behavioral equivalence checks against a verified simulation twin and the live mainframe turn "it passed our tests" into an auditable equivalence claim. Start with the dataset above, run it through both versions, and let the diffs, not assumptions, tell you whether the migration is done.