test_basic.py 56.4 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 36 37 38 39 40
LOCAL_IMPORT_TEST_CONTENTS = '''
from avocado import Test
from mylib import hello

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

41 42 43 44 45 46
UNSUPPORTED_STATUS_TEST_CONTENTS = '''
from avocado import Test

class FakeStatusTest(Test):
    def run_avocado(self):
        super(FakeStatusTest, self).run_avocado()
47 48
        # Please do NOT ever use this, it's for unittesting only.
        self._Test__status = 'not supported'
49 50 51 52 53

    def test(self):
        pass
'''

54 55 56 57 58 59 60 61 62 63 64
INVALID_PYTHON_TEST = '''
from avocado import Test

class MyTest(Test):

    non_existing_variable_causing_crash

    def test_my_name(self):
        pass
'''

65

66 67 68 69 70 71 72 73 74 75 76 77
VALID_PYTHON_TEST_WITH_TAGS = '''
from avocado import Test

class MyTest(Test):
    def test(self):
         """
         :avocado: tags=BIG_TAG_NAME
         """
         pass
'''


78 79 80 81 82 83 84
REPORTS_STATUS_AND_HANG = '''
from avocado import Test
import time

class MyTest(Test):
    def test(self):
         self.runner_queue.put({"running": False})
85
         time.sleep(70)
86 87
'''

88

89 90 91 92 93 94 95 96 97 98 99
DIE_WITHOUT_REPORTING_STATUS = '''
from avocado import Test
import os
import signal

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


100 101 102 103 104 105 106 107 108 109 110 111 112
RAISE_CUSTOM_PATH_EXCEPTION_CONTENT = '''import os
import sys

from avocado import Test

class SharedLibTest(Test):
    def test(self):
        sys.path.append(os.path.join(os.path.dirname(__file__), "shared_lib"))
        from mylib import CancelExc
        raise CancelExc("This should not crash on unpickling in runner")
'''


A
Amador Pahim 已提交
113
def probe_binary(binary):
114
    try:
A
Amador Pahim 已提交
115
        return utils_path.find_command(binary)
116
    except utils_path.CmdNotFoundError:
A
Amador Pahim 已提交
117 118
        return None

L
Lukáš Doktor 已提交
119

120
TRUE_CMD = probe_binary('true')
A
Amador Pahim 已提交
121
CC_BINARY = probe_binary('cc')
122

L
Lukáš Doktor 已提交
123
# On macOS, the default GNU core-utils installation (brew)
124 125 126 127 128
# 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:
129 130 131 132
    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 已提交
133 134
READ_BINARY = probe_binary('read')
SLEEP_BINARY = probe_binary('sleep')
135 136


137 138
class RunnerOperationTest(unittest.TestCase):

139
    def setUp(self):
140
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
141
        os.chdir(basedir)
142

143
    def test_show_version(self):
144
        result = process.run('%s -v' % AVOCADO, ignore_status=True)
145
        self.assertEqual(result.exit_status, 0)
C
Cleber Rosa 已提交
146 147 148
        self.assertTrue(re.match(r"^Avocado \d+\.\d+$", result.stderr),
                        "Version string does not match 'Avocado \\d\\.\\d:'\n"
                        "%r" % (result.stderr))
149

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    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)

172
        cmd = '%s --config %s config --datadir' % (AVOCADO, config_file)
173 174 175 176 177 178 179 180 181 182
        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)

183
    def test_runner_all_ok(self):
184 185
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py passtest.py' % (AVOCADO, self.tmpdir))
186
        process.run(cmd_line)
187 188 189 190 191
        # Also check whether jobdata contains correct mux_path
        variants = open(os.path.join(self.tmpdir, "latest", "jobdata",
                        "variants.json")).read()
        self.assertIn('["/run/*"]', variants, "mux_path stored in jobdata "
                      "does not contains [\"/run/*\"]\n%s" % variants)
192

193
    def test_runner_failfast(self):
194 195 196
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py failtest.py passtest.py --failfast on'
                    % (AVOCADO, self.tmpdir))
197 198 199 200 201 202 203
        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 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    def test_runner_ignore_missing_references_one_missing(self):
        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):
        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 已提交
227
    @unittest.skipIf(not CC_BINARY,
228
                     "C compiler is required by the underlying datadir.py test")
229
    def test_datadir_alias(self):
