1. Create the comparison product folder
You will build a product comparing expected settings with observations. A Boolean is a true or false value. null can mean an unknown observation here; it must not automatically be treated as false.
Python 3 and an editor are enough. Check python3 --version; if unavailable, install Python 3 and reopen the terminal. Actual checks used Python 3.14.4. Save the three files in ayar-ferqi-v1 as UTF-8, without hidden .txt extensions. Do not save the tree itself.
ayar-ferqi-v1/
app.py
demo.json
test_app.py
2. Implement comparisons in app.py
Save the complete code as app.py. A null override uses default; an explicit false overrides even a true default. A null observed puts the id in unknown. A differing known observation enters changes; a match enters unchanged.
Each list is sorted by id. checked counts all input records, not successful measurements. The report does not apply proposed changes; it shows differences in supplied data only. Existing output and original input are not replaced.
"""Yalnız verilmiş boolean ayarların fərq hesabatını yaradır."""
import argparse
import json
import re
import sys
from pathlib import Path
LIMIT = 1024 * 1024
def unique_object(pairs):
result = dict(pairs)
if len(result) != len(pairs):
raise ValueError("JSON sahəsi təkrarlanır")
return result
def reject_constant(value):
raise ValueError("NaN və Infinity qəbul edilmir")
def fields(value, keys):
if type(value) is not dict or set(value) != set(keys):
raise ValueError("sahələr çatışmır və ya artıqdır")
def report(source):
with Path(source).open("rb") as stream:
raw = stream.read(LIMIT + 1)
if len(raw) > LIMIT:
raise ValueError("giriş 1 MiB həddini keçir")
data = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object,
parse_constant=reject_constant)
fields(data, ("default", "repos"))
if type(data["default"]) is not bool:
raise ValueError("default boolean olmalıdır")
rows = data["repos"]
if type(rows) is not list or len(rows) > 100:
raise ValueError("repos: siyahı, ən çox 100 element")
seen = set()
for row in rows:
fields(row, ("id", "override", "observed"))
key = row["id"]
if (type(key) is not str or
re.fullmatch(r"[A-Za-z0-9_-]{1,40}", key) is None):
raise ValueError("id: 1–40 ASCII hərf, rəqəm, _ və ya -")
if key in seen:
raise ValueError("id təkrarlanır")
seen.add(key)
for name in ("override", "observed"):
if row[name] is not None and type(row[name]) is not bool:
raise ValueError(name + " boolean və ya null olmalıdır")
result = {"checked": len(rows), "changes": [], "unknown": [], "unchanged": []}
for row in sorted(rows, key=lambda item: item["id"]):
key, observed = row["id"], row["observed"]
expected = data["default"] if row["override"] is None else row["override"]
if observed is None:
result["unknown"].append(key)
elif observed == expected:
result["unchanged"].append(key)
else:
result["changes"].append(dict(id=key, expected=expected, observed=observed))
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input")
parser.add_argument("output")
args = parser.parse_args()
try:
payload = json.dumps(report(args.input), indent=2) + "\n"
with Path(args.output).open("x", encoding="utf-8") as stream:
stream.write(payload)
except (OSError, ValueError, RecursionError) as error:
print("Xəta:", error, file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
sys.exit(main())
3. Supply expectations in demo.json
Save the complete sample as demo.json. JSON is a text format with named fields. default is the general choice and repos lists invented records. Each has id, an individual override and an observed value.
For a, expected false differs from observed true. The true override for b matches its observation. The observation for c is unknown and must stay in unknown. These are not real repository measurements; a, b and c are sample identifiers.
{
"default": false,
"repos": [
{"id": "a", "override": null, "observed": true},
{"id": "b", "override": true, "observed": true},
{"id": "c", "override": null, "observed": null}
]
}
4. Generate a report and correct an error
Open a terminal in the folder: python3 app.py demo.json report.json. Success prints nothing. Expect checked 3, a in changes (expected false, observed true), c in unknown and b in unchanged. Reusing output causes an error with exit code 2; choose report-2.json instead.
Put {"default":false,"repos":[]} in empty.json. Run python3 app.py empty.json empty-report.json. Expect checked 0 and three empty lists. Put {"default":0,"repos":[]} in bad.json and use fresh output. Expect Xəta: default boolean olmalıdır and no file. Replace 0 with false to correct it.
5. Verify the result with test_app.py
Save the complete tests as test_app.py and run python3 -m unittest -v test_app.py. The product passed 6 actual CLI test methods; expect Ran 6 tests and OK. Tests create their own temporary input files.
Checks cover an explicit false override, unknown observations, empty input, wrong types and preservation of existing files. Boolean fields reject 0, 1 and text. Error messages are Azerbaijani; the code is identical across all three lessons.
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
DEMO = json.loads((HERE / "demo.json").read_text())
WANT = {"checked": 3, "changes": [dict(id="a", expected=False, observed=True)],
"unknown": ["c"], "unchanged": ["b"]}
class CliTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.src = Path(self.temp.name) / "input.json"
self.dst = Path(self.temp.name) / "output.json"
def call(self, data, output=None):
self.src.write_text(data if isinstance(data, str) else json.dumps(data))
return subprocess.run([sys.executable, str(HERE / "app.py"),
str(self.src), str(output or self.dst)],
capture_output=True)
def check(self, data, expected):
self.assertEqual(self.call(data).returncode, 0)
self.assertEqual(json.loads(self.dst.read_text()), expected)
def test_demo(self):
self.check(dict(DEMO, repos=list(reversed(DEMO["repos"]))), WANT)
def test_empty(self):
self.check(dict(default=True, repos=[]),
dict(checked=0, changes=[], unknown=[], unchanged=[]))
def test_override(self):
rows = [dict(id="b", override=None, observed=True),
dict(id="a", override=False, observed=True)]
self.check(dict(default=True, repos=rows),
dict(WANT, checked=2, unknown=[]))
def test_rejections(self):
bad = [{}, dict(DEMO, extra=1), dict(default=False, repos={}),
dict(default=False, repos=[{}]), dict(default=False, repos=[0]),
dict(DEMO, repos=DEMO["repos"] * 34),
dict(DEMO, repos=[DEMO["repos"][0]] * 2),
'{"default":false,"repos":[{"id":"a","id":"b"}]}',
'{"default":false,"default":true,"repos":[]}',
'{"default":false,"repos":[],"x":NaN}', " " * 1048577]
for value in [0, 1, "false", None]:
bad.append(dict(DEMO, default=value))
row = DEMO["repos"][0]
for patch in [{"id": ""}, {"id": "a" * 41}, {"id": "ə"},
{"id": "a b"}, {"id": 1}, {"extra": True},
{"override": 0}, {"override": "true"},
{"observed": 1}, {"observed": "false"}]:
bad.append(dict(DEMO, repos=[dict(row, **patch)]))
for data in bad:
with self.subTest(data=str(data)[:60]):
self.assertEqual(self.call(data).returncode, 2)
self.assertFalse(self.dst.exists())
def test_existing_paths(self):
self.dst.write_text("KEEP")
self.assertEqual(self.call(DEMO).returncode, 2)
self.assertEqual(self.dst.read_text(), "KEEP")
self.assertEqual(self.call(DEMO, self.src).returncode, 2)
self.assertEqual(json.loads(self.src.read_text()), DEMO)
def test_extension(self):
rows = [dict(row) for row in DEMO["repos"]]
rows[2]["observed"] = False
self.check(dict(DEMO, repos=rows),
dict(WANT, unknown=[], unchanged=["b", "c"]))
if __name__ == "__main__":
unittest.main(verbosity=2)
6. Make an unknown observation known
Exercise: in a copy of demo.json, change only c’s observed value to false. Save exercise.json and run python3 app.py exercise.json exercise-report.json. checked stays 3; changes contains only a, unknown becomes empty and unchanged is b,c. This separates newly supplied evidence for c from a differing setting.
Limits are 1 MiB UTF-8 input and 100 records. Unique ids use 1–40 ASCII letters, digits, underscores or hyphens. Extra or missing fields, duplicate JSON fields, NaN and Infinity are rejected. The tool does not measure services, apply settings or guarantee input accuracy. Keep original files and practice with invented data.

