test_basic.py 53.7 KB
Newer Older
1
# This Python file uses the following encoding: utf-8
2 3
import aexpect
import glob
4
import json
5
import os
6
import re
7
import shutil
8
import signal
9
import sys
10
import tempfile
11
import time
12
import xml.dom.minidom
13
import zipfile
14
import unittest
15
import psutil
16
import pkg_resources
17

18 19 20
from lxml import etree
from StringIO import StringIO

21
from avocado.core import exit_codes
22
from avocado.utils import astring
23 24
from avocado.utils import process
from avocado.utils import script
25
from avocado.utils import path as utils_path
26

27
basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')
28 29
basedir = os.path.abspath(basedir)

30 31
AVOCADO = os.environ.get("UNITTEST_AVOCADO_CMD", "./scripts/avocado")

32 33 34 35
PASS_SCRIPT_CONTENTS = """#!/bin/sh
true
"""

C
Cleber Rosa 已提交
36 37
PASS_SHELL_CONTENTS = "exit 0"

38 39 40 41
FAIL_SCRIPT_CONTENTS = """#!/bin/sh
false
"""

C
Cleber Rosa 已提交
42 43
FAIL_SHELL_CONTENTS = "exit 1"

44 45 46 47 48 49 50 51 52 53 54 55 56 57
HELLO_LIB_CONTENTS = """
def hello():
    return 'Hello world'
"""

LOCAL_IMPORT_TEST_CONTENTS = '''
from avocado import Test
from mylib import hello

class LocalImportTest(Test):
    def test(self):
        self.log.info(hello())
'''

58 59 60 61 62 63
UNSUPPORTED_STATUS_TEST_CONTENTS = '''
from avocado import Test

class FakeStatusTest(Test):
    def run_avocado(self):
        super(FakeStatusTest, self).run_avocado()
64 65
        # Please do NOT ever use this, it's for unittesting only.
        self._Test__status = 'not supported'
66 67 68 69 70

    def test(self):
        pass
'''

71 72 73 74 75 76 77 78 79 80 81
INVALID_PYTHON_TEST = '''
from avocado import Test

class MyTest(Test):

    non_existing_variable_causing_crash

    def test_my_name(self):
        pass
'''

82

83 84 85 86 87 88 89
REPORTS_STATUS_AND_HANG = '''
from avocado import Test
import time

class MyTest(Test):
    def test(self):
         self.runner_queue.put({"running": False})
90
         time.sleep(70)
91 92
'''

93

94 95 96 97 98 99 100 101 102 103 104
DIE_WITHOUT_REPORTING_STATUS = '''
from avocado import Test
import os
import signal

class MyTest(Test):
    def test(self):
         os.kill(os.getpid(), signal.SIGKILL)
'''


A
Amador Pahim 已提交
105
def probe_binary(binary):
106
    try:
A
Amador Pahim 已提交
107
        return utils_path.find_command(binary)
108
    except utils_path.CmdNotFoundError:
A
Amador Pahim 已提交
109 110
        return None

L
Lukáš Doktor 已提交
111

112
TRUE_CMD = probe_binary('true')
A
Amador Pahim 已提交
113
CC_BINARY = probe_binary('cc')
114

L
Lukáš Doktor 已提交
115
# On macOS, the default GNU core-utils installation (brew)
116 117 118 119 120
# installs the gnu utility versions with a g prefix. It still has the
# BSD versions of the core utilities installed on their expected paths
# but their behavior and flags are in most cases different.
GNU_ECHO_BINARY = probe_binary('echo')
if GNU_ECHO_BINARY is not None:
121 122 123 124
    if probe_binary('man') is not None:
        echo_manpage = process.run('man %s' % os.path.basename(GNU_ECHO_BINARY)).stdout
        if '-e' not in echo_manpage:
            GNU_ECHO_BINARY = probe_binary('gecho')
A
Amador Pahim 已提交
125 126
READ_BINARY = probe_binary('read')
SLEEP_BINARY = probe_binary('sleep')
127 128


129 130
class RunnerOperationTest(unittest.TestCase):

131
    def setUp(self):
132
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
133

134
    def test_show_version(self):
135
        result = process.run('%s -v' % AVOCADO, ignore_status=True)
136
        self.assertEqual(result.exit_status, 0)
C
Cleber Rosa 已提交
137 138 139
        self.assertTrue(re.match(r"^Avocado \d+\.\d+$", result.stderr),
                        "Version string does not match 'Avocado \\d\\.\\d:'\n"
                        "%r" % (result.stderr))
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    def test_alternate_config_datadir(self):
        """
        Uses the "--config" flag to check custom configuration is applied

        Even on the more complex data_dir module, which adds extra checks
        to what is set on the plain settings module.
        """
        base_dir = os.path.join(self.tmpdir, 'datadir_base')
        os.mkdir(base_dir)
        mapping = {'base_dir': base_dir,
                   'test_dir': os.path.join(base_dir, 'test'),
                   'data_dir': os.path.join(base_dir, 'data'),
                   'logs_dir': os.path.join(base_dir, 'logs')}
        config = '[datadir.paths]'
        for key, value in mapping.iteritems():
            if not os.path.isdir(value):
                os.mkdir(value)
            config += "%s = %s\n" % (key, value)
        fd, config_file = tempfile.mkstemp(dir=self.tmpdir)
        os.write(fd, config)
        os.close(fd)

        os.chdir(basedir)
164
        cmd = '%s --config %s config --datadir' % (AVOCADO, config_file)
165 166 167 168 169 170 171 172 173 174
        result = process.run(cmd)
        output = result.stdout
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('    base     ' + mapping['base_dir'], result.stdout)
        self.assertIn('    data     ' + mapping['data_dir'], result.stdout)
        self.assertIn('    logs     ' + mapping['logs_dir'], result.stdout)

175 176
    def test_runner_all_ok(self):
        os.chdir(basedir)
177 178
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py passtest.py' % (AVOCADO, self.tmpdir))
179 180
        process.run(cmd_line)

181 182
    def test_runner_failfast(self):
        os.chdir(basedir)
