Path: blob/master/exercices/oop/multianalyzer/solution_multianalyzer_protocol.py
306 views
import functools1from dataclasses import dataclass2from typing import Protocol345@dataclass6class Result:7iocs: set[str]8score: int = 091011@dataclass12class Report:13results: list[Result] = None1415@property16def score(self):17return functools.reduce(lambda x, y: x + y, (r.score for r in self.results))1819@property20def iocs(self):21return sorted([ioc for r in self.results for ioc in r.iocs])2223def __str__(self) -> str:24s = "Report :\n"25s += f"- score = {self.score}\n"26if self.iocs:27s += f"- iocs :\n"28for ioc in self.iocs:29s += f" - {ioc}\n"30return s313233# correction Protocol34class Service(Protocol):35name: str3637def run(self, filepath: str) -> Result:38raise NotImplementedError394041@dataclass42class Yara:43name: str = "Yara"4445def run(self, filepath: str) -> Result:46return Result(score=500, iocs=["1.1.1.1"])474849@dataclass50class ScanPDF:51name: str = "ScanPDF"5253def run(self, filepath: str) -> Result:54return Result(iocs=["cestpasnous.com"])555657@dataclass58class Antivirus:59name: str = "Antivirus"6061def run(self, filepath: str) -> Result:62return Result(score=500, iocs={})636465@dataclass66class MultiAnalyzer:67services: list[Service]6869def get_service_by_name(self, name: str) -> Service:70for service in self.services:71if service.name == name:72return service73raise ValueError7475def analyze(self, filepath: str, services: list[str]) -> Report:76results = []77for service_name in services:78service = self.get_service_by_name(service_name)79results.append(service.run(filepath))80return Report(results=results)818283scanpdf = ScanPDF()84yara = Yara()85antivirus = Antivirus()86tool = MultiAnalyzer(services=[scanpdf, yara, antivirus])8788report = tool.analyze(filepath="bizarre.pdf", services=["ScanPDF", "Yara", "Antivirus"])89print(report)90assert (91str(report)92== """Report :93- score = 100094- iocs :95- 1.1.1.196- cestpasnous.com97"""98)99100101