import json
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    path = Path(directory) / "report.json"
    payload = {"station": "Nord", "quantity": 12}
    path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
    loaded = json.loads(path.read_text(encoding="utf-8"))
    assert loaded == payload


import pickle

with TemporaryDirectory() as directory:
    base = Path(directory)
    entree = base / "entrees"
    sortie = base / "sorties"
    entree.mkdir()
    sortie.mkdir()
    fichier = entree / "lot.txt"
    assert (sortie / ".." / "entrees" / "lot.txt").resolve() == fichier
    with open(fichier, "w", encoding="utf-8") as flux:
        assert flux.write("nord:12\n") == 8
    assert flux.closed
    with open(fichier, "a", encoding="utf-8") as flux:
        flux.write("sud:8\n")
    with open(fichier, "r", encoding="utf-8") as flux:
        texte = flux.read()
        assert flux.read() == ""
    assert texte == "nord:12\nsud:8\n"
    assert [int(ligne.split(":")[1]) for ligne in texte.splitlines()] == [12, 8]
    with open(fichier, "rb") as flux:
        assert flux.read().startswith(b"nord:12")

    # Ne charger que les octets pickle produits ici, dans ce dossier de test.
    sauvegarde = base / "controle.pickle"
    with open(sauvegarde, "wb") as flux:
        redacteur = pickle.Pickler(flux)
        redacteur.dump({"station": "nord", "quantite": 12})
        redacteur.dump({"station": "sud", "quantite": 8})
    with open(sauvegarde, "rb") as flux:
        lecteur = pickle.Unpickler(flux)
        assert lecteur.load() == {"station": "nord", "quantite": 12}
        assert lecteur.load() == {"station": "sud", "quantite": 8}
        try:
            lecteur.load()
        except EOFError:
            pass
        else:
            raise AssertionError("La fin du flux aurait dû être atteinte")

with TemporaryDirectory() as repertoire_test:
    rapport_test = Path(repertoire_test) / "rapport.txt"
    with open(rapport_test, "x", encoding="utf-8") as flux:
        flux.write("lot accepté")
    try:
        with open(rapport_test, "r", encoding="utf-8") as flux:
            assert flux.read() == "lot accepté"
            raise ValueError("erreur simulée")
    except ValueError as erreur:
        assert str(erreur) == "erreur simulée"
    else:
        raise AssertionError("L'exception doit continuer après le bloc with")
    assert flux.closed
    try:
        open(rapport_test, "x", encoding="utf-8")
    except FileExistsError:
        pass
    else:
        raise AssertionError("La création exclusive doit refuser un fichier existant")
    assert rapport_test.read_text(encoding="utf-8") == "lot accepté"

def refuser_constante_json(valeur):
    raise ValueError("Constante JSON non autorisée : " + valeur)

rapport_valide = {"station": "nord", "quantite": 4}
texte_valide = json.dumps(rapport_valide, allow_nan=False)
assert json.loads(texte_valide, parse_constant=refuser_constante_json) == rapport_valide
try:
    json.dumps({"quantite": float("nan")}, allow_nan=False)
except ValueError:
    pass
else:
    raise AssertionError("NaN doit être refusé à l'écriture")
try:
    json.loads('{"quantite": NaN}', parse_constant=refuser_constante_json)
except ValueError:
    pass
else:
    raise AssertionError("NaN doit être refusé à la lecture")

with TemporaryDirectory() as repertoire_blocs:
    chemin_blocs = Path(repertoire_blocs) / "station.txt"
    chemin_blocs.write_text("été", encoding="utf-8")
    with open(chemin_blocs, "r", encoding="utf-8") as flux_texte:
        assert flux_texte.read(1) == "é"
        assert flux_texte.read() == "té"
        assert flux_texte.read(1) == ""
    with open(chemin_blocs, "rb") as flux_binaire:
        premier_octet = flux_binaire.read(1)
        suite = flux_binaire.read()
        assert premier_octet + suite == "été".encode("utf-8")
        assert len(premier_octet + suite) > len("été")

from io import BytesIO

flux_vide = BytesIO(b"")
try:
    pickle.load(flux_vide)
except EOFError:
    pass
else:
    raise AssertionError("Un flux vide doit signaler sa fin")

flux_fiable = BytesIO()
pickle.dump({"lot": "A", "lignes": 3}, flux_fiable)
flux_fiable.seek(0)
assert pickle.load(flux_fiable) == {"lot": "A", "lignes": 3}
try:
    pickle.load(flux_fiable)
except EOFError:
    pass
else:
    raise AssertionError("Le flux ne contient pas de deuxième objet")

with TemporaryDirectory() as dossier_troncature:
    chemin_test = Path(dossier_troncature) / "rapport.txt"
    chemin_test.write_text("données précédentes", encoding="utf-8")
    with open(chemin_test, "w", encoding="utf-8"):
        assert chemin_test.stat().st_size == 0
    assert chemin_test.read_text(encoding="utf-8") == ""

import threading
try:
    pickle.dumps(threading.Lock())
except TypeError:
    pass
else:
    raise AssertionError("Un verrou de thread ne doit pas être sérialisé directement")