230 231
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'datadir.py' % (AVOCADO, self.tmpdir))
232 233 234 235
        process.run(cmd_line)

    def test_shell_alias(self):
        """ Tests that .sh files are also executable via alias """
236 237
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'env_variables.sh' % (AVOCADO, self.tmpdir))
238 239
        process.run(cmd_line)

A
Amador Pahim 已提交
240
    @unittest.skipIf(not CC_BINARY,
241
                     "C compiler is required by the underlying datadir.py test")
242
    def test_datadir_noalias(self):
243 244
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s examples/tests/datadir.py '
                    'examples/tests/datadir.py' % (AVOCADO, self.tmpdir))
245 246
        process.run(cmd_line)

247
    def test_runner_noalias(self):
248 249
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s examples/tests/passtest.py "
                    "examples/tests/passtest.py" % (AVOCADO, self.tmpdir))
250 251
        process.run(cmd_line)

252 253 254
    def test_runner_test_with_local_imports(self):
        mylib = script.TemporaryScript(
            'mylib.py',
255
            "def hello():\n    return 'Hello world'",
256 257 258 259 260 261
            'avocado_simpletest_functional')
        mylib.save()
        mytest = script.Script(
            os.path.join(os.path.dirname(mylib.path), 'test_local_imports.py'),
            LOCAL_IMPORT_TEST_CONTENTS)
        mytest.save()
262 263
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s "
                    "%s" % (AVOCADO, self.tmpdir, mytest))
264 265
        process.run(cmd_line)

266 267 268 269
    def test_unsupported_status(self):
        with script.TemporaryScript("fake_status.py",
                                    UNSUPPORTED_STATUS_TEST_CONTENTS,
                                    "avocado_unsupported_status") as tst:
270 271 272
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s"
                              " --json -" % (AVOCADO, self.tmpdir, tst),
                              ignore_status=True)
273 274 275 276 277
            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))
278
            self.assertIn("Runner error occurred: Test reports unsupported",
279 280
                          results["tests"][0]["fail_reason"])

281 282 283
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 1,
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
284 285 286 287 288
    def test_hanged_test_with_status(self):
        """ Check that avocado handles hanged tests properly """
        with script.TemporaryScript("report_status_and_hang.py",
                                    REPORTS_STATUS_AND_HANG,
                                    "hanged_test_with_status") as tst:
289
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s "
290
                              "--json - --job-timeout 1" % (AVOCADO, self.tmpdir, tst),
291
                              ignore_status=True)
292 293 294 295 296 297 298
            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"])
299 300 301 302 303
            # 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, "
304 305 306 307 308 309 310
                            "which is likely because the hanged test was not "
                            "interrupted. Results:\n%s" % res)

    def test_no_status_reported(self):
        with script.TemporaryScript("die_without_reporting_status.py",
                                    DIE_WITHOUT_REPORTING_STATUS,
                                    "no_status_reported") as tst:
311 312 313
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s "
                              "--json -" % (AVOCADO, self.tmpdir, tst),
                              ignore_status=True)
314 315 316 317 318 319 320 321
            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"])

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

    def test_runner_nonexistent_test(self):
331 332
        cmd_line = ('%s run --sysinfo=off --job-results-dir '
                    '%s bogustest' % (AVOCADO, self.tmpdir))
333
        result = process.run(cmd_line, ignore_status=True)
334 335
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
336 337 338 339 340
        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))

341
    def test_runner_doublefail(self):
342 343
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    '--xunit - doublefail.py' % (AVOCADO, self.tmpdir))
344 345
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
346 347
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
348 349 350 351
        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))
352
        self.assertIn("TestError: Failing during tearDown. Yay!", output,
353
                      "Cleanup exception not printed to log output")
354
        self.assertIn("TestFail: This test is supposed to fail",
355
                      output,
356
                      "Test did not fail with action exception:\n%s" % output)
357

358
    def test_uncaught_exception(self):
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 370
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s "
                    "--json - fail_on_exception.py" % (AVOCADO, self.tmpdir))
371
        result = process.run(cmd_line, ignore_status=True)
