regression.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 = 0):
  10. self.loader = loader
  11. self.executable = executable
  12. self.prepare = prepare
  13. self.runs = dict()
  14. default_timeout = int(os.getenv('TIMEOUT', '1000'))
  15. if default_timeout > timeout:
  16. self.timeout = default_timeout
  17. else:
  18. self.timeout = timeout
  19. self.keep_log = (os.getenv('KEEP_LOG', '0') == '1')
  20. def add_check(self, name, check, times = 1, args = []):
  21. combined_args = ' '.join(args)
  22. if not combined_args in self.runs:
  23. self.runs[combined_args] = []
  24. self.runs[combined_args].append((name, check, times))
  25. def run_checks(self):
  26. for combined_args in self.runs:
  27. needed_times = 1
  28. for (name, check, times) in self.runs[combined_args]:
  29. if needed_times < times:
  30. needed_times = times
  31. run_times = 0
  32. outputs = []
  33. while run_times < needed_times:
  34. args = []
  35. if self.loader:
  36. args.append(self.loader)
  37. if self.executable:
  38. args.append(self.executable)
  39. if combined_args:
  40. args += combined_args.split(' ')
  41. if self.prepare:
  42. self.prepare(args)
  43. time.sleep(0.1)
  44. p = subprocess.Popen(args,
  45. stdout=subprocess.PIPE,
  46. stderr=subprocess.PIPE)
  47. sleep_time = 0
  48. finish = False
  49. while sleep_time < self.timeout:
  50. time.sleep(0.001)
  51. if p.poll() is not None:
  52. finish = True
  53. break
  54. sleep_time += 1
  55. if not finish and p.poll() is None:
  56. p.kill()
  57. time.sleep(0.1)
  58. out = p.stdout.read()
  59. log = p.stderr.read()
  60. outputs.append(Result(out, log, p.returncode))
  61. run_times = run_times + 1
  62. keep_log = False
  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
  70. keep_log = True
  71. if self.keep_log and keep_log:
  72. sargs = [re.sub(r"\W", '_', a).strip('_') for a in args]
  73. filename = 'log-' + '_'.join(sargs) + '_' + time.strftime("%Y%m%d_%H%M%S")
  74. with open(filename, 'w') as f:
  75. f.write(log + out)
  76. print 'keep log to %s' % (filename)