# coding=utf-8 """ Faux serveur de capture pour les tests (memes routes que le serveur Flask). python tests/fake_camera.py Ecrit son port sur la sortie standard, puis sert : - /capture et /old : la photo (image/jpeg) ; /capture renvoie une erreur 500 « Error: Could not access the camera » si le fichier /broken existe ; - /text : une reponse texte (comme la route /photo du serveur Flask). Chaque chemin demande est ajoute a /calls.txt. /cut annonce plus d'octets qu'il n'en envoie puis ferme : transmission interrompue. Il tourne dans son propre processus, comme la vraie camera. """ import os import socket import sys import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer def main(photo, folder): with open(photo, "rb") as handle: jpeg = handle.read() class Handler(BaseHTTPRequestHandler): def do_GET(self): with open(os.path.join(folder, "calls.txt"), "a") as log: log.write(self.path + "\n") broken = os.path.exists(os.path.join(folder, "broken")) if self.path == "/capture" and broken: self.reply(500, "text/html", b"Error: Could not access the camera") elif self.path in ("/capture", "/old"): self.reply(200, "image/jpeg", jpeg) elif self.path == "/cut": self.send_response(200) self.send_header("Content-Type", "image/jpeg") self.send_header("Content-Length", str(len(jpeg))) self.end_headers() self.wfile.write(jpeg[:1000]) self.close_connection = True elif self.path == "/text": self.reply(200, "text/html", b"Photo save") else: self.reply(404, "text/html", b"Not found") def reply(self, code, content_type, body): self.send_response(code) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) self.wfile.flush() # Fermeture en douceur. Sur certaines machines Windows (filtre # reseau, antivirus), fermer la connexion juste apres l'envoi fait # perdre la fin de la reponse en boucle locale : constate avec curl # comme avec urllib (environ 1 fois sur 5 sans cette pause, jamais # avec). On laisse les donnees partir, puis on attend que le client # ferme a son tour. try: time.sleep(0.5) self.connection.shutdown(socket.SHUT_WR) self.connection.settimeout(10) while self.connection.recv(65536): pass except OSError: pass def log_message(self, *args): pass server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) print(server.server_address[1], flush=True) server.serve_forever() if __name__ == "__main__": main(sys.argv[1], sys.argv[2])