comparers.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """
  2. Digress comparers.
  3. """
  4. from digress.errors import ComparisonError
  5. import os
  6. from itertools import imap, izip
  7. def compare_direct(value_a, value_b):
  8. if value_a != value_b:
  9. raise ComparisonError("%s is not %s" % (value_a, value_b))
  10. def compare_pass(value_a, value_b):
  11. """
  12. Always true, as long as the test is passed.
  13. """
  14. def compare_tolerance(tolerance):
  15. def _compare_tolerance(value_a, value_b):
  16. if abs(value_a - value_b) > tolerance:
  17. raise ComparisonError("%s is not %s (tolerance: %s)" % (
  18. value_a,
  19. value_b,
  20. tolerance
  21. ))
  22. return _compare_tolerance
  23. def compare_files(file_a, file_b):
  24. size_a = os.path.getsize(file_a)
  25. size_b = os.path.getsize(file_b)
  26. print file_a, file_b
  27. if size_a != size_b:
  28. raise ComparisonError("%s is not the same size as %s" % (
  29. file_a,
  30. file_b
  31. ))
  32. BUFFER_SIZE = 8196
  33. offset = 0
  34. with open(file_a) as f_a:
  35. with open(file_b) as f_b:
  36. for chunk_a, chunk_b in izip(
  37. imap(
  38. lambda i: f_a.read(BUFFER_SIZE),
  39. xrange(size_a // BUFFER_SIZE + 1)
  40. ),
  41. imap(
  42. lambda i: f_b.read(BUFFER_SIZE),
  43. xrange(size_b // BUFFER_SIZE + 1)
  44. )
  45. ):
  46. chunk_size = len(chunk_a)
  47. if chunk_a != chunk_b:
  48. for i in xrange(chunk_size):
  49. if chunk_a[i] != chunk_b[i]:
  50. raise ComparisonError("%s differs from %s at offset %d" % (
  51. file_a,
  52. file_b,
  53. offset + i
  54. ))
  55. offset += chunk_size