1. Start a text-checking product
You will build a product that reads text and checks the format of demo markers. A marker here is a labeled word the program recognizes. Output shows counts and positions rather than marker values. Do not use personal information or real keys.
You need Python 3 and a text editor. Check installation with python3 --version. If unavailable, install Python 3 and reopen the terminal. The actual run used Python 3.14.4. The program handles local files only; there are no packages, accounts or network calls.
Create numune-yoxla-v1. The tree below shows three main files; do not save the tree itself. Select UTF-8 and watch for hidden .txt extensions. The program creates report.json later; do not create it beforehand.
numune-yoxla-v1/
app.py
demo.txt
test_app.py
2. Put the format rule in app.py
Save the complete code as app.py. CANDIDATE locates words starting with DEMO_KEY_. FORMAT requires exactly eight uppercase Latin letters or digits after it. fullmatch checks the whole candidate word; having a matching beginning is insufficient.
inspect_text counts lines and columns from 1. valid refers only to our format rule. The JSON report does not contain the marker value. A matching format does not prove that access to a real service works or that the text is secret.
main validates input before opening a new output in x mode. An existing output file is not replaced. JSON is a text format with named fields; you can read the report in an ordinary editor.
"""Local format exercise. Never use this as a real secret scanner."""
import argparse
import json
from pathlib import Path
import re
import sys
CANDIDATE = re.compile(r"\bDEMO_KEY_[\w-]*")
FORMAT = re.compile(r"DEMO_KEY_[A-Z0-9]{8}")
LIMIT = 1024 * 1024
def inspect_text(text):
if len(text.encode("utf-8")) > LIMIT:
raise ValueError("Input exceeds 1 MiB")
findings = []
for line_number, line in enumerate(text.splitlines(), 1):
for match in CANDIDATE.finditer(line):
if len(findings) >= 20000:
raise ValueError("More than 20000 candidates")
findings.append({
"line": line_number,
"column": match.start() + 1,
"valid": FORMAT.fullmatch(match.group()) is not None,
})
accepted = sum(item["valid"] for item in findings)
return {
"kind": "demo-format-only",
"candidates": len(findings),
"accepted": accepted,
"rejected": len(findings) - accepted,
"findings": findings,
}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args(argv)
try:
with args.input.open("rb") as stream:
raw = stream.read(LIMIT + 1)
if len(raw) > LIMIT:
raise ValueError("Input exceeds 1 MiB")
report = inspect_text(raw.decode("utf-8-sig"))
result = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
with args.output.open("x", encoding="utf-8") as stream:
stream.write(result)
except (OSError, UnicodeError, ValueError):
print("Error: use UTF-8 input <=1 MiB and a new output filename.", file=sys.stderr)
return 1
print(f"Saved candidates: {report['candidates']}; format matches: {report['accepted']}.")
return 0
if __name__ == "__main__":
sys.exit(main())
3. Save four examples in demo.txt
Save all the text below as demo.txt. All four markers were invented for this lesson; the first line says so. AB12CD34 has eight uppercase letters or digits. SHORT is too short, ab12cd34 uses lowercase letters, and AB12CD345 is too long.
Expect candidates 4, accepted 1 and rejected 3. The first finding has line 2, column 7 and valid true. Positions start at 1; tabs count as text characters rather than their visual width on screen.
Demo only: all values below are invented.
first DEMO_KEY_AB12CD34
short DEMO_KEY_SHORT
lower DEMO_KEY_ab12cd34
long DEMO_KEY_AB12CD345
4. Generate a report and try an error
Open a terminal in the folder: python3 app.py demo.txt report.json. Expect Saved candidates: 4; format matches: 1. Open report.json and check candidates 4, accepted 1, rejected 3 and the findings list. Notice that marker values are absent from the report.
Create a blank text file named empty.txt. Run python3 app.py empty.txt empty-report.json. Expect zero counts and empty findings. Plain text without a marker gives the same result. That means the input was processed but no candidate word was found.
Repeat the first command using report.json again. Expect an Error message and preservation of the previous report. Choose report-2.json for a new result. Non-UTF-8 input or a file above 1 MiB also causes an error. Save as UTF-8 or use a smaller sample; the original input is not rewritten.
5. Test the format with test_app.py
Save the complete code as test_app.py and run python3 -m unittest -v test_app.py. The finished product passed 7 tests. Expect Ran 7 tests and OK. Tests create sample files in a temporary directory, without checking personal files.
Checks cover empty input, word boundaries, extended and lowercase forms, omission of values from the report and input limits. The real program is also launched with invalid encoding. Preservation of input bytes and an existing report is checked separately. If a check fails, first compare filenames and the complete code.
import contextlib
import io
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from app import inspect_text, main, LIMIT
class Tests(unittest.TestCase):
def test_demo(self):
text = Path(__file__).with_name("demo.txt").read_text()
report = inspect_text(text)
self.assertEqual((report["candidates"], report["accepted"], report["rejected"]), (4, 1, 3))
self.assertEqual(report["findings"][0], {"line": 2, "column": 7, "valid": True})
self.assertNotIn("AB12CD34", json.dumps(report))
def test_empty_and_no_candidate(self):
for text in ["", "A normal demo sentence"]:
self.assertEqual(inspect_text(text)["candidates"], 0)
def test_whole_format(self):
report = inspect_text("DEMO_KEY_A1B2C3D4-extra DEMO_KEY_A1B2C3D4_ DEMO_KEY_A1B2C3D4ə")
self.assertEqual(report["accepted"], 0)
def test_boundaries(self):
self.assertEqual(inspect_text("xDEMO_KEY_A1B2C3D4")["candidates"], 0)
self.assertEqual(inspect_text("(DEMO_KEY_A1B2C3D4)")["accepted"], 1)
def test_limits(self):
for text in ["x" * (LIMIT + 1), "DEMO_KEY_ " * 20001]:
with self.assertRaises(ValueError):
inspect_text(text)
def test_cli_and_preservation(self):
with tempfile.TemporaryDirectory() as folder:
source, output = Path(folder) / "in.txt", Path(folder) / "out.json"
source.write_bytes(b"\xef\xbb\xbfDEMO_KEY_AB12CD34")
before = source.read_bytes()
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(main([str(source), str(output)]), 0)
saved = output.read_bytes()
self.assertEqual(main([str(source), str(output)]), 1)
self.assertEqual(main([str(source), str(source)]), 1)
self.assertEqual(source.read_bytes(), before)
self.assertEqual(output.read_bytes(), saved)
self.assertEqual(json.loads(saved)["accepted"], 1)
def test_process_error_does_not_create_output(self):
with tempfile.TemporaryDirectory() as folder:
source, output = Path(folder) / "bad.txt", Path(folder) / "out.json"
source.write_bytes(b"\xff")
result = subprocess.run([sys.executable, str(Path(__file__).with_name("app.py")), str(source), str(output)], capture_output=True)
self.assertEqual(result.returncode, 1)
self.assertIn(b"Error:", result.stderr)
self.assertFalse(output.exists())
if __name__ == "__main__":
unittest.main()
6. Change a marker and predict the result
Exercise: in a copy of demo.txt, replace only DEMO_KEY_SHORT with DEMO_KEY_A1B2C3D4. Process the copy using a fresh output name. Expect candidates 4, accepted 2 and rejected 2. Append one digit and try again: that marker should now be rejected.
Input is limited to 1 MiB and 20000 candidates. The rule recognizes only DEMO_KEY_ examples. It does not connect to GitHub or Slack and is not a real secret scanner. The GitHub announcement reports fewer Slack-format false positives, without endorsing our rule or its quality.
The product separates finding a similar word from confirming its format. Do not enter real keys, private notes or contact details or send them to an AI service. Only invented inputs were tested; other Python versions were not separately checked.