372
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
373 374 375 376 377
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc,
                                                                result))
        self.assertIn('"status": "FAIL"', result.stdout)

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    def test_exception_not_in_path(self):
        os.mkdir(os.path.join(self.tmpdir, "shared_lib"))
        mylib = script.Script(os.path.join(self.tmpdir, "shared_lib",
                                           "mylib.py"),
                              "from avocado import TestCancel\n\n"
                              "class CancelExc(TestCancel):\n"
                              "    pass")
        mylib.save()
        mytest = script.Script(os.path.join(self.tmpdir, "mytest.py"),
                               RAISE_CUSTOM_PATH_EXCEPTION_CONTENT)
        mytest.save()
        result = process.run("%s --show test run --sysinfo=off "
                             "--job-results-dir %s %s"
                             % (AVOCADO, self.tmpdir, mytest))
        self.assertIn("mytest.py:SharedLibTest.test -> CancelExc: This "
                      "should not crash on unpickling in runner",
                      result.stdout)
        self.assertNotIn("Failed to read queue", result.stdout)

397
    def test_runner_timeout(self):
398 399
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    '--xunit - timeouttest.py' % (AVOCADO, self.tmpdir))
400 401
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
402
        expected_rc = exit_codes.AVOCADO_JOB_INTERRUPTED
403
        unexpected_rc = exit_codes.AVOCADO_FAIL
404 405 406 407
        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))
408
        self.assertIn("Runner error occurred: Timeout reached", output,
409
                      "Timeout reached message not found in the output:\n%s" % output)
410 411
        # Ensure no test aborted error messages show up
        self.assertNotIn("TestAbortedError: Test aborted unexpectedly", output)
412

413
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 2,
414 415
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
416
    def test_runner_abort(self):
417 418
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    '--xunit - abort.py' % (AVOCADO, self.tmpdir))
419
        result = process.run(cmd_line, ignore_status=True)
420
        output = result.stdout
421
        excerpt = 'Test died without reporting the status.'
422 423
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
424 425 426 427
        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))
428
        self.assertIn(excerpt, output)
429

430
    def test_silent_output(self):
431 432
        cmd_line = ('%s --silent run --sysinfo=off --job-results-dir %s '
                    'passtest.py' % (AVOCADO, self.tmpdir))
433
        result = process.run(cmd_line, ignore_status=True)
434
        expected_rc = exit_codes.AVOCADO_ALL_OK
435 436
        expected_output = ''
        self.assertEqual(result.exit_status, expected_rc)
437
        self.assertEqual(result.stdout, expected_output)
438

439
    def test_empty_args_list(self):
440
        cmd_line = AVOCADO
441
        result = process.run(cmd_line, ignore_status=True)
442
        expected_rc = exit_codes.AVOCADO_FAIL
443
        expected_output = 'error: too few arguments'
444
        self.assertEqual(result.exit_status, expected_rc)
445
        self.assertIn(expected_output, result.stderr)
446

447
    def test_empty_test_list(self):
448 449
        cmd_line = '%s run --sysinfo=off --job-results-dir %s' % (AVOCADO,
                                                                  self.tmpdir)
450
        result = process.run(cmd_line, ignore_status=True)
451
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
452 453
        expected_output = ('No test references provided nor any other '
                           'arguments resolved into tests')
454
        self.assertEqual(result.exit_status, expected_rc)
455
        self.assertIn(expected_output, result.stderr)
456

457
    def test_not_found(self):
458 459
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s sbrubles'
                    % (AVOCADO, self.tmpdir))
460
        result = process.run(cmd_line, ignore_status=True)
461
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
462
        self.assertEqual(result.exit_status, expected_rc)
463 464
        self.assertIn('Unable to resolve reference', result.stderr)
        self.assertNotIn('Unable to resolve reference', result.stdout)
465

466
    def test_invalid_unique_id(self):
467 468
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s --force-job-id '
                    'foobar passtest.py' % (AVOCADO, self.tmpdir))
469
        result = process.run(cmd_line, ignore_status=True)
470
        self.assertNotEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
471
        self.assertIn('needs to be a 40 digit hex', result.stderr)
472
        self.assertNotIn('needs to be a 40 digit hex', result.stdout)
473 474

    def test_valid_unique_id(self):
475
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
476
                    '--force-job-id 975de258ac05ce5e490648dec4753657b7ccc7d1 '
477
                    'passtest.py' % (AVOCADO, self.tmpdir))
478
        result = process.run(cmd_line, ignore_status=True)
479
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
480
        self.assertNotIn('needs to be a 40 digit hex', result.stderr)
481
        self.assertIn('PASS', result.stdout)
482

483
    def test_automatic_unique_id(self):
