from decimal import Decimal

def amount_with_tax(amount, rate=Decimal("0.20")):
    return amount * (1 + rate)

assert amount_with_tax(Decimal("10")) == Decimal("12.00")
rows = [("B", 12), ("A", 9)]
assert sorted(rows, key=lambda row: row[0])[0] == ("A", 9)


def totaux_lots(taille_lot, nombre_lots=10):
    "Retourner les totaux cumulés pour une taille et un nombre de lots."
    if type(nombre_lots) is not int or nombre_lots < 0:
        raise ValueError("Nombre de lots entier et non négatif attendu")
    return [taille_lot * numero for numero in range(1, nombre_lots + 1)]

def totaux(taille_lot, nombre_lots=10):
    "Calculer les totaux cumulés sans les afficher."
    return totaux_lots(taille_lot, nombre_lots)

def afficher_totaux(taille_lot, nombre_lots=10):
    "Afficher les totaux cumulés pour le nombre de lots demandé."
    for total in totaux(taille_lot, nombre_lots):
        print(total)

def afficher_etat():
    "Afficher l'état initial du traitement."
    print("Lot prêt")

assert totaux_lots(7, 3) == [7, 14, 21]
assert totaux_lots(nombre_lots=3, taille_lot=7) == [7, 14, 21]
assert len(totaux_lots(7)) == 10
assert totaux_lots(7, 0) == []
assert totaux(7, 3) == [7, 14, 21]
assert totaux(nombre_lots=3, taille_lot=7) == [7, 14, 21]
from contextlib import redirect_stdout
from io import StringIO
sortie_fonction = StringIO()
with redirect_stdout(sortie_fonction):
    retour = afficher_totaux(nombre_lots=3, taille_lot=7)
assert retour is None and sortie_fonction.getvalue().splitlines() == ["7", "14", "21"]
try:
    totaux_lots(7, -1)
except ValueError:
    pass
else:
    raise AssertionError("Une limite négative doit être refusée")


from inspect import signature
import math as mathematiques

def configurer(taille=100, tentatives=3, delai=5):
    return taille, tentatives, delai

assert configurer() == (100, 3, 5)
assert configurer(delai=10, tentatives=2) == (100, 2, 10)
assert signature(configurer).parameters["taille"].default == 100

def regle():
    return "ancienne"
ancienne_regle = regle
def regle():
    return "nouvelle"
assert ancienne_regle() == "ancienne" and regle() == "nouvelle"

def octets_vers_kio(octets):
    return octets / 1024

taille_kio = octets_vers_kio(2048)
assert taille_kio == 2.0
en_kio = lambda octets: octets / 1024
assert en_kio(2048) == 2.0 and en_kio(512) == 0.5
assert (lambda lignes, rejets: lignes - rejets)(100, 4) == 96
assert mathematiques.sqrt(16) == 4.0
assert callable(mathematiques.sqrt)


from math import fabs
assert fabs(-5) == 5.0 and fabs(0) == 0.0
assert mathematiques.fabs(-5) == fabs(-5)

def resumer_lot(quantites):
    acceptees = [valeur for valeur in quantites if valeur >= 0]
    return sum(acceptees), len(quantites) - len(acceptees)

total_lot, nombre_rejets = resumer_lot([4, -2, 0, 7])
assert (total_lot, nombre_rejets) == (11, 1)
assert resumer_lot([]) == (0, 0)
assert (lambda valeur: valeur * 2)(6) == 12
assert totaux_lots(5, 2) == [5, 10]
assert totaux_lots(3, 2) == [3, 6]

import math
import math as maths
from math import sqrt as racine_carree

def sqrt(valeur):
    return "contrôle local"

assert sqrt(16) == "contrôle local"
assert math.sqrt(16) == maths.sqrt(16) == racine_carree(16) == 4.0
assert math is maths
assert type(math.fabs(-5)) is float
assert math.fabs(-5) == math.fabs(5) == 5.0

def historique_partage(lot, historique=[]):
    historique.append(lot)
    return historique

premier_historique = historique_partage("A")
second_historique = historique_partage("B")
assert premier_historique is second_historique
assert premier_historique == ["A", "B"]

