| 1 | #!/usr/bin/env python |
| 2 | # -*- coding: utf-8 -*- |
| 3 | # |
| 4 | # compare.py -- High-level tests for dtrx. |
| 5 | # Copyright © 2006-2009 Brett Smith <brettcsmith@brettcsmith.org>. |
| 6 | # |
| 7 | # This program is free software; you can redistribute it and/or modify it |
| 8 | # under the terms of the GNU General Public License as published by the |
| 9 | # Free Software Foundation; either version 3 of the License, or (at your |
| 10 | # option) any later version. |
| 11 | # |
| 12 | # This program is distributed in the hope that it will be useful, but |
| 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General |
| 15 | # Public License for more details. |
| 16 | # |
| 17 | # You should have received a copy of the GNU General Public License along |
| 18 | # with this program; if not, see <http://www.gnu.org/licenses/>. |
| 19 | |
| 20 | import os |
| 21 | import re |
| 22 | import subprocess |
| 23 | import yaml |
| 24 | import sys |
| 25 | import tempfile |
| 26 | |
| 27 | from sets import Set as set |
| 28 | |
| 29 | if os.path.exists('scripts/dtrx') and os.path.exists('tests'): |
| 30 | os.chdir('tests') |
| 31 | elif os.path.exists('../scripts/dtrx') and os.path.exists('../tests'): |
| 32 | pass |
| 33 | else: |
| 34 | print "ERROR: Can't run tests in this directory!" |
| 35 | sys.exit(2) |
| 36 | |
| 37 | X_SCRIPT = os.path.realpath('../scripts/dtrx') |
| 38 | ROOT_DIR = os.path.realpath(os.curdir) |
| 39 | OUTCOMES = ['error', 'failed', 'passed'] |
| 40 | TESTSCRIPT_NAME = 'testscript.sh' |
| 41 | SCRIPT_PROLOGUE = """#!/bin/sh |
| 42 | set -e |
| 43 | """ |
| 44 | |
| 45 | input_buffer = tempfile.TemporaryFile() |
| 46 | output_buffer = tempfile.TemporaryFile() |
| 47 | |
| 48 | class ExtractorTestError(Exception): |
| 49 | pass |
| 50 | |
| 51 | |
| 52 | class ExtractorTest(object): |
| 53 | def __init__(self, **kwargs): |
| 54 | setattr(self, 'name', kwargs['name']) |
| 55 | setattr(self, 'options', kwargs.get('options', '-n').split()) |
| 56 | setattr(self, 'filenames', kwargs.get('filenames', '').split()) |
| 57 | for key in ('directory', 'prerun', 'posttest', 'baseline', 'error', |
| 58 | 'input', 'output', 'cleanup'): |
| 59 | setattr(self, key, kwargs.get(key, None)) |
| 60 | for key in ('grep', 'antigrep'): |
| 61 | value = kwargs.get(key, []) |
| 62 | if isinstance(value, str): |
| 63 | value = [value] |
| 64 | setattr(self, key, value) |
| 65 | |
| 66 | def get_results(self, commands, stdin=None): |
| 67 | print >>output_buffer, "Output from %s:" % (' '.join(commands),) |
| 68 | output_buffer.flush() |
| 69 | status = subprocess.call(commands, stdout=output_buffer, |
| 70 | stderr=output_buffer, stdin=stdin) |
| 71 | process = subprocess.Popen(['find', '!', '-name', TESTSCRIPT_NAME], |
| 72 | stdout=subprocess.PIPE) |
| 73 | process.wait() |
| 74 | output = process.stdout.read(-1) |
| 75 | process.stdout.close() |
| 76 | return status, set(output.split('\n')) |
| 77 | |
| 78 | def write_script(self, commands): |
| 79 | script = open(TESTSCRIPT_NAME, 'w') |
| 80 | script.write("%s%s\n" % (SCRIPT_PROLOGUE, commands)) |
| 81 | script.close() |
| 82 | subprocess.call(['chmod', 'u+w', TESTSCRIPT_NAME]) |
| 83 | |
| 84 | def run_script(self, key): |
| 85 | commands = getattr(self, key) |
| 86 | if commands is not None: |
| 87 | if self.directory: |
| 88 | directory_hint = '../' |
| 89 | else: |
| 90 | directory_hint = '' |
| 91 | self.write_script(commands) |
| 92 | subprocess.call(['sh', TESTSCRIPT_NAME, directory_hint]) |
| 93 | |
| 94 | def get_shell_results(self): |
| 95 | self.run_script('prerun') |
| 96 | self.write_script(self.baseline) |
| 97 | return self.get_results(['sh', TESTSCRIPT_NAME] + self.filenames) |
| 98 | |
| 99 | def get_extractor_results(self): |
| 100 | self.run_script('prerun') |
| 101 | input_buffer.seek(0, 0) |
| 102 | input_buffer.truncate() |
| 103 | if self.input: |
| 104 | input_buffer.write(self.input) |
| 105 | if not self.input.endswith('\n'): |
| 106 | input_buffer.write('\n') |
| 107 | input_buffer.seek(0, 0) |
| 108 | input_buffer.flush() |
| 109 | return self.get_results([X_SCRIPT] + self.options + self.filenames, |
| 110 | input_buffer) |
| 111 | |
| 112 | def get_posttest_result(self): |
| 113 | if not self.posttest: |
| 114 | return 0 |
| 115 | self.write_script(self.posttest) |
| 116 | return subprocess.call(['sh', TESTSCRIPT_NAME]) |
| 117 | |
| 118 | def clean(self): |
| 119 | self.run_script('cleanup') |
| 120 | if self.directory: |
| 121 | target = os.path.join(ROOT_DIR, self.directory) |
| 122 | extra_options = ['!', '-name', TESTSCRIPT_NAME] |
| 123 | else: |
| 124 | target = ROOT_DIR |
| 125 | extra_options = ['(', '(', '-type', 'd', |
| 126 | '!', '-name', 'CVS', |
| 127 | '!', '-name', '.svn', ')', |
| 128 | '-or', '-name', 'test-text', |
| 129 | '-or', '-name', 'test-onefile', ')'] |
| 130 | status = subprocess.call(['find', target, |
| 131 | '-mindepth', '1', '-maxdepth', '1'] + |
| 132 | extra_options + |
| 133 | ['-exec', 'rm', '-rf', '{}', ';']) |
| 134 | if status != 0: |
| 135 | raise ExtractorTestError("cleanup exited with status code %s" % |
| 136 | (status,)) |
| 137 | |
| 138 | def show_status(self, status, message=None): |
| 139 | raw_status = status.lower() |
| 140 | if raw_status != 'passed': |
| 141 | output_buffer.seek(0, 0) |
| 142 | sys.stdout.write(output_buffer.read(-1)) |
| 143 | if message is None: |
| 144 | last_part = '' |
| 145 | else: |
| 146 | last_part = ': %s' % (message,) |
| 147 | print "%7s: %s%s" % (status, self.name, last_part) |
| 148 | return raw_status |
| 149 | |
| 150 | def compare_results(self, actual): |
| 151 | posttest_result = self.get_posttest_result() |
| 152 | self.clean() |
| 153 | status, expected = self.get_shell_results() |
| 154 | self.clean() |
| 155 | if expected != actual: |
| 156 | print >>output_buffer, "Only in baseline results:" |
| 157 | print >>output_buffer, '\n'.join(expected.difference(actual)) |
| 158 | print >>output_buffer, "Only in actual results:" |
| 159 | print >>output_buffer, '\n'.join(actual.difference(expected)) |
| 160 | return self.show_status('FAILED') |
| 161 | elif posttest_result != 0: |
| 162 | print >>output_buffer, "Posttest gave status code", posttest_result |
| 163 | return self.show_status('FAILED') |
| 164 | return self.show_status('Passed') |
| 165 | |
| 166 | def have_error_mismatch(self, status): |
| 167 | if self.error and (status == 0): |
| 168 | return "dtrx did not return expected error" |
| 169 | elif (not self.error) and (status != 0): |
| 170 | return "dtrx returned error code %s" % (status,) |
| 171 | return None |
| 172 | |
| 173 | def grep_output(self, output): |
| 174 | for pattern in self.grep: |
| 175 | if not re.search(pattern.replace(' ', '\\s+'), output, |
| 176 | re.MULTILINE): |
| 177 | return "output did not match %s" % (pattern) |
| 178 | for pattern in self.antigrep: |
| 179 | if re.search(pattern.replace(' ', '\\s+'), output, re.MULTILINE): |
| 180 | return "output matched antigrep %s" % (self.antigrep) |
| 181 | return None |
| 182 | |
| 183 | def check_output(self, output): |
| 184 | if ((self.output is not None) and |
| 185 | (self.output.strip() != output.strip())): |
| 186 | return "output did not match provided text" |
| 187 | return None |
| 188 | |
| 189 | def check_results(self): |
| 190 | output_buffer.seek(0, 0) |
| 191 | output_buffer.truncate() |
| 192 | self.clean() |
| 193 | status, actual = self.get_extractor_results() |
| 194 | output_buffer.seek(0, 0) |
| 195 | output_buffer.readline() |
| 196 | output = output_buffer.read(-1) |
| 197 | problem = (self.have_error_mismatch(status) or |
| 198 | self.check_output(output) or self.grep_output(output)) |
| 199 | if problem: |
| 200 | return self.show_status('FAILED', problem) |
| 201 | if self.baseline: |
| 202 | return self.compare_results(actual) |
| 203 | else: |
| 204 | self.clean() |
| 205 | return self.show_status('Passed') |
| 206 | |
| 207 | def run(self): |
| 208 | if self.directory: |
| 209 | os.mkdir(self.directory) |
| 210 | os.chdir(self.directory) |
| 211 | try: |
| 212 | result = self.check_results() |
| 213 | except ExtractorTestError, error: |
| 214 | result = self.show_status('ERROR', error) |
| 215 | if self.directory: |
| 216 | os.chdir(ROOT_DIR) |
| 217 | subprocess.call(['chmod', '-R', '700', self.directory]) |
| 218 | subprocess.call(['rm', '-rf', self.directory]) |
| 219 | return result |
| 220 | |
| 221 | |
| 222 | test_db = open('tests.yml') |
| 223 | test_data = yaml.load(test_db.read(-1)) |
| 224 | test_db.close() |
| 225 | tests = [ExtractorTest(**data) for data in test_data] |
| 226 | for original_data in test_data: |
| 227 | if (original_data.has_key('directory') or |
| 228 | (not original_data.has_key('baseline'))): |
| 229 | continue |
| 230 | data = original_data.copy() |
| 231 | data['name'] += ' in ..' |
| 232 | data['directory'] = 'inside-dir' |
| 233 | data['filenames'] = ' '.join(['../%s' % filename for filename in |
| 234 | data.get('filenames', '').split()]) |
| 235 | tests.append(ExtractorTest(**data)) |
| 236 | results = [test.run() for test in tests] |
| 237 | counts = {} |
| 238 | for outcome in OUTCOMES: |
| 239 | counts[outcome] = 0 |
| 240 | for result in results: |
| 241 | counts[result] += 1 |
| 242 | print " Totals:", ', '.join(["%s %s" % (counts[key], key) for key in OUTCOMES]) |
| 243 | input_buffer.close() |
| 244 | output_buffer.close() |