183 184 185
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py failtest.py passtest.py --failfast on'
                    % (AVOCADO, self.tmpdir))
186 187 188 189 190 191 192
        result = process.run(cmd_line, ignore_status=True)
        self.assertIn('Interrupting job (failfast).', result.stdout)
        self.assertIn('PASS 1 | ERROR 0 | FAIL 1 | SKIP 1', result.stdout)
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL | exit_codes.AVOCADO_JOB_INTERRUPTED
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

A
Amador Pahim 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    def test_runner_ignore_missing_references_one_missing(self):
        os.chdir(basedir)
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py badtest.py --ignore-missing-references on'
                    % (AVOCADO, self.tmpdir))
        result = process.run(cmd_line, ignore_status=True)
        self.assertIn("Unable to resolve reference(s) 'badtest.py'", result.stderr)
        self.assertIn('PASS 1 | ERROR 0 | FAIL 0 | SKIP 0', result.stdout)
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

    def test_runner_ignore_missing_references_all_missing(self):
        os.chdir(basedir)
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'badtest.py badtest2.py --ignore-missing-references on'
                    % (AVOCADO, self.tmpdir))
        result = process.run(cmd_line, ignore_status=True)
        self.assertIn("Unable to resolve reference(s) 'badtest.py', 'badtest2.py'",
                      result.stderr)
        self.assertEqual('', result.stdout)
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

A
Amador Pahim 已提交
218
    @unittest.skipIf(not CC_BINARY,
219
                     "C compiler is required by the underlying datadir.py test")
220 221
    def test_datadir_alias(self):
        os.chdir(basedir)
222 223
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'datadir.py' % (AVOCADO, self.tmpdir))
224 225 226 227 228
        process.run(cmd_line)

    def test_shell_alias(self):
        """ Tests that .sh files are also executable via alias """
        os.chdir(basedir)
229 230
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'env_variables.sh' % (AVOCADO, self.tmpdir))
231 232
        process.run(cmd_line)

A
Amador Pahim 已提交
233
    @unittest.skipIf(not CC_BINARY,
234
                     "C compiler is required by the underlying datadir.py test")
235 236
    def test_datadir_noalias(self):
        os.chdir(basedir)
237 238
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s examples/tests/datadir.py '
                    'examples/tests/datadir.py' % (AVOCADO, self.tmpdir))
239 240
        process.run(cmd_line)

241 242
    def test_runner_noalias(self):
        os.chdir(basedir)
243 244
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s examples/tests/passtest.py "
                    "examples/tests/passtest.py" % (AVOCADO, self.tmpdir))
245 246
        process.run(cmd_line)

247 248 249 250 251 252 253 254 255 256 257
    def test_runner_test_with_local_imports(self):
        mylib = script.TemporaryScript(
            'mylib.py',
            HELLO_LIB_CONTENTS,
            'avocado_simpletest_functional')
        mylib.save()
        mytest = script.Script(
            os.path.join(os.path.dirname(mylib.path), 'test_local_imports.py'),
            LOCAL_IMPORT_TEST_CONTENTS)
        os.chdir(basedir)
        mytest.save()
258 259
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s "
                    "%s" % (AVOCADO, self.tmpdir, mytest))
260 261
        process.run(cmd_line)

262 263 264 265 266
    def test_unsupported_status(self):
        os.chdir(basedir)
        with script.TemporaryScript("fake_status.py",
                                    UNSUPPORTED_STATUS_TEST_CONTENTS,
                                    "avocado_unsupported_status") as tst:
267 268 269
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s"
                              " --json -" % (AVOCADO, self.tmpdir, tst),
                              ignore_status=True)
270 271 272 273 274
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
            results = json.loads(res.stdout)
            self.assertEqual(results["tests"][0]["status"], "ERROR",
                             "%s != %s\n%s" % (results["tests"][0]["status"],
                                               "ERROR", res))
275
            self.assertIn("Runner error occurred: Test reports unsupported",
276 277
                          results["tests"][0]["fail_reason"])

278 279 280 281 282 283
    def test_hanged_test_with_status(self):
        """ Check that avocado handles hanged tests properly """
        os.chdir(basedir)
        with script.TemporaryScript("report_status_and_hang.py",
                                    REPORTS_STATUS_AND_HANG,
                                    "hanged_test_with_status") as tst:
284
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s "
285
                              "--json - --job-timeout 1" % (AVOCADO, self.tmpdir, tst),
286
                              ignore_status=True)
287 288 289 290 291 292 293
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
            results = json.loads(res.stdout)
            self.assertEqual(results["tests"][0]["status"], "ERROR",
                             "%s != %s\n%s" % (results["tests"][0]["status"],
                                               "ERROR", res))
            self.assertIn("Test reported status but did not finish",
                          results["tests"][0]["fail_reason"])
294 295 296 297 298
            # Currently it should finish up to 1s after the job-timeout
            # but the prep and postprocess could take a bit longer on
            # some environments, so let's just check it does not take
            # > 60s, which is the deadline for force-finishing the test.
            self.assertLess(res.duration, 55, "Test execution took too long, "
299 300 301 302 303 304 305 306
                            "which is likely because the hanged test was not "
                            "interrupted. Results:\n%s" % res)

    def test_no_status_reported(self):
        os.chdir(basedir)
        with script.TemporaryScript("die_without_reporting_status.py",
                                    DIE_WITHOUT_REPORTING_STATUS,
                                    "no_status_reported") as tst:
307 308 309
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s "
                              "--json -" % (AVOCADO, self.tmpdir, tst),
                              ignore_status=True)
310 311 312 313 314 315 316 317
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
            results = json.loads(res.stdout)
            self.assertEqual(results["tests"][0]["status"], "ERROR",
                             "%s != %s\n%s" % (results["tests"][0]["status"],
                                               "ERROR", res))
            self.assertIn("Test died without reporting the status",
                          results["tests"][0]["fail_reason"])

318 319
    def test_runner_tests_fail(self):
        os.chdir(basedir)
320 321
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s passtest.py '
                    'failtest.py passtest.py' % (AVOCADO, self.tmpdir))