import csv
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as dossier:
    chemin_bom = Path(dossier) / "stations.csv"
    chemin_bom.write_bytes(b"\xef\xbb\xbfstation,quantite\nnord,12\n")
    with chemin_bom.open(encoding="utf-8", newline="") as fichier:
        brut = next(csv.DictReader(fichier))
    with chemin_bom.open(encoding="utf-8-sig", newline="") as fichier:
        corrige = next(csv.DictReader(fichier))
    assert "station" not in brut and "\ufeffstation" in brut
    assert corrige == {"station": "nord", "quantite": "12"}

import os
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as dossier_temporaire:
    base = Path(dossier_temporaire)
    nord, sud = base / "nord", base / "sud"
    nord.mkdir()
    sud.mkdir()
    (nord / "lot.txt").write_text("lot nord", encoding="utf-8")
    (sud / "lot.txt").write_text("lot sud", encoding="utf-8")
    dossier_initial = Path.cwd()
    try:
        os.chdir(nord)
        assert Path("lot.txt").read_text(encoding="utf-8") == "lot nord"
        os.chdir(sud)
        assert Path("lot.txt").read_text(encoding="utf-8") == "lot sud"
        assert (nord / "lot.txt").read_text(encoding="utf-8") == "lot nord"
    finally:
        os.chdir(dossier_initial)

# Le nombre de caractères écrits diffère parfois du nombre d'octets.
with TemporaryDirectory() as dossier:
    chemin = Path(dossier) / "accent.txt"
    with chemin.open("w", encoding="utf-8") as fichier:
        nombre_caracteres = fichier.write("é")
    assert nombre_caracteres == 1
    assert chemin.read_bytes() == b"\xc3\xa9"

from pathlib import PureWindowsPath

chemin_absolu_windows = PureWindowsPath("C:/projet/lot.csv")
chemin_relatif_lecteur = PureWindowsPath("C:projet/lot.csv")
assert chemin_absolu_windows.is_absolute()
assert not chemin_relatif_lecteur.is_absolute()
assert chemin_absolu_windows.drive == chemin_relatif_lecteur.drive == "C:"
assert chemin_absolu_windows.root and not chemin_relatif_lecteur.root

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as dossier_lecture:
    chemin_lot = Path(dossier_lecture) / "lot.txt"
    chemin_lot.write_text("nord:12\nsud:8\nest:invalide\n", encoding="utf-8")
    total_lu = 0
    lignes_rejetees = []
    with chemin_lot.open("r", encoding="utf-8") as fichier_lot:
        for numero, ligne in enumerate(fichier_lot, start=1):
            try:
                station, texte_quantite = ligne.rstrip("\n").split(":", 1)
                quantite = int(texte_quantite)
            except ValueError:
                lignes_rejetees.append(numero)
                continue
            total_lu += quantite
    assert fichier_lot.closed
    assert total_lu == 20 and lignes_rejetees == [3]

from io import BytesIO
import pickle

flux_partage = BytesIO()
ecrivain = pickle.Pickler(flux_partage)
liste_partagee = ["lot-A"]
ecrivain.dump(liste_partagee)
ecrivain.dump(liste_partagee)
flux_partage.seek(0)
lecteur_unique = pickle.Unpickler(flux_partage)
premier_lot = lecteur_unique.load()
second_lot = lecteur_unique.load()
assert premier_lot == ["lot-A"] and premier_lot is second_lot

flux_partage.seek(0)
assert pickle.load(flux_partage) == ["lot-A"]
try:
    pickle.load(flux_partage)
except pickle.UnpicklingError:
    pass
else:
    raise AssertionError("Ce flux partage une référence entre les objets")

import json
import math
from decimal import Decimal

def refuser_constante_json(texte):
    raise ValueError("Constante JSON non autorisée : " + texte)

mesure_flottante = json.loads('{"mesure": 1e999}', parse_constant=refuser_constante_json)
assert math.isinf(mesure_flottante["mesure"])
mesure_decimale = json.loads('{"mesure": 1e999}', parse_float=Decimal,
                            parse_constant=refuser_constante_json)["mesure"]
assert mesure_decimale.is_finite() and mesure_decimale == Decimal("1e999")
limite_mesure = Decimal("1000000")
assert mesure_decimale > limite_mesure  # Rejetée par la règle métier de cet exemple.
try:
    json.loads('{"mesure": NaN}', parse_constant=refuser_constante_json)
except ValueError:
    pass
else:
    raise AssertionError("Le jeton NaN doit être refusé")

with TemporaryDirectory() as dossier_ajout:
    sans_separateur = Path(dossier_ajout) / "sans-separateur.txt"
    with sans_separateur.open("a", encoding="utf-8") as flux:
        flux.write("nord:12")  # Le fichier n'existait pas avant cette ouverture.
    with sans_separateur.open("a", encoding="utf-8") as flux:
        flux.write("sud:8\n")
    assert sans_separateur.read_text(encoding="utf-8").splitlines() == ["nord:12sud:8"]

    avec_separateur = Path(dossier_ajout) / "avec-separateur.txt"
    with avec_separateur.open("a", encoding="utf-8") as flux:
        flux.write("nord:12\n")
    with avec_separateur.open("a", encoding="utf-8") as flux:
        flux.write("sud:8\n")
    assert avec_separateur.read_text(encoding="utf-8").splitlines() == ["nord:12", "sud:8"]
