regression.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/python
  2. import sys, os, subprocess, re, time
  3. class Result:
  4. def __init__(self, out, log, code):
  5. self.out = out.split('\n')
  6. self.log = log.split('\n')
  7. self.code = code
  8. class Regression:
  9. def __init__(self, loader = None, executable = '', prepare = None, timeout = 1000, keep_log = False):
  10. self.loader = loader
  11. self.executable = executable
  12. self.prepare = prepare
  13. self.runs = dict()
  14. self.timeout = timeout
  15. self.keep_log = keep_log
  16. def add_check(self, name, check, times = 1, args = []):
  17. combined_args = ' '.join(args)
  18. if not combined_args in self.runs:
  19. self.runs[combined_args] = []
  20. self.runs[combined_args].append((name, check, times))
  21. def run_checks(self):
  22. for combined_args in self.runs:
  23. needed_times = 1
  24. for (name, check, times) in self.runs[combined_args]:
  25. if needed_times < times:
  26. needed_times = times
  27. run_times = 0
  28. outputs = []
  29. while run_times < needed_times:
  30. args = []
  31. if self.loader:
  32. args.append(self.loader)
  33. if self.executable:
  34. args.append(self.executable)
  35. if combined_args:
  36. args += combined_args.split(' ')
  37. if self.prepare:
  38. self.prepare(args)
  39. p = subprocess.Popen(args,
  40. stdout=subprocess.PIPE,
  41. stderr=subprocess.PIPE)
  42. sleep_time = 0
  43. finish = False
  44. while sleep_time < self.timeout:
  45. time.sleep(0.001)
  46. if p.poll() is not None:
  47. finish = True
  48. break
  49. sleep_time += 1
  50. if not finish and p.poll() is None:
  51. p.kill()
  52. out = p.stdout.read()
  53. log = p.stderr.read()
  54. if self.keep_log:
  55. sargs = [re.sub(r"\W", '_', a).strip('_') for a in args]
  56. filename = '_'.join(sargs) + '_' + time.strftime("%Y%m%d_%H%M%S")
  57. with open(filename + '.log', 'w') as f:
  58. f.write(log)
  59. with open(filename + '.out', 'w') as f:
  60. f.write(out)
  61. outputs.append(Result(out, log, p.returncode))
  62. run_times = run_times + 1
  63. for (name, check, times) in self.runs[combined_args]:
  64. if run_times == times:
  65. result = check(outputs)
  66. if result:
  67. print '\033[92m[Success]\033[0m', name
  68. else:
  69. print '\033[93m[Fail ]\033[0m', name