1. import time
  2. import hashlib
  3. def validate_file_performance(filepath, expected_hash, num_iterations=100):
  4. """
  5. Measures the performance of file content validation against an expected hash.
  6. Args:
  7. filepath (str): The path to the file.
  8. expected_hash (str): The expected SHA-256 hash of the file.
  9. num_iterations (int): The number of validation iterations to perform.
  10. Returns:
  11. tuple: A tuple containing:
  12. - average_time (float): The average time taken per iteration in seconds.
  13. - validation_success (bool): True if all iterations passed validation, False otherwise.
  14. Raises:
  15. FileNotFoundError: If the specified file does not exist.
  16. ValueError: If the expected_hash is not a valid SHA-256 hash.
  17. """
  18. try:
  19. with open(filepath, "rb") as f:
  20. file_content = f.read()
  21. except FileNotFoundError:
  22. raise FileNotFoundError(f"File not found: {filepath}")
  23. if not isinstance(expected_hash, str) or len(expected_hash) != 64:
  24. raise ValueError("Expected hash must be a 64-character SHA-256 hash.")
  25. try:
  26. calculated_hash = hashlib.sha256(file_content).hexdigest()
  27. except Exception as e:
  28. raise ValueError(f"Error calculating hash: {e}")
  29. if calculated_hash != expected_hash:
  30. print(f"Hash mismatch! Expected: {expected_hash}, Calculated: {calculated_hash}")
  31. return 0.0, False
  32. start_time = time.time()
  33. for _ in range(num_iterations):
  34. calculated_hash = hashlib.sha256(file_content).hexdigest()
  35. if calculated_hash != expected_hash:
  36. print(f"Hash mismatch during iterations! Expected: {expected_hash}, Calculated: {calculated_hash}")
  37. return 0.0, False
  38. end_time = time.time()
  39. total_time = end_time - start_time
  40. average_time = total_time / num_iterations
  41. print(f"Performance validation completed.")
  42. return average_time, True
  43. if __name__ == '__main__':
  44. # Example Usage (replace with your file and expected hash)
  45. filepath = "test_file.txt" #Replace with your file path
  46. expected_hash = "e5b7f39c994b765c9024a8341d544217f8a509d92f8a932a508a777a2460e5b7" # Replace with your expected hash
  47. #Create a test file if it doesn't exist
  48. try:
  49. with open(filepath, "x") as f:
  50. f.write("This is a test file.")
  51. except FileExistsError:
  52. pass
  53. try:
  54. avg_time, success = validate_file_performance(filepath, expected_hash, num_iterations=100)
  55. if success:
  56. print(f"Validation successful. Average time per iteration: {avg_time:.6f} seconds.")
  57. else:
  58. print("Validation failed.")
  59. except (FileNotFoundError, ValueError) as e:
  60. print(f"Error: {e}")

Add your comment