regression.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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', '10000'))
  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. timed_out = False
  34. while run_times < needed_times:
  35. args = []
  36. if self.loader:
  37. args.append(self.loader)
  38. if self.executable:
  39. args.append(self.executable)
  40. if combined_args:
  41. args += combined_args.split(' ')
  42. if self.prepare:
  43. self.prepare(args)
  44. time.sleep(0.1)
  45. p = subprocess.Popen(args,
  46. stdout=subprocess.PIPE,
  47. stderr=subprocess.PIPE)
  48. sleep_time = 0
  49. finish = False
  50. while sleep_time < self.timeout:
  51. time.sleep(0.001)
  52. if p.poll() is not None:
  53. finish = True
  54. break
  55. sleep_time += 1
  56. if not finish and p.poll() is None:
  57. timed_out = True
  58. p.kill()
  59. time.sleep(0.1)
  60. out = p.stdout.read()
  61. log = p.stderr.read()
  62. outputs.append(Result(out, log, p.returncode))
  63. run_times = run_times + 1
  64. keep_log = False
  65. for (name, check, times) in self.runs[combined_args]:
  66. if run_times == times:
  67. result = check(outputs)
  68. if result:
  69. print '\033[92m[Success]\033[0m', name
  70. else:
  71. print '\033[93m[Fail ]\033[0m', name
  72. if timed_out : print 'Test timed out!'
  73. keep_log = True
  74. if self.keep_log and keep_log:
  75. sargs = [re.sub(r"\W", '_', a).strip('_') for a in args]
  76. filename = 'log-' + '_'.join(sargs) + '_' + time.strftime("%Y%m%d_%H%M%S")
  77. with open(filename, 'w') as f:
  78. f.write(log + out)
  79. print 'keep log to %s' % (filename)