322
        result = process.run(cmd_line, ignore_status=True)
323
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
324 325 326 327 328
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

    def test_runner_nonexistent_test(self):
        os.chdir(basedir)
329 330
        cmd_line = ('%s run --sysinfo=off --job-results-dir '
                    '%s bogustest' % (AVOCADO, self.tmpdir))
331
        result = process.run(cmd_line, ignore_status=True)
332 333
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
334 335 336 337 338
        self.assertNotEqual(result.exit_status, unexpected_rc,
                            "Avocado crashed (rc %d):\n%s" % (unexpected_rc, result))
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

339 340
    def test_runner_doublefail(self):
        os.chdir(basedir)
341 342
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    '--xunit - doublefail.py' % (AVOCADO, self.tmpdir))
343 344
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
345 346
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
347 348 349 350
        self.assertNotEqual(result.exit_status, unexpected_rc,
                            "Avocado crashed (rc %d):\n%s" % (unexpected_rc, result))
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))
351
        self.assertIn("TestError: Failing during tearDown. Yay!", output,
352
                      "Cleanup exception not printed to log output")
353
        self.assertIn("TestFail: This test is supposed to fail",
354
                      output,
355
                      "Test did not fail with action exception:\n%s" % output)
356

357 358
    def test_uncaught_exception(self):
        os.chdir(basedir)
359 360
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s "
                    "--json - uncaught_exception.py" % (AVOCADO, self.tmpdir))
361
        result = process.run(cmd_line, ignore_status=True)
362
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
363 364 365 366 367
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc,
                                                                result))
        self.assertIn('"status": "ERROR"', result.stdout)

368
    def test_fail_on_exception(self):
369
        os.chdir(basedir)
370 371
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s "
                    "--json - fail_on_exception.py" % (AVOCADO, self.tmpdir))
372
        result = process.run(cmd_line, ignore_status=True)
373
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
374 375 376 377 378
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc,
                                                                result))
        self.assertIn('"status": "FAIL"', result.stdout)

379 380
    def test_runner_timeout(self):
        os.chdir(basedir)
381 382
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    '--xunit - timeouttest.py' % (AVOCADO, self.tmpdir))
383 384
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
385
        expected_rc = exit_codes.AVOCADO_JOB_INTERRUPTED
386
        unexpected_rc = exit_codes.AVOCADO_FAIL
387 388 389 390
        self.assertNotEqual(result.exit_status, unexpected_rc,
                            "Avocado crashed (rc %d):\n%s" % (unexpected_rc, result))
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))
391
        self.assertIn("Runner error occurred: Timeout reached", output,
392
                      "Timeout reached message not found in the output:\n%s" % output)
393 394
        # Ensure no test aborted error messages show up
        self.assertNotIn("TestAbortedError: Test aborted unexpectedly", output)
395

396
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 2,
397 398
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
399 400
    def test_runner_abort(self):
        os.chdir(basedir)
401 402
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    '--xunit - abort.py' % (AVOCADO, self.tmpdir))
403
        result = process.run(cmd_line, ignore_status=True)
404
        output = result.stdout
405
        excerpt = 'Test died without reporting the status.'
406 407
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
408 409 410 411
        self.assertNotEqual(result.exit_status, unexpected_rc,
                            "Avocado crashed (rc %d):\n%s" % (unexpected_rc, result))
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))
412
        self.assertIn(excerpt, output)
413

414 415
    def test_silent_output(self):
        os.chdir(basedir)
416 417
        cmd_line = ('%s --silent run --sysinfo=off --job-results-dir %s '
                    'passtest.py' % (AVOCADO, self.tmpdir))
418
        result = process.run(cmd_line, ignore_status=True)
419
        expected_rc = exit_codes.AVOCADO_ALL_OK
420 421
        expected_output = ''
        self.assertEqual(result.exit_status, expected_rc)
422
        self.assertEqual(result.stdout, expected_output)
423

424 425
    def test_empty_args_list(self):
        os.chdir(basedir)
426
        cmd_line = AVOCADO
427
        result = process.run(cmd_line, ignore_status=True)
428
        expected_rc = exit_codes.AVOCADO_FAIL
429
        expected_output = 'error: too few arguments'
430
        self.assertEqual(result.exit_status, expected_rc)
431
        self.assertIn(expected_output, result.stderr)
432

433 434
    def test_empty_test_list(self):
        os.chdir(basedir)
435 436
        cmd_line = '%s run --sysinfo=off --job-results-dir %s' % (AVOCADO,
                                                                  self.tmpdir)
437
        result = process.run(cmd_line, ignore_status=True)
438
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
439 440
        expected_output = ('No test references provided nor any other '
                           'arguments resolved into tests')
441
        self.assertEqual(result.exit_status, expected_rc)
442
        self.assertIn(expected_output, result.stderr)
443

444 445
    def test_not_found(self):
        os.chdir(basedir)
446 447
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s sbrubles'
                    % (AVOCADO, self.tmpdir))
448
        result = process.run(cmd_line, ignore_status=True)
449
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
450
        self.assertEqual(result.exit_status, expected_rc)
451 452
        self.assertIn('Unable to resolve reference', result.stderr)
        self.assertNotIn('Unable to resolve reference', result.stdout)
453

454
    def test_invalid_unique_id(self):
455 456
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s --force-job-id '
                    'foobar passtest.py' % (AVOCADO, self.tmpdir))
457
        result = process.run(cmd_line, ignore_status=True)
458
        self.assertNotEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
459
        self.assertIn('needs to be a 40 digit hex', result.stderr)
460
        self.assertNotIn('needs to be a 40 digit hex', result.stdout)
461 462

    def test_valid_unique_id(self):
463
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
464
                    '--force-job-id 975de258ac05ce5e490648dec4753657b7ccc7d1 '
465
                    'passtest.py' % (AVOCADO, self.tmpdir))
466
        result = process.run(cmd_line, ignore_status=True)
467
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
468
        self.assertNotIn('needs to be a 40 digit hex', result.stderr)
469
        self.assertIn('PASS', result.stdout)
470

471
    def test_automatic_unique_id(self):