484 485
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    'passtest.py --json -' % (AVOCADO, self.tmpdir))
486
        result = process.run(cmd_line, ignore_status=True)
487
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
488 489 490 491
        r = json.loads(result.stdout)
        int(r['job_id'], 16)  # it's an hex number
        self.assertEqual(len(r['job_id']), 40)

492 493 494 495
    def test_early_latest_result(self):
        """
        Tests that the `latest` link to the latest job results is created early
        """
496 497
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'examples/tests/passtest.py' % (AVOCADO, self.tmpdir))
498 499 500 501 502 503
        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):
504
                avocado_process.wait()
505 506 507 508
                break
        self.assertTrue(os.path.exists(link))
        self.assertTrue(os.path.islink(link))

509
    def test_dry_run(self):
510
        cmd = ("%s run --sysinfo=off passtest.py failtest.py "
511
               "gendata.py --json - --mux-inject foo:1 bar:2 baz:3 foo:foo:a"
512
               " foo:bar:b foo:baz:c bar:bar:bar --dry-run" % AVOCADO)
513 514 515 516 517
        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)))
518
        self.assertIn(tempfile.gettempdir(), debuglog)   # Use tmp dir, not default location
519 520
        self.assertEqual(result['job_id'], u'0' * 40)
        # Check if all tests were skipped
521
        self.assertEqual(result['cancel'], 4)
522
        for i in xrange(4):
523 524
            test = result['tests'][i]
            self.assertEqual(test['fail_reason'],
525
                             u'Test cancelled due to --dry-run')
526 527 528 529 530
        # 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"):
531
            self.assertEqual(log.count(line), 4)
532

533 534 535
    def test_invalid_python(self):
        test = script.make_script(os.path.join(self.tmpdir, 'test.py'),
                                  INVALID_PYTHON_TEST)
536 537
        cmd_line = ('%s --show test run --sysinfo=off '
                    '--job-results-dir %s %s') % (AVOCADO, self.tmpdir, test)
538 539 540 541 542
        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))
543 544
        self.assertIn('1-%s:MyTest.test_my_name -> TestError' % test,
                      result.stdout)
545

A
Amador Pahim 已提交
546
    @unittest.skipIf(not READ_BINARY, "read binary not available.")
547 548 549
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 1,
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
L
Lukáš Doktor 已提交
550
    def test_read(self):
551
        cmd = "%s run --sysinfo=off --job-results-dir %%s %%s" % AVOCADO
552
        cmd %= (self.tmpdir, READ_BINARY)
553
        result = process.run(cmd, timeout=10, ignore_status=True)
L
Lukáš Doktor 已提交
554 555 556 557 558
        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)

559 560 561
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

562

563 564 565
class RunnerHumanOutputTest(unittest.TestCase):

    def setUp(self):
566
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
567
        os.chdir(basedir)
568 569

    def test_output_pass(self):
570 571
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py' % (AVOCADO, self.tmpdir))
572
        result = process.run(cmd_line, ignore_status=True)
573
        expected_rc = exit_codes.AVOCADO_ALL_OK
574 575 576 577 578 579
        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):
580 581
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'failtest.py' % (AVOCADO, self.tmpdir))
582
        result = process.run(cmd_line, ignore_status=True)
583
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
584 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('failtest.py:FailTest.test:  FAIL', result.stdout)

    def test_output_error(self):
590 591
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'errortest.py' % (AVOCADO, self.tmpdir))
592
        result = process.run(cmd_line, ignore_status=True)
593
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
594 595 596 597 598
        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 已提交
599
    def test_output_cancel(self):
600 601
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'cancelonsetup.py' % (AVOCADO, self.tmpdir))
602
        result = process.run(cmd_line, ignore_status=True)
603
        expected_rc = exit_codes.AVOCADO_ALL_OK
604 605 606
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
A
Amador Pahim 已提交
607 608
        self.assertIn('PASS 0 | ERROR 0 | FAIL 0 | SKIP 0 | WARN 0 | INTERRUPT 0 | CANCEL 1',
                      result.stdout)
609

610 611
    @unittest.skipIf(not GNU_ECHO_BINARY,
                     'GNU style echo binary not available')
612
    def test_ugly_echo_cmd(self):