def ajouter_lot(lot, historique=None):
    if historique is None:
        historique = []
    historique.append(lot)
    return historique

assert ajouter_lot("A") == ["A"]
assert ajouter_lot("B") == ["B"]
fourni = ["A"]
assert ajouter_lot("B", fourni) is fourni
assert fourni == ["A", "B"]

taille_defaut = 100
def taille_de_traitement(taille=taille_defaut):
    return taille

taille_defaut = 200
assert taille_de_traitement() == 100
assert taille_de_traitement(taille_defaut) == 200

import sys
from types import ModuleType

nom_demo = "_demo_configuration_lots"
assert nom_demo not in sys.modules
configuration_demo = ModuleType(nom_demo)
configuration_demo.taille_lot = 100
sys.modules[nom_demo] = configuration_demo
try:
    from _demo_configuration_lots import taille_lot as taille_importee
    configuration_demo.taille_lot = 200
    assert taille_importee == 100
    assert configuration_demo.taille_lot == 200
finally:
    del sys.modules[nom_demo]

from contextlib import redirect_stdout
from io import StringIO

sortie_totaux = StringIO()
with redirect_stdout(sortie_totaux):
    def afficher_totaux_sept():
        taille_lot = 7
        compteur = 0
        while compteur < 10:
            print((compteur + 1) * taille_lot)
            compteur += 1

    assert sortie_totaux.getvalue() == ""
    afficher_totaux_sept()
    afficher_totaux_sept()

assert sortie_totaux.getvalue().splitlines() == [str(n * 7) for n in range(1, 11)] * 2

# Une borne négative rend ce test faux dès le départ.
passages = 0
while passages < -3:
    passages += 1
assert passages == 0

from inspect import getdoc
assert "totaux cumulés" in getdoc(totaux_lots)
try:
    math.sqrt(-1)
except ValueError:
    pass
else:
    raise AssertionError("Une racine réelle négative doit être refusée")

# L'aide peut recevoir la fonction ou son nom complet sous forme de chaîne.
from contextlib import redirect_stdout
from io import StringIO
import math

aide_objet, aide_nom = StringIO(), StringIO()
with redirect_stdout(aide_objet):
    help(math.sqrt)
with redirect_stdout(aide_nom):
    help("math.sqrt")
assert "sqrt" in aide_objet.getvalue()
assert "sqrt" in aide_nom.getvalue()

# Démonstration d'un import générique : il peut masquer un nom local.
sqrt_avant = sqrt
assert sqrt_avant(4) == "contrôle local"
from math import *
assert sqrt(4) == 2.0 and fabs(5) == 5.0
assert sqrt is not sqrt_avant
sqrt = sqrt_avant

assert configurer() == (100, 3, 5)
assert configurer(50) == (50, 3, 5)
assert configurer(delai=10, tentatives=2) == (100, 2, 10)
assert configurer(delai=8, taille=50, tentatives=4) == (50, 4, 8)
try:
    configurer(50, taille=60)
except TypeError:
    pass
else:
    raise AssertionError("Un paramètre ne peut pas recevoir deux valeurs")

lignes_a_trier = [{"id": "B", "quantite": 12}, {"id": "A", "quantite": 9}]
lignes_triees = sorted(lignes_a_trier, key=lambda ligne: ligne["id"])
assert [ligne["id"] for ligne in lignes_triees] == ["A", "B"]
assert [ligne["id"] for ligne in lignes_a_trier] == ["B", "A"]
try:
    sorted([{"id": "A"}, {"quantite": 2}], key=lambda ligne: ligne["id"])
except KeyError:
    pass
else:
    raise AssertionError("Une ligne sans identifiant doit être détectée")

def compter_sans_validation(limite):
    compteur = 0
    passages = []
    while compteur < limite:
        passages.append(compteur)
        compteur += 1
    return passages

assert compter_sans_validation(-1) == []
assert compter_sans_validation(0) == []
assert compter_sans_validation(3) == [0, 1, 2]
try:
    totaux_lots(7, -1)
except ValueError:
    pass
else:
    raise AssertionError("Le contrat doit refuser un nombre de lots négatif")