472 473
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    'passtest.py --json -' % (AVOCADO, self.tmpdir))
474
        result = process.run(cmd_line, ignore_status=True)
475
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
476 477 478 479
        r = json.loads(result.stdout)
        int(r['job_id'], 16)  # it's an hex number
        self.assertEqual(len(r['job_id']), 40)

480 481 482 483 484
    def test_early_latest_result(self):
        """
        Tests that the `latest` link to the latest job results is created early
        """
        os.chdir(basedir)
485 486
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'examples/tests/passtest.py' % (AVOCADO, self.tmpdir))
487 488 489 490 491 492
        avocado_process = process.SubProcess(cmd_line)
        avocado_process.start()
        link = os.path.join(self.tmpdir, 'latest')
        for trial in xrange(0, 50):
            time.sleep(0.1)
            if os.path.exists(link) and os.path.islink(link):
493
                avocado_process.wait()
494 495 496 497
                break
        self.assertTrue(os.path.exists(link))
        self.assertTrue(os.path.islink(link))

498 499
    def test_dry_run(self):
        os.chdir(basedir)
500
        cmd = ("%s run --sysinfo=off passtest.py failtest.py "
501
               "gendata.py --json - --mux-inject foo:1 bar:2 baz:3 foo:foo:a"
502
               " foo:bar:b foo:baz:c bar:bar:bar --dry-run" % AVOCADO)
503 504 505 506 507
        result = json.loads(process.run(cmd).stdout)
        debuglog = result['debuglog']
        log = open(debuglog, 'r').read()
        # Remove the result dir
        shutil.rmtree(os.path.dirname(os.path.dirname(debuglog)))
508
        self.assertIn(tempfile.gettempdir(), debuglog)   # Use tmp dir, not default location
509 510
        self.assertEqual(result['job_id'], u'0' * 40)
        # Check if all tests were skipped
511
        self.assertEqual(result['cancel'], 4)
512
        for i in xrange(4):
513 514
            test = result['tests'][i]
            self.assertEqual(test['fail_reason'],
515
                             u'Test cancelled due to --dry-run')
516 517 518 519 520
        # Check if all params are listed
        # The "/:bar ==> 2 is in the tree, but not in any leave so inaccessible
        # from test.
        for line in ("/:foo ==> 1", "/:baz ==> 3", "/foo:foo ==> a",
                     "/foo:bar ==> b", "/foo:baz ==> c", "/bar:bar ==> bar"):
521
            self.assertEqual(log.count(line), 4)
522

523 524 525 526
    def test_invalid_python(self):
        os.chdir(basedir)
        test = script.make_script(os.path.join(self.tmpdir, 'test.py'),
                                  INVALID_PYTHON_TEST)
527 528
        cmd_line = ('%s --show test run --sysinfo=off '
                    '--job-results-dir %s %s') % (AVOCADO, self.tmpdir, test)
529 530 531 532 533
        result = process.run(cmd_line, ignore_status=True)
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
534 535
        self.assertIn('1-%s:MyTest.test_my_name -> TestError' % test,
                      result.stdout)
536

A
Amador Pahim 已提交
537
    @unittest.skipIf(not READ_BINARY, "read binary not available.")
L
Lukáš Doktor 已提交
538 539
    def test_read(self):
        os.chdir(basedir)
540
        cmd = "%s run --sysinfo=off --job-results-dir %%s %%s" % AVOCADO
541
        cmd %= (self.tmpdir, READ_BINARY)
542
        result = process.run(cmd, timeout=10, ignore_status=True)
L
Lukáš Doktor 已提交
543 544 545 546 547
        self.assertLess(result.duration, 8, "Duration longer than expected."
                        "\n%s" % result)
        self.assertEqual(result.exit_status, 1, "Expected exit status is 1\n%s"
                         % result)

548 549 550
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

551

552 553 554
class RunnerHumanOutputTest(unittest.TestCase):

    def setUp(self):
555
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
556 557 558

    def test_output_pass(self):
        os.chdir(basedir)
559 560
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py' % (AVOCADO, self.tmpdir))
561
        result = process.run(cmd_line, ignore_status=True)
562
        expected_rc = exit_codes.AVOCADO_ALL_OK
563 564 565 566 567 568 569
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('passtest.py:PassTest.test:  PASS', result.stdout)

    def test_output_fail(self):
        os.chdir(basedir)
570 571
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'failtest.py' % (AVOCADO, self.tmpdir))
572
        result = process.run(cmd_line, ignore_status=True)
573
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
574 575 576 577 578 579 580
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('failtest.py:FailTest.test:  FAIL', result.stdout)

    def test_output_error(self):
        os.chdir(basedir)
581 582
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'errortest.py' % (AVOCADO, self.tmpdir))
583
        result = process.run(cmd_line, ignore_status=True)
584
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
585 586 587 588 589
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('errortest.py:ErrorTest.test:  ERROR', result.stdout)

A
Amador Pahim 已提交
590
    def test_output_cancel(self):
591
        os.chdir(basedir)
592 593
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'cancelonsetup.py' % (AVOCADO, self.tmpdir))
594
        result = process.run(cmd_line, ignore_status=True)
595
        expected_rc = exit_codes.AVOCADO_ALL_OK
596 597 598
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
A
Amador Pahim 已提交
599 600
        self.assertIn('PASS 0 | ERROR 0 | FAIL 0 | SKIP 0 | WARN 0 | INTERRUPT 0 | CANCEL 1',
                      result.stdout)
601

602 603
    @unittest.skipIf(not GNU_ECHO_BINARY,
                     'GNU style echo binary not available')
604 605
    def test_ugly_echo_cmd(self):
        os.chdir(basedir)
606
        cmd_line = ('%s run --external-runner "%s -ne" '
607
                    '"foo\\\\\\n\\\'\\\\\\"\\\\\\nbar/baz" --job-results-dir %s'
A
Amador Pahim 已提交
608
                    ' --sysinfo=off  --show-job-log' %
609
                    (AVOCADO, GNU_ECHO_BINARY, self.tmpdir))
610 611 612 613 614
        result = process.run(cmd_line, ignore_status=True)
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %s:\n%s" %
                         (expected_rc, result))