613
        cmd_line = ('%s run --external-runner "%s -ne" '
614
                    '"foo\\\\\\n\\\'\\\\\\"\\\\\\nbar/baz" --job-results-dir %s'
A
Amador Pahim 已提交
615
                    ' --sysinfo=off  --show-job-log' %
616
                    (AVOCADO, GNU_ECHO_BINARY, self.tmpdir))
617 618 619 620 621
        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))
622 623 624
        self.assertIn('[stdout] foo', result.stdout, result)
        self.assertIn('[stdout] \'"', result.stdout, result)
        self.assertIn('[stdout] bar/baz', result.stdout, result)
625 626
        self.assertIn('PASS 1-foo\\\\n\\\'\\"\\\\nbar/baz',
                      result.stdout, result)
627 628 629 630 631 632 633
        # 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]),
634
                         '1-foo\\\\n\\\'\\"\\\\nbar_baz')
635

636
    def test_replay_skip_skipped(self):
637 638
        cmd = ("%s run --job-results-dir %s --json - "
               "cancelonsetup.py" % (AVOCADO, self.tmpdir))
639
        result = process.run(cmd)
640
        result = json.loads(result.stdout)
641
        jobid = str(result["job_id"])
642 643
        cmd = ("%s run --job-results-dir %s --replay %s "
               "--replay-test-status PASS" % (AVOCADO, self.tmpdir, jobid))
644
        process.run(cmd)
645

646 647 648
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

649

650
class RunnerSimpleTest(unittest.TestCase):
651 652

    def setUp(self):
653
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
654
        self.pass_script = script.TemporaryScript(
655
            'ʊʋʉʈɑ ʅʛʌ',
656
            "#!/bin/sh\ntrue",
657
            'avocado_simpletest_functional')
658
        self.pass_script.save()
L
Lukáš Doktor 已提交
659
        self.fail_script = script.TemporaryScript('avocado_fail.sh',
660
                                                  "#!/bin/sh\nfalse",
L
Lukáš Doktor 已提交
661 662
                                                  'avocado_simpletest_'
                                                  'functional')
663
        self.fail_script.save()
664
        os.chdir(basedir)
665

666
    def test_simpletest_pass(self):
667 668
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' "%s"' % (AVOCADO, self.tmpdir, self.pass_script.path))
669
        result = process.run(cmd_line, ignore_status=True)
670
        expected_rc = exit_codes.AVOCADO_ALL_OK
671 672 673 674
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

675
    def test_simpletest_fail(self):
676 677
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' %s' % (AVOCADO, self.tmpdir, self.fail_script.path))
678
        result = process.run(cmd_line, ignore_status=True)
679
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
680 681 682 683
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

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

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