615 616 617
        self.assertIn('[stdout] foo', result.stdout, result)
        self.assertIn('[stdout] \'"', result.stdout, result)
        self.assertIn('[stdout] bar/baz', result.stdout, result)
618 619
        self.assertIn('PASS 1-foo\\\\n\\\'\\"\\\\nbar/baz',
                      result.stdout, result)
620 621 622 623 624 625 626
        # logdir name should escape special chars (/)
        test_dirs = glob.glob(os.path.join(self.tmpdir, 'latest',
                                           'test-results', '*'))
        self.assertEqual(len(test_dirs), 1, "There are multiple directories in"
                         " test-results dir, but only one test was executed: "
                         "%s" % (test_dirs))
        self.assertEqual(os.path.basename(test_dirs[0]),
627
                         '1-foo\\\\n\\\'\\"\\\\nbar_baz')
628

629
    def test_replay_skip_skipped(self):
630 631
        cmd = ("%s run --job-results-dir %s --json - "
               "cancelonsetup.py" % (AVOCADO, self.tmpdir))
632
        result = process.run(cmd)
633
        result = json.loads(result.stdout)
634
        jobid = str(result["job_id"])
635 636
        cmd = ("%s run --job-results-dir %s --replay %s "
               "--replay-test-status PASS" % (AVOCADO, self.tmpdir, jobid))
637
        process.run(cmd)
638

639 640 641
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

642

643
class RunnerSimpleTest(unittest.TestCase):
644 645

    def setUp(self):
646
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
647
        self.pass_script = script.TemporaryScript(
648
            'ʊʋʉʈɑ ʅʛʌ',
649
            PASS_SCRIPT_CONTENTS,
650
            'avocado_simpletest_functional')
651
        self.pass_script.save()
L
Lukáš Doktor 已提交
652 653 654 655
        self.fail_script = script.TemporaryScript('avocado_fail.sh',
                                                  FAIL_SCRIPT_CONTENTS,
                                                  'avocado_simpletest_'
                                                  'functional')
656
        self.fail_script.save()
657

658
    def test_simpletest_pass(self):
659
        os.chdir(basedir)
660 661
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' "%s"' % (AVOCADO, self.tmpdir, self.pass_script.path))
662
        result = process.run(cmd_line, ignore_status=True)
663
        expected_rc = exit_codes.AVOCADO_ALL_OK
664 665 666 667
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

668
    def test_simpletest_fail(self):
669
        os.chdir(basedir)
670 671
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' %s' % (AVOCADO, self.tmpdir, self.fail_script.path))
672
        result = process.run(cmd_line, ignore_status=True)
673
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
674 675 676 677
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

678
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 2,
679 680
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
681 682
    def test_runner_onehundred_fail_timing(self):
        """
A
Amador Pahim 已提交
683
        We can be pretty sure that a failtest should return immediately. Let's
684
        run 100 of them and assure they not take more than 30 seconds to run.
685

686 687
        Notice: on a current machine this takes about 0.12s, so 30 seconds is
        considered to be pretty safe here.
688 689
        """
        os.chdir(basedir)
690
        one_hundred = 'failtest.py ' * 100
691 692
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off %s'
                    % (AVOCADO, self.tmpdir, one_hundred))
693 694 695
        initial_time = time.time()
        result = process.run(cmd_line, ignore_status=True)
        actual_time = time.time() - initial_time
696
        self.assertLess(actual_time, 30.0)
697
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
698 699 700 701 702 703 704 705 706
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

    def test_runner_sleep_fail_sleep_timing(self):
        """
        Sleeptest is supposed to take 1 second, let's make a sandwich of
        100 failtests and check the test runner timing.
        """
        os.chdir(basedir)
707 708
        sleep_fail_sleep = ('sleeptest.py ' + 'failtest.py ' * 100 +
                            'sleeptest.py')
709 710
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off %s'
                    % (AVOCADO, self.tmpdir, sleep_fail_sleep))
711 712 713
        initial_time = time.time()
        result = process.run(cmd_line, ignore_status=True)
        actual_time = time.time() - initial_time
714
        self.assertLess(actual_time, 33.0)
715
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
716 717 718
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

719 720 721 722 723
    def test_simplewarning(self):
        """
        simplewarning.sh uses the avocado-bash-utils
        """
        os.chdir(basedir)
724 725 726
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    'examples/tests/simplewarning.sh --show-job-log'
                    % (AVOCADO, self.tmpdir))
727
        result = process.run(cmd_line, ignore_status=True)
728 729 730 731
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %s:\n%s" %
                         (expected_rc, result))
732 733
        self.assertIn('DEBUG| Debug message', result.stdout, result)
        self.assertIn('INFO | Info message', result.stdout, result)
734
        self.assertIn('WARN | Warning message (should cause this test to '
735
                      'finish with warning)', result.stdout, result)
736
        self.assertIn('ERROR| Error message (ordinary message not changing '
737
                      'the results)', result.stdout, result)
738

739 740 741 742 743 744
    def test_non_absolute_path(self):
        avocado_path = os.path.join(basedir, 'scripts', 'avocado')
        test_base_dir = os.path.dirname(self.pass_script.path)
        test_file_name = os.path.basename(self.pass_script.path)
        os.chdir(test_base_dir)
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
745
                    ' "%s"' % (avocado_path, self.tmpdir, test_file_name))
746 747 748 749 750 751
        result = process.run(cmd_line, ignore_status=True)
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

A
Amador Pahim 已提交
752
    @unittest.skipIf(not SLEEP_BINARY, 'sleep binary not available')
753
    def test_kill_stopped_sleep(self):
754 755 756 757
        proc = aexpect.Expect("%s run 60 --job-results-dir %s "
                              "--external-runner %s --sysinfo=off "
                              "--job-timeout 3"
                              % (AVOCADO, self.tmpdir, SLEEP_BINARY))
758 759
        proc.read_until_output_matches(["\(1/1\)"], timeout=3,
                                       internal_timeout=0.01)
760 761 762 763
        # We need pid of the avocado process, not the shell executing it
        avocado_shell = psutil.Process(proc.get_pid())
        avocado_proc = avocado_shell.children()[0]
        pid = avocado_proc.pid
764
        os.kill(pid, signal.SIGTSTP)   # This freezes the process
765
        deadline = time.time() + 9
766 767 768
        while time.time() < deadline:
            if not proc.is_alive():
                break
769
            time.sleep(0.1)
770 771
        else:
            proc.kill(signal.SIGKILL)
772
            self.fail("Avocado process still alive 5s after job-timeout:\n%s"
773 774 775 776 777 778 779
                      % proc.get_output())
        output = proc.get_output()
        self.assertIn("ctrl+z pressed, stopping test", output, "SIGTSTP "
                      "message not in the output, test was probably not "
                      "stopped.")
        self.assertIn("TIME", output, "TIME not in the output, avocado "
                      "probably died unexpectadly")
780
        self.assertEqual(proc.get_status(), 8, "Avocado did not finish with "
781
                         "1.")
782 783

        sleep_dir = astring.string_to_safe_path("1-60")
784
        debug_log = os.path.join(self.tmpdir, "latest", "test-results",
785
                                 sleep_dir, "debug.log")
786
        debug_log = open(debug_log).read()
787 788 789 790 791 792 793
        self.assertIn("Runner error occurred: Timeout reached", debug_log,
                      "Runner error occurred: Timeout reached message not "
                      "in the test's debug.log:\n%s" % debug_log)
        self.assertNotIn("Traceback (most recent", debug_log, "Traceback "
                         "present in the test's debug.log file, but it was "
                         "suppose to be stopped and unable to produce it.\n"
                         "%s" % debug_log)
794

795
    def tearDown(self):
796 797
        self.pass_script.remove()
        self.fail_script.remove()
798
        shutil.rmtree(self.tmpdir)
799 800


801
class ExternalRunnerTest(unittest.TestCase):
C
Cleber Rosa 已提交
802 803

    def setUp(self):
804
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
C
Cleber Rosa 已提交
805 806 807
        self.pass_script = script.TemporaryScript(
            'pass',
            PASS_SHELL_CONTENTS,
808
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
809 810 811 812
        self.pass_script.save()
        self.fail_script = script.TemporaryScript(
            'fail',
            FAIL_SHELL_CONTENTS,
813
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
814 815
        self.fail_script.save()

816
    def test_externalrunner_pass(self):
C
Cleber Rosa 已提交
817
        os.chdir(basedir)
818 819 820
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    '--external-runner=/bin/sh %s'
                    % (AVOCADO, self.tmpdir, self.pass_script.path))
C
Cleber Rosa 已提交
821
        result = process.run(cmd_line, ignore_status=True)
822
        expected_rc = exit_codes.AVOCADO_ALL_OK
C
Cleber Rosa 已提交
823 824 825 826
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

827
    def test_externalrunner_fail(self):
C
Cleber Rosa 已提交
828
        os.chdir(basedir)
829 830 831
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    '--external-runner=/bin/sh %s'
                    % (AVOCADO, self.tmpdir, self.fail_script.path))
C
Cleber Rosa 已提交
832
        result = process.run(cmd_line, ignore_status=True)
833
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
C
Cleber Rosa 已提交
834 835 836 837
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

838
    def test_externalrunner_chdir_no_testdir(self):
C
Cleber Rosa 已提交
839
        os.chdir(basedir)
840 841 842
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    '--external-runner=/bin/sh --external-runner-chdir=test %s'
                    % (AVOCADO, self.tmpdir, self.pass_script.path))
C
Cleber Rosa 已提交
843
        result = process.run(cmd_line, ignore_status=True)
844 845
        expected_output = ('Option "--external-runner-chdir=test" requires '
                           '"--external-runner-testdir" to be set')
C
Cleber Rosa 已提交
846
        self.assertIn(expected_output, result.stderr)
847
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
848 849 850 851 852 853
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

    def test_externalrunner_no_url(self):
        os.chdir(basedir)
854 855
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    '--external-runner=%s' % (AVOCADO, self.tmpdir, TRUE_CMD))
856
        result = process.run(cmd_line, ignore_status=True)
857 858
        expected_output = ('No test references provided nor any other '
                           'arguments resolved into tests')
859 860
        self.assertIn(expected_output, result.stderr)
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
C
Cleber Rosa 已提交
861 862 863 864 865 866 867 868 869 870
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

    def tearDown(self):
        self.pass_script.remove()
        self.fail_script.remove()
        shutil.rmtree(self.tmpdir)


871
class AbsPluginsTest(object):
872

873
    def setUp(self):
874
        self.base_outputdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
875

876 877 878 879 880 881
    def tearDown(self):
        shutil.rmtree(self.base_outputdir)


class PluginsTest(AbsPluginsTest, unittest.TestCase):

882 883
    def test_sysinfo_plugin(self):
        os.chdir(basedir)
884
        cmd_line = '%s sysinfo %s' % (AVOCADO, self.base_outputdir)
885
        result = process.run(cmd_line, ignore_status=True)
886
        expected_rc = exit_codes.AVOCADO_ALL_OK
887 888 889 890 891 892
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        sysinfo_files = os.listdir(self.base_outputdir)
        self.assertGreater(len(sysinfo_files), 0, "Empty sysinfo files dir")

893 894
    def test_list_plugin(self):
        os.chdir(basedir)
895
        cmd_line = '%s list' % AVOCADO
896 897
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
898
        expected_rc = exit_codes.AVOCADO_ALL_OK
899 900 901 902 903
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn('No tests were found on current tests dir', output)

904 905
    def test_list_error_output(self):
        os.chdir(basedir)
906
        cmd_line = '%s list sbrubles' % AVOCADO
907 908
        result = process.run(cmd_line, ignore_status=True)
        output = result.stderr
909
        expected_rc = exit_codes.AVOCADO_FAIL
910 911 912
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
913
        self.assertIn("Unable to resolve reference", output)
914