706 707 708
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 1,
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
709 710 711 712 713
    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.
        """
714 715
        sleep_fail_sleep = ('sleeptest.py ' + 'failtest.py ' * 100 +
                            'sleeptest.py')
716 717
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off %s'
                    % (AVOCADO, self.tmpdir, sleep_fail_sleep))
718 719 720
        initial_time = time.time()
        result = process.run(cmd_line, ignore_status=True)
        actual_time = time.time() - initial_time
721
        self.assertLess(actual_time, 33.0)
722
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
723 724 725
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

726 727 728 729
    def test_simplewarning(self):
        """
        simplewarning.sh uses the avocado-bash-utils
        """
730 731 732 733 734
        # simplewarning.sh calls "avocado" without specifying a path
        os.environ['PATH'] += ":" + os.path.join(basedir, 'scripts')
        # simplewarning.sh calls "avocado exec-path" which hasn't
        # access to an installed location for the libexec scripts
        os.environ['PATH'] += ":" + os.path.join(basedir, 'libexec')
735 736 737
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    'examples/tests/simplewarning.sh --show-job-log'
                    % (AVOCADO, self.tmpdir))
738
        result = process.run(cmd_line, ignore_status=True)
739 740 741 742
        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))
743 744
        self.assertIn('DEBUG| Debug message', result.stdout, result)
        self.assertIn('INFO | Info message', result.stdout, result)
745
        self.assertIn('WARN | Warning message (should cause this test to '
746
                      'finish with warning)', result.stdout, result)
747
        self.assertIn('ERROR| Error message (ordinary message not changing '
748
                      'the results)', result.stdout, result)
749

750 751 752 753
    def test_non_absolute_path(self):
        avocado_path = os.path.join(basedir, 'scripts', 'avocado')
        test_base_dir = os.path.dirname(self.pass_script.path)
        os.chdir(test_base_dir)
754
        test_file_name = os.path.basename(self.pass_script.path)
755
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
756
                    ' "%s"' % (avocado_path, self.tmpdir, test_file_name))
757 758 759 760 761 762
        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 已提交
763
    @unittest.skipIf(not SLEEP_BINARY, 'sleep binary not available')
764 765 766
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 1,
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
767
    def test_kill_stopped_sleep(self):
768 769 770 771
        proc = aexpect.Expect("%s run 60 --job-results-dir %s "
                              "--external-runner %s --sysinfo=off "
                              "--job-timeout 3"
                              % (AVOCADO, self.tmpdir, SLEEP_BINARY))
772 773
        proc.read_until_output_matches(["\(1/1\)"], timeout=3,
                                       internal_timeout=0.01)
774 775 776 777
        # 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
778
        os.kill(pid, signal.SIGTSTP)   # This freezes the process
779
        deadline = time.time() + 9
780 781 782
        while time.time() < deadline:
            if not proc.is_alive():
                break
783
            time.sleep(0.1)
784 785
        else:
            proc.kill(signal.SIGKILL)
786
            self.fail("Avocado process still alive 5s after job-timeout:\n%s"
787 788 789 790 791 792 793
                      % 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")
794
        self.assertEqual(proc.get_status(), 8, "Avocado did not finish with "
795
                         "1.")
796 797

        sleep_dir = astring.string_to_safe_path("1-60")
798
        debug_log = os.path.join(self.tmpdir, "latest", "test-results",
799
                                 sleep_dir, "debug.log")
800
        debug_log = open(debug_log).read()
801 802 803 804 805 806 807
        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)
808

809
    def tearDown(self):
810 811
        self.pass_script.remove()
        self.fail_script.remove()
812
        shutil.rmtree(self.tmpdir)
813 814


815
class ExternalRunnerTest(unittest.TestCase):
C
Cleber Rosa 已提交
816 817

    def setUp(self):
818
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
C
Cleber Rosa 已提交
819 820
        self.pass_script = script.TemporaryScript(
            'pass',
821
            "exit 0",
822
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
823 824 825
        self.pass_script.save()
        self.fail_script = script.TemporaryScript(
            'fail',
826
            "exit 1",
827
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
828
        self.fail_script.save()
829
        os.chdir(basedir)
C
Cleber Rosa 已提交
830

831
    def test_externalrunner_pass(self):
832 833 834
        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 已提交
835
        result = process.run(cmd_line, ignore_status=True)
836
        expected_rc = exit_codes.AVOCADO_ALL_OK
C
Cleber Rosa 已提交
837 838 839 840
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

841
    def test_externalrunner_fail(self):
842 843 844
        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 已提交
845
        result = process.run(cmd_line, ignore_status=True)
846
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
C
Cleber Rosa 已提交
847 848 849 850
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

851
    def test_externalrunner_chdir_no_testdir(self):
852 853 854
        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 已提交
855
        result = process.run(cmd_line, ignore_status=True)
856 857
        expected_output = ('Option "--external-runner-chdir=test" requires '
                           '"--external-runner-testdir" to be set')
C
Cleber Rosa 已提交
858
        self.assertIn(expected_output, result.stderr)
859
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
860 861 862 863 864
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

    def test_externalrunner_no_url(self):
865 866
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    '--external-runner=%s' % (AVOCADO, self.tmpdir, TRUE_CMD))
867
        result = process.run(cmd_line, ignore_status=True)
868 869
        expected_output = ('No test references provided nor any other '
                           'arguments resolved into tests')
870 871
        self.assertIn(expected_output, result.stderr)
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
C
Cleber Rosa 已提交
872 873 874 875 876 877 878 879 880 881
        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)


882
class AbsPluginsTest(object):
883

884
    def setUp(self):
885
        self.base_outputdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
886
        os.chdir(basedir)
887

888 889 890 891 892 893
    def tearDown(self):
        shutil.rmtree(self.base_outputdir)


class PluginsTest(AbsPluginsTest, unittest.TestCase):

894
    def test_sysinfo_plugin(self):
895
        cmd_line = '%s sysinfo %s' % (AVOCADO, self.base_outputdir)
896
        result = process.run(cmd_line, ignore_status=True)
897
        expected_rc = exit_codes.AVOCADO_ALL_OK
898 899 900 901 902 903
        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")

904
    def test_list_plugin(self):
905
        cmd_line = '%s list' % AVOCADO
906 907
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
908
        expected_rc = exit_codes.AVOCADO_ALL_OK
909 910 911 912 913
        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)

914
    def test_list_error_output(self):
915
        cmd_line = '%s list sbrubles' % AVOCADO
916 917
        result = process.run(cmd_line, ignore_status=True)
        output = result.stderr
918
        expected_rc = exit_codes.AVOCADO_FAIL
919 920 921
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
922
        self.assertIn("Unable to resolve reference", output)
923

924 925 926 927 928 929 930
    def test_list_no_file_loader(self):
        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))
931 932
        exp = ("Type    Test                 Tag(s)\n"
               "MISSING this-wont-be-matched \n\n"
933 934
               "TEST TYPES SUMMARY\n"
               "==================\n"
935
               "EXTERNAL: 0\n"
936 937 938 939
               "MISSING: 1\n")
        self.assertEqual(exp, result.stdout, "Stdout mismatch:\n%s\n\n%s"
                         % (exp, result))

940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
    def test_list_verbose_tags(self):
        """
        Runs list verbosely and check for tag related output
        """
        test = script.make_script(os.path.join(self.base_outputdir, 'test.py'),
                                  VALID_PYTHON_TEST_WITH_TAGS)
        cmd_line = ("%s list --loaders file --verbose %s" % (AVOCADO,
                                                             test))
        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))
        stdout_lines = result.stdout.splitlines()
        self.assertIn("Tag(s)", stdout_lines[0])
        full_test_name = "%s:MyTest.test" % test
955 956
        self.assertEqual("INSTRUMENTED %s BIG_TAG_NAME" % full_test_name,
                         stdout_lines[1])
957 958 959
        self.assertIn("TEST TYPES SUMMARY", stdout_lines)
        self.assertIn("INSTRUMENTED: 1", stdout_lines)
        self.assertIn("TEST TAGS SUMMARY", stdout_lines)
960
        self.assertEqual("BIG_TAG_NAME: 1", stdout_lines[-1])
961

962
    def test_plugin_list(self):
963
        cmd_line = '%s plugins' % AVOCADO
964 965
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
966
        expected_rc = exit_codes.AVOCADO_ALL_OK
967 968 969
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
970 971
        if sys.version_info[:2] >= (2, 7, 0):
            self.assertNotIn('Disabled', output)
972

973
    def test_config_plugin(self):
974
        cmd_line = '%s config --paginator off' % AVOCADO
975 976
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
977
        expected_rc = exit_codes.AVOCADO_ALL_OK
978 979 980 981 982 983
        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):
984
        cmd_line = '%s config --datadir --paginator off' % AVOCADO
985 986
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
987
        expected_rc = exit_codes.AVOCADO_ALL_OK
988 989 990 991 992
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn('Disabled', output)

993
    def test_disable_plugin(self):
994
        cmd_line = '%s plugins' % AVOCADO
995 996 997 998 999 1000 1001 1002 1003 1004 1005
        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:
1006
            cmd_line = '%s --config %s plugins' % (AVOCADO, config)
1007 1008 1009 1010 1011 1012 1013
            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)

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    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):
1026
            cmd = ('%s --config %s run passtest.py --archive '
1027
                   '--job-results-dir %s --sysinfo=off'
1028
                   % (AVOCADO, config_path, self.base_outputdir))
1029 1030 1031 1032 1033 1034 1035 1036 1037
            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:
1038
            pkg_resources.require('avocado-framework-plugin-result-html')
1039
            result_plugins.append("html")
1040
            result_outputs.append("results.html")
1041 1042 1043
        except pkg_resources.DistributionNotFound:
            pass

1044
        cmd_line = '%s plugins' % AVOCADO
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
        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',"
1067 1068
                                   "'xunit', 'non_existing_plugin_is_ignored'"
                                   ",'zip_archive']")
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        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)

1080
    def test_Namespace_object_has_no_attribute(self):
1081
        cmd_line = '%s plugins' % AVOCADO
1082 1083
        result = process.run(cmd_line, ignore_status=True)
        output = result.stderr
1084
        expected_rc = exit_codes.AVOCADO_ALL_OK
1085 1086 1087 1088 1089
        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)

1090

1091 1092 1093 1094
class ParseXMLError(Exception):
    pass


1095
class PluginsXunitTest(AbsPluginsTest, unittest.TestCase):
1096

1097
    def setUp(self):
1098
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
L
Lucas Meneghel Rodrigues 已提交
1099 1100 1101
        junit_xsd = os.path.join(os.path.dirname(__file__),
                                 os.path.pardir, ".data", 'junit-4.xsd')
        self.junit = os.path.abspath(junit_xsd)
1102 1103
        super(PluginsXunitTest, self).setUp()

1104
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
1105
                      e_nnotfound, e_nfailures, e_nskip):
1106 1107
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' --xunit - %s' % (AVOCADO, self.tmpdir, testname))
1108 1109 1110 1111 1112 1113 1114
        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)
1115
        except Exception as detail:
1116 1117 1118
            raise ParseXMLError("Failed to parse content: %s\n%s" %
                                (detail, xml_output))

1119 1120 1121 1122 1123 1124 1125 1126
        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()))

1127 1128 1129 1130
        testsuite_list = xunit_doc.getElementsByTagName('testsuite')
        self.assertEqual(len(testsuite_list), 1, 'More than one testsuite tag')

        testsuite_tag = testsuite_list[0]
1131 1132
        self.assertEqual(len(testsuite_tag.attributes), 7,
                         'The testsuite tag does not have 7 attributes. '
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
                         '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)

1150
        n_skip = int(testsuite_tag.attributes['skipped'].value)
1151 1152 1153 1154
        self.assertEqual(n_skip, e_nskip,
                         "Unexpected number of test skips, "
                         "XML:\n%s" % xml_output)

1155
    def test_xunit_plugin_passtest(self):
1156
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1157
                           1, 0, 0, 0, 0)
1158 1159

    def test_xunit_plugin_failtest(self):
1160
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1161
                           1, 0, 0, 1, 0)
1162

1163
    def test_xunit_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1164
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1165
                           1, 0, 0, 0, 1)
1166

1167
    def test_xunit_plugin_errortest(self):
1168
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1169
                           1, 1, 0, 0, 0)
1170

1171 1172 1173 1174
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsXunitTest, self).tearDown()

1175 1176 1177 1178 1179

class ParseJSONError(Exception):
    pass


1180
class PluginsJSONTest(AbsPluginsTest, unittest.TestCase):
1181

1182
    def setUp(self):
1183
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
1184 1185
        super(PluginsJSONTest, self).setUp()

1186
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
1187
                      e_nfailures, e_nskip, e_ncancel=0, external_runner=None):
1188 1189
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off --json - '
                    '--archive %s' % (AVOCADO, self.tmpdir, testname))
1190 1191
        if external_runner is not None:
            cmd_line += " --external-runner '%s'" % external_runner
1192 1193 1194 1195 1196 1197 1198
        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)
1199
        except Exception as detail:
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
            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")
1217 1218
        n_cancel = json_data['cancel']
        self.assertEqual(n_cancel, e_ncancel)
1219
        return json_data
1220

1221
    def test_json_plugin_passtest(self):
1222
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1223
                           1, 0, 0, 0)
1224 1225

    def test_json_plugin_failtest(self):
1226
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1227
                           1, 0, 1, 0)
1228

1229
    def test_json_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1230
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1231
                           1, 0, 0, 0, 1)
1232

1233
    def test_json_plugin_errortest(self):
1234
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1235
                           1, 1, 0, 0)
1236

1237
    @unittest.skipIf(not GNU_ECHO_BINARY, 'echo binary not available')
1238
    def test_ugly_echo_cmd(self):
1239
        data = self.run_and_check('"-ne foo\\\\\\n\\\'\\\\\\"\\\\\\'
1240
                                  'nbar/baz"', exit_codes.AVOCADO_ALL_OK, 1, 0,
1241
                                  0, 0, external_runner=GNU_ECHO_BINARY)
1242 1243
        # The executed test should be this
        self.assertEqual(data['tests'][0]['url'],
1244
                         '1--ne foo\\\\n\\\'\\"\\\\nbar/baz')
1245 1246
        # logdir name should escape special chars (/)
        self.assertEqual(os.path.basename(data['tests'][0]['logdir']),
1247
                         '1--ne foo\\\\n\\\'\\"\\\\nbar_baz')
1248

1249 1250 1251 1252
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsJSONTest, self).tearDown()

L
Lukáš Doktor 已提交
1253

1254 1255
if __name__ == '__main__':
    unittest.main()