915 916 917 918 919 920 921 922 923 924 925 926 927
    def test_list_no_file_loader(self):
        os.chdir(basedir)
        cmd_line = ("%s list --loaders external --verbose -- "
                    "this-wont-be-matched" % AVOCADO)
        result = process.run(cmd_line, ignore_status=True)
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK,
                         "Avocado did not return rc %d:\n%s"
                         % (exit_codes.AVOCADO_ALL_OK, result))
        exp = ("Type    Test\nMISSING this-wont-be-matched\n\nEXTERNAL: 0\n"
               "MISSING: 1\n")
        self.assertEqual(exp, result.stdout, "Stdout mismatch:\n%s\n\n%s"
                         % (exp, result))

928 929
    def test_plugin_list(self):
        os.chdir(basedir)
930
        cmd_line = '%s plugins' % AVOCADO
931 932
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
933
        expected_rc = exit_codes.AVOCADO_ALL_OK
934 935 936
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
937 938
        if sys.version_info[:2] >= (2, 7, 0):
            self.assertNotIn('Disabled', output)
939

940
    def test_config_plugin(self):
941
        os.chdir(basedir)
942
        cmd_line = '%s config --paginator off' % AVOCADO
943 944
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
945
        expected_rc = exit_codes.AVOCADO_ALL_OK
946 947 948 949 950 951 952
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn('Disabled', output)

    def test_config_plugin_datadir(self):
        os.chdir(basedir)
953
        cmd_line = '%s config --datadir --paginator off' % AVOCADO
954 955
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
956
        expected_rc = exit_codes.AVOCADO_ALL_OK
957 958 959 960 961
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn('Disabled', output)

962 963
    def test_disable_plugin(self):
        os.chdir(basedir)
964
        cmd_line = '%s plugins' % AVOCADO
965 966 967 968 969 970 971 972 973 974 975
        result = process.run(cmd_line, ignore_status=True)
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn("Collect system information", result.stdout)

        config_content = "[plugins]\ndisable=['cli.cmd.sysinfo',]"
        config = script.TemporaryScript("disable_sysinfo_cmd.conf",
                                        config_content)
        with config:
976
            cmd_line = '%s --config %s plugins' % (AVOCADO, config)
977 978 979 980 981 982 983
            result = process.run(cmd_line, ignore_status=True)
            expected_rc = exit_codes.AVOCADO_ALL_OK
            self.assertEqual(result.exit_status, expected_rc,
                             "Avocado did not return rc %d:\n%s" %
                             (expected_rc, result))
            self.assertNotIn("Collect system information", result.stdout)

984 985 986 987 988 989 990 991 992 993 994 995
    def test_plugin_order(self):
        """
        Tests plugin order by configuration file

        First it checks if html, json, xunit and zip_archive plugins are enabled.
        Then it runs a test with zip_archive running first, which means the html,
        json and xunit output files do not make into the archive.

        Then it runs with zip_archive set to run last, which means the html,
        json and xunit output files *do* make into the archive.
        """
        def run_config(config_path):
996
            cmd = ('%s --config %s run passtest.py --archive '
997
                   '--job-results-dir %s --sysinfo=off'
998
                   % (AVOCADO, config_path, self.base_outputdir))
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
            result = process.run(cmd, ignore_status=True)
            expected_rc = exit_codes.AVOCADO_ALL_OK
            self.assertEqual(result.exit_status, expected_rc,
                             "Avocado did not return rc %d:\n%s" %
                             (expected_rc, result))

        result_plugins = ["json", "xunit", "zip_archive"]
        result_outputs = ["results.json", "results.xml"]
        try:
            pkg_resources.require('avocado_result_html')
            result_plugins.append("html")
            result_outputs.append("html/results.html")
        except pkg_resources.DistributionNotFound:
            pass

        os.chdir(basedir)
1015
        cmd_line = '%s plugins' % AVOCADO
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
        result = process.run(cmd_line, ignore_status=True)
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        for result_plugin in result_plugins:
            self.assertIn(result_plugin, result.stdout)

        config_content_zip_first = "[plugins.result]\norder=['zip_archive']"
        config_zip_first = script.TemporaryScript("zip_first.conf",
                                                  config_content_zip_first)
        with config_zip_first:
            run_config(config_zip_first)
            archives = glob.glob(os.path.join(self.base_outputdir, '*.zip'))
            self.assertEqual(len(archives), 1, "ZIP Archive not generated")
            zip_file = zipfile.ZipFile(archives[0], 'r')
            zip_file_list = zip_file.namelist()
            for result_output in result_outputs:
                self.assertNotIn(result_output, zip_file_list)
            os.unlink(archives[0])

        config_content_zip_last = ("[plugins.result]\norder=['html', 'json',"
1038 1039
                                   "'xunit', 'non_existing_plugin_is_ignored'"
                                   ",'zip_archive']")
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        config_zip_last = script.TemporaryScript("zip_last.conf",
                                                 config_content_zip_last)
        with config_zip_last:
            run_config(config_zip_last)
            archives = glob.glob(os.path.join(self.base_outputdir, '*.zip'))
            self.assertEqual(len(archives), 1, "ZIP Archive not generated")
            zip_file = zipfile.ZipFile(archives[0], 'r')
            zip_file_list = zip_file.namelist()
            for result_output in result_outputs:
                self.assertIn(result_output, zip_file_list)

1051 1052
    def test_Namespace_object_has_no_attribute(self):
        os.chdir(basedir)
1053
        cmd_line = '%s plugins' % AVOCADO
1054 1055
        result = process.run(cmd_line, ignore_status=True)
        output = result.stderr
1056
        expected_rc = exit_codes.AVOCADO_ALL_OK
1057 1058 1059 1060 1061
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn("'Namespace' object has no attribute", output)

1062

1063 1064 1065 1066
class ParseXMLError(Exception):
    pass


1067
class PluginsXunitTest(AbsPluginsTest, unittest.TestCase):
1068

1069
    def setUp(self):
1070
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
1071 1072
        self.junit = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                     os.path.pardir, ".data", 'junit-4.xsd'))
1073 1074
        super(PluginsXunitTest, self).setUp()

1075
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
1076
                      e_nnotfound, e_nfailures, e_nskip):
1077
        os.chdir(basedir)
1078 1079
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' --xunit - %s' % (AVOCADO, self.tmpdir, testname))
1080 1081 1082 1083 1084 1085 1086
        result = process.run(cmd_line, ignore_status=True)
        xml_output = result.stdout
        self.assertEqual(result.exit_status, e_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (e_rc, result))
        try:
            xunit_doc = xml.dom.minidom.parseString(xml_output)
1087
        except Exception as detail:
1088 1089 1090
            raise ParseXMLError("Failed to parse content: %s\n%s" %
                                (detail, xml_output))

1091 1092 1093 1094 1095 1096 1097 1098
        with open(self.junit, 'r') as f:
            xmlschema = etree.XMLSchema(etree.parse(f))

        self.assertTrue(xmlschema.validate(etree.parse(StringIO(xml_output))),
                        "Failed to validate against %s, message:\n%s" %
                        (self.junit,
                         xmlschema.error_log.filter_from_errors()))

1099 1100 1101 1102
        testsuite_list = xunit_doc.getElementsByTagName('testsuite')
        self.assertEqual(len(testsuite_list), 1, 'More than one testsuite tag')

        testsuite_tag = testsuite_list[0]
1103 1104
        self.assertEqual(len(testsuite_tag.attributes), 7,
                         'The testsuite tag does not have 7 attributes. '
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
                         'XML:\n%s' % xml_output)

        n_tests = int(testsuite_tag.attributes['tests'].value)
        self.assertEqual(n_tests, e_ntests,
                         "Unexpected number of executed tests, "
                         "XML:\n%s" % xml_output)

        n_errors = int(testsuite_tag.attributes['errors'].value)
        self.assertEqual(n_errors, e_nerrors,
                         "Unexpected number of test errors, "
                         "XML:\n%s" % xml_output)

        n_failures = int(testsuite_tag.attributes['failures'].value)
        self.assertEqual(n_failures, e_nfailures,
                         "Unexpected number of test failures, "
                         "XML:\n%s" % xml_output)

1122
        n_skip = int(testsuite_tag.attributes['skipped'].value)
1123 1124 1125 1126
        self.assertEqual(n_skip, e_nskip,
                         "Unexpected number of test skips, "
                         "XML:\n%s" % xml_output)

1127
    def test_xunit_plugin_passtest(self):
1128
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1129
                           1, 0, 0, 0, 0)
1130 1131

    def test_xunit_plugin_failtest(self):
1132
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1133
                           1, 0, 0, 1, 0)
1134

1135
    def test_xunit_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1136
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1137
                           1, 0, 0, 0, 1)
1138

1139
    def test_xunit_plugin_errortest(self):
1140
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1141
                           1, 1, 0, 0, 0)
1142

1143 1144 1145 1146
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsXunitTest, self).tearDown()

1147 1148 1149 1150 1151

class ParseJSONError(Exception):
    pass


1152
class PluginsJSONTest(AbsPluginsTest, unittest.TestCase):
1153

1154
    def setUp(self):
1155
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
1156 1157
        super(PluginsJSONTest, self).setUp()

1158
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
1159
                      e_nfailures, e_nskip, e_ncancel=0, external_runner=None):
1160
        os.chdir(basedir)
1161 1162
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off --json - '
                    '--archive %s' % (AVOCADO, self.tmpdir, testname))
1163 1164
        if external_runner is not None:
            cmd_line += " --external-runner '%s'" % external_runner
1165 1166 1167 1168 1169 1170 1171
        result = process.run(cmd_line, ignore_status=True)
        json_output = result.stdout
        self.assertEqual(result.exit_status, e_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (e_rc, result))
        try:
            json_data = json.loads(json_output)
1172
        except Exception as detail:
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
            raise ParseJSONError("Failed to parse content: %s\n%s" %
                                 (detail, json_output))
        self.assertTrue(json_data, "Empty JSON result:\n%s" % json_output)
        self.assertIsInstance(json_data['tests'], list,
                              "JSON result lacks 'tests' list")
        n_tests = len(json_data['tests'])
        self.assertEqual(n_tests, e_ntests,
                         "Different number of expected tests")
        n_errors = json_data['errors']
        self.assertEqual(n_errors, e_nerrors,
                         "Different number of expected tests")
        n_failures = json_data['failures']
        self.assertEqual(n_failures, e_nfailures,
                         "Different number of expected tests")
        n_skip = json_data['skip']
        self.assertEqual(n_skip, e_nskip,
                         "Different number of skipped tests")
1190 1191
        n_cancel = json_data['cancel']
        self.assertEqual(n_cancel, e_ncancel)
1192
        return json_data
1193

1194
    def test_json_plugin_passtest(self):
1195
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1196
                           1, 0, 0, 0)
1197 1198

    def test_json_plugin_failtest(self):
1199
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1200
                           1, 0, 1, 0)
1201

1202
    def test_json_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1203
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1204
                           1, 0, 0, 0, 1)
1205

1206
    def test_json_plugin_errortest(self):
1207
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1208
                           1, 1, 0, 0)
1209

1210
    @unittest.skipIf(not GNU_ECHO_BINARY, 'echo binary not available')
1211
    def test_ugly_echo_cmd(self):
1212
        data = self.run_and_check('"-ne foo\\\\\\n\\\'\\\\\\"\\\\\\'
1213
                                  'nbar/baz"', exit_codes.AVOCADO_ALL_OK, 1, 0,
1214
                                  0, 0, external_runner=GNU_ECHO_BINARY)
1215 1216
        # The executed test should be this
        self.assertEqual(data['tests'][0]['url'],
1217
                         '1--ne foo\\\\n\\\'\\"\\\\nbar/baz')
1218 1219
        # logdir name should escape special chars (/)
        self.assertEqual(os.path.basename(data['tests'][0]['logdir']),
1220
                         '1--ne foo\\\\n\\\'\\"\\\\nbar_baz')
1221

1222 1223 1224 1225
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsJSONTest, self).tearDown()

L
Lukáš Doktor 已提交
1226

1227 1228
if __name__ == '__main__':
    unittest.main()