test_basic.py 61.4 KB
Newer Older
1 2
import aexpect
import glob
3
import json
4
import os
5
import re
6
import shutil
7
import signal
8
import sys
9
import tempfile
10
import time
11
import xml.dom.minidom
12
import zipfile
13
import unittest
14
import psutil
15
import pkg_resources
16

17 18
try:
    from io import BytesIO
19
except ImportError:
20
    from BytesIO import BytesIO
21

22 23 24 25 26 27
try:
    from lxml import etree
    SCHEMA_CAPABLE = True
except ImportError:
    SCHEMA_CAPABLE = False

28
from six import iteritems
29
from six.moves import xrange as range
30

31
from avocado.core import exit_codes
32
from avocado.utils import astring
33
from avocado.utils import genio
34 35
from avocado.utils import process
from avocado.utils import script
36
from avocado.utils import path as utils_path
37

38
basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')
39 40
basedir = os.path.abspath(basedir)

41 42
AVOCADO = os.environ.get("UNITTEST_AVOCADO_CMD",
                         "%s ./scripts/avocado" % sys.executable)
43

44 45 46 47 48 49 50 51 52
LOCAL_IMPORT_TEST_CONTENTS = '''
from avocado import Test
from mylib import hello

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

53 54 55 56 57 58
UNSUPPORTED_STATUS_TEST_CONTENTS = '''
from avocado import Test

class FakeStatusTest(Test):
    def run_avocado(self):
        super(FakeStatusTest, self).run_avocado()
59 60
        # Please do NOT ever use this, it's for unittesting only.
        self._Test__status = 'not supported'
61 62 63 64 65

    def test(self):
        pass
'''

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

class MyTest(Test):

    non_existing_variable_causing_crash

    def test_my_name(self):
        pass
'''

77

78 79 80 81 82 83 84 85 86 87 88 89
VALID_PYTHON_TEST_WITH_TAGS = '''
from avocado import Test

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


90 91 92 93 94 95 96
REPORTS_STATUS_AND_HANG = '''
from avocado import Test
import time

class MyTest(Test):
    def test(self):
         self.runner_queue.put({"running": False})
97
         time.sleep(70)
98 99
'''

100

101 102 103 104 105 106 107 108 109 110 111
DIE_WITHOUT_REPORTING_STATUS = '''
from avocado import Test
import os
import signal

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


112 113 114 115 116 117 118 119 120 121 122 123 124
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 已提交
125
def probe_binary(binary):
126
    try:
A
Amador Pahim 已提交
127
        return utils_path.find_command(binary)
128
    except utils_path.CmdNotFoundError:
A
Amador Pahim 已提交
129 130
        return None

L
Lukáš Doktor 已提交
131

132
TRUE_CMD = probe_binary('true')
A
Amador Pahim 已提交
133
CC_BINARY = probe_binary('cc')
134

L
Lukáš Doktor 已提交
135
# On macOS, the default GNU core-utils installation (brew)
136 137 138 139 140
# 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:
141
    if probe_binary('man') is not None:
142 143 144
        echo_cmd = 'man %s' % os.path.basename(GNU_ECHO_BINARY)
        echo_manpage = process.run(echo_cmd, env={'LANG': 'C'},
                                   encoding='ascii').stdout
145
        if b'-e' not in echo_manpage:
146
            GNU_ECHO_BINARY = probe_binary('gecho')
A
Amador Pahim 已提交
147 148
READ_BINARY = probe_binary('read')
SLEEP_BINARY = probe_binary('sleep')
149 150


151 152 153 154 155 156 157 158
def html_capable():
    try:
        pkg_resources.require('avocado-framework-plugin-result-html')
        return True
    except pkg_resources.DistributionNotFound:
        return False


159 160
class RunnerOperationTest(unittest.TestCase):

161
    def setUp(self):
162
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
163
        os.chdir(basedir)
164

165
    def test_show_version(self):
166
        result = process.run('%s -v' % AVOCADO, ignore_status=True)
167
        self.assertEqual(result.exit_status, 0)
168 169 170 171 172
        if sys.version_info[0] == 3:
            content = result.stdout_text
        else:
            content = result.stderr_text
        self.assertTrue(re.match(r"^Avocado \d+\.\d+$", content),
C
Cleber Rosa 已提交
173
                        "Version string does not match 'Avocado \\d\\.\\d:'\n"
174
                        "%r" % (content))
175

176 177 178 179 180 181 182 183 184 185 186 187 188
    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')}
189
        config = '[datadir.paths]\n'
190
        for key, value in iteritems(mapping):
191 192 193 194
            if not os.path.isdir(value):
                os.mkdir(value)
            config += "%s = %s\n" % (key, value)
        fd, config_file = tempfile.mkstemp(dir=self.tmpdir)
195
        os.write(fd, config.encode())
196 197
        os.close(fd)

198
        cmd = '%s --config %s config --datadir' % (AVOCADO, config_file)
199 200 201 202 203
        result = process.run(cmd)
        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))
204 205 206
        self.assertIn('    base     ' + mapping['base_dir'], result.stdout_text)
        self.assertIn('    data     ' + mapping['data_dir'], result.stdout_text)
        self.assertIn('    logs     ' + mapping['logs_dir'], result.stdout_text)
207

208
    def test_runner_all_ok(self):
209 210
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py passtest.py' % (AVOCADO, self.tmpdir))
211
        process.run(cmd_line)
212
        # Also check whether jobdata contains correct parameter paths
213 214
        variants = open(os.path.join(self.tmpdir, "latest", "jobdata",
                        "variants.json")).read()
215
        self.assertIn('["/run/*"]', variants, "paths stored in jobdata "
216
                      "does not contains [\"/run/*\"]\n%s" % variants)
217

218
    def test_runner_failfast(self):
219 220 221
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py failtest.py passtest.py --failfast on'
                    % (AVOCADO, self.tmpdir))
222
        result = process.run(cmd_line, ignore_status=True)
223 224
        self.assertIn(b'Interrupting job (failfast).', result.stdout)
        self.assertIn(b'PASS 1 | ERROR 0 | FAIL 1 | SKIP 1', result.stdout)
225 226 227 228
        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 已提交
229 230 231 232 233
    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)
234 235
        self.assertIn(b"Unable to resolve reference(s) 'badtest.py'", result.stderr)
        self.assertIn(b'PASS 1 | ERROR 0 | FAIL 0 | SKIP 0', result.stdout)
A
Amador Pahim 已提交
236 237 238 239 240 241 242 243 244
        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)
245
        self.assertIn(b"Unable to resolve reference(s) 'badtest.py', 'badtest2.py'",
A
Amador Pahim 已提交
246
                      result.stderr)
247
        self.assertEqual(b'', result.stdout)
A
Amador Pahim 已提交
248 249 250 251
        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))

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
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
274
            results = json.loads(res.stdout_text)
275 276 277
            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
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
293
            results = json.loads(res.stdout_text)
294 295 296 297 298
            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
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
315
            results = json.loads(res.stdout_text)
316 317 318 319 320 321
            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
        result = process.run(cmd_line, ignore_status=True)
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(b"TestError: Failing during tearDown. Yay!", result.stdout,
352
                      "Cleanup exception not printed to log output")
353 354
        self.assertIn(b"TestFail: This test is supposed to fail", result.stdout,
                      "Test did not fail with action exception:\n%s" % result.stdout)
355

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

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

376 377 378 379 380 381 382 383 384 385 386 387 388 389
    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))
390 391
        self.assertIn(b"mytest.py:SharedLibTest.test -> CancelExc: This "
                      b"should not crash on unpickling in runner",
392
                      result.stdout)
393
        self.assertNotIn(b"Failed to read queue", result.stdout)
394

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

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

427
    def test_silent_output(self):
428 429
        cmd_line = ('%s --silent run --sysinfo=off --job-results-dir %s '
                    'passtest.py' % (AVOCADO, self.tmpdir))
430
        result = process.run(cmd_line, ignore_status=True)
431
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
432
        self.assertEqual(result.stdout, b'')
433

434
    def test_empty_args_list(self):
435
        cmd_line = AVOCADO
436
        result = process.run(cmd_line, ignore_status=True)
437
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_FAIL)
438 439 440 441 442
        if sys.version_info[0] == 3:
            exp = b'avocado: error: the following arguments are required'
        else:
            exp = b'error: too few arguments'
        self.assertIn(exp, result.stderr)
443

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

452
    def test_not_found(self):
453 454
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s sbrubles'
                    % (AVOCADO, self.tmpdir))
455
        result = process.run(cmd_line, ignore_status=True)
456
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_JOB_FAIL)
457 458
        self.assertIn(b'Unable to resolve reference', result.stderr)
        self.assertNotIn(b'Unable to resolve reference', result.stdout)
459

460
    def test_invalid_unique_id(self):
461 462
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s --force-job-id '
                    'foobar passtest.py' % (AVOCADO, self.tmpdir))
463
        result = process.run(cmd_line, ignore_status=True)
464
        self.assertNotEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
465 466
        self.assertIn(b'needs to be a 40 digit hex', result.stderr)
        self.assertNotIn(b'needs to be a 40 digit hex', result.stdout)
467 468

    def test_valid_unique_id(self):
469
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
470
                    '--force-job-id 975de258ac05ce5e490648dec4753657b7ccc7d1 '
471
                    'passtest.py' % (AVOCADO, self.tmpdir))
472
        result = process.run(cmd_line, ignore_status=True)
473
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
474 475
        self.assertNotIn(b'needs to be a 40 digit hex', result.stderr)
        self.assertIn(b'PASS', result.stdout)
476

477
    def test_automatic_unique_id(self):
478 479
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    'passtest.py --json -' % (AVOCADO, self.tmpdir))
480
        result = process.run(cmd_line, ignore_status=True)
481
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
482
        r = json.loads(result.stdout_text)
483 484 485
        int(r['job_id'], 16)  # it's an hex number
        self.assertEqual(len(r['job_id']), 40)

486 487 488
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 2,
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
489 490 491 492
    def test_early_latest_result(self):
        """
        Tests that the `latest` link to the latest job results is created early
        """
493 494
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'examples/tests/passtest.py' % (AVOCADO, self.tmpdir))
495
        avocado_process = process.SubProcess(cmd_line)
496 497 498
        try:
            avocado_process.start()
            link = os.path.join(self.tmpdir, 'latest')
499
            for _ in range(0, 50):
500 501 502 503 504 505 506 507
                time.sleep(0.1)
                if os.path.exists(link) and os.path.islink(link):
                    avocado_process.wait()
                    break
            self.assertTrue(os.path.exists(link))
            self.assertTrue(os.path.islink(link))
        finally:
            avocado_process.wait()
508

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
        result = json.loads(process.run(cmd).stdout_text)
514
        debuglog = result['debuglog']
515
        log = genio.read_file(debuglog)
516 517
        # 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 range(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 532
            self.assertEqual(log.count(line), 4,
                             "Avocado log count for param '%s' not as expected:\n%s" % (line, log))
533

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

A
Amador Pahim 已提交
547
    @unittest.skipIf(not READ_BINARY, "read binary not available.")
548 549 550
    @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 已提交
551
    def test_read(self):
552
        cmd = "%s run --sysinfo=off --job-results-dir %%s %%s" % AVOCADO
553
        cmd %= (self.tmpdir, READ_BINARY)
554
        result = process.run(cmd, timeout=10, ignore_status=True)
L
Lukáš Doktor 已提交
555 556 557 558 559
        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)

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

563

564 565 566
class RunnerHumanOutputTest(unittest.TestCase):

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

    def test_output_pass(self):
571 572
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'passtest.py' % (AVOCADO, self.tmpdir))
573
        result = process.run(cmd_line, ignore_status=True)
574
        expected_rc = exit_codes.AVOCADO_ALL_OK
575 576 577
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
578
        self.assertIn(b'passtest.py:PassTest.test:  PASS', result.stdout)
579 580

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

    def test_output_error(self):
591 592
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'errortest.py' % (AVOCADO, self.tmpdir))
593
        result = process.run(cmd_line, ignore_status=True)
594
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
595 596 597
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
598
        self.assertIn(b'errortest.py:ErrorTest.test:  ERROR', result.stdout)
599

A
Amador Pahim 已提交
600
    def test_output_cancel(self):
601 602
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'cancelonsetup.py' % (AVOCADO, self.tmpdir))
603
        result = process.run(cmd_line, ignore_status=True)
604
        expected_rc = exit_codes.AVOCADO_ALL_OK
605 606 607
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
608 609
        self.assertIn(b'PASS 0 | ERROR 0 | FAIL 0 | SKIP 0 | WARN 0 | '
                      b'INTERRUPT 0 | CANCEL 1',
A
Amador Pahim 已提交
610
                      result.stdout)
611

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

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

648 649 650
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

651

652
class RunnerSimpleTest(unittest.TestCase):
653 654

    def setUp(self):
655
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
656
        self.pass_script = script.TemporaryScript(
657
            u'\u00e1 \u00e9 \u00ed \u00f3 \u00fa',
658
            "#!/bin/sh\ntrue",
659
            'avocado_simpletest_functional')
660
        self.pass_script.save()
L
Lukáš Doktor 已提交
661
        self.fail_script = script.TemporaryScript('avocado_fail.sh',
662
                                                  "#!/bin/sh\nfalse",
L
Lukáš Doktor 已提交
663 664
                                                  'avocado_simpletest_'
                                                  'functional')
665
        self.fail_script.save()
666
        os.chdir(basedir)
667

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

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

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

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

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

728 729 730 731
    def test_simplewarning(self):
        """
        simplewarning.sh uses the avocado-bash-utils
        """
732 733 734 735 736
        # 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')
737 738 739
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    'examples/tests/simplewarning.sh --show-job-log'
                    % (AVOCADO, self.tmpdir))
740
        result = process.run(cmd_line, ignore_status=True)
741 742 743 744
        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))
745 746 747 748 749 750
        self.assertIn(b'DEBUG| Debug message', result.stdout, result)
        self.assertIn(b'INFO | Info message', result.stdout, result)
        self.assertIn(b'WARN | Warning message (should cause this test to '
                      b'finish with warning)', result.stdout, result)
        self.assertIn(b'ERROR| Error message (ordinary message not changing '
                      b'the results)', result.stdout, result)
751 752
        self.assertIn(b'Test passed but there were warnings', result.stdout,
                      result)
753

754 755 756 757 758 759 760 761 762 763 764 765
    @unittest.skipIf(not GNU_ECHO_BINARY, "Uses echo as test")
    def test_fs_unfriendly_run(self):
        os.chdir(basedir)
        commands_path = os.path.join(self.tmpdir, "commands")
        script.make_script(commands_path, "echo '\"\\/|?*<>'")
        config_path = os.path.join(self.tmpdir, "config.conf")
        script.make_script(config_path,
                           "[sysinfo.collectibles]\ncommands = %s"
                           % commands_path)
        cmd_line = ("%s --show all --config %s run --job-results-dir %s "
                    "--sysinfo=on --external-runner %s -- \"'\\\"\\/|?*<>'\""
                    % (AVOCADO, config_path, self.tmpdir, GNU_ECHO_BINARY))
766
        process.run(cmd_line)
767 768 769 770 771 772 773 774 775 776 777 778
        self.assertTrue(os.path.exists(os.path.join(self.tmpdir, "latest",
                                                    "test-results",
                                                    "1-\'________\'/")))
        self.assertTrue(os.path.exists(os.path.join(self.tmpdir, "latest",
                                                    "sysinfo", "pre",
                                                    "echo \'________\'")))

        if html_capable():
            with open(os.path.join(self.tmpdir, "latest",
                                   "results.html")) as html_res:
                html_results = html_res.read()
            # test results should replace odd chars with "_"
779 780 781 782 783 784
            # HTML could contain either the literal char, or an entity reference
            test1_href = (os.path.join("test-results",
                                       "1-'________'") in html_results or
                          os.path.join("test-results",
                                       "1-&#x27;________&#x27;") in html_results)
            self.assertTrue(test1_href)
785
            # sysinfo replaces "_" with " "
786 787 788
            sysinfo = ("echo '________'" in html_results or
                       "echo &#x27;________&#x27;" in html_results)
            self.assertTrue(sysinfo)
789

790 791 792 793
    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)
794
        test_file_name = os.path.basename(self.pass_script.path)
795 796 797
        cmd_line = ('%s %s run --job-results-dir %s --sysinfo=off'
                    ' "%s"' % (sys.executable, avocado_path, self.tmpdir,
                               test_file_name))
798 799 800 801 802 803
        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 已提交
804
    @unittest.skipIf(not SLEEP_BINARY, 'sleep binary not available')
805
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 2,
806 807
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
808
    def test_kill_stopped_sleep(self):
809 810 811 812
        proc = aexpect.Expect("%s run 60 --job-results-dir %s "
                              "--external-runner %s --sysinfo=off "
                              "--job-timeout 3"
                              % (AVOCADO, self.tmpdir, SLEEP_BINARY))
L
Lukáš Doktor 已提交
813
        proc.read_until_output_matches([r"\(1/1\)"], timeout=3,
814
                                       internal_timeout=0.01)
815 816 817 818
        # 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
819
        os.kill(pid, signal.SIGTSTP)   # This freezes the process
820
        deadline = time.time() + 9
821 822 823
        while time.time() < deadline:
            if not proc.is_alive():
                break
824
            time.sleep(0.1)
825 826
        else:
            proc.kill(signal.SIGKILL)
827
            self.fail("Avocado process still alive 5s after job-timeout:\n%s"
828 829 830 831 832 833 834
                      % 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")
835
        self.assertEqual(proc.get_status(), 8, "Avocado did not finish with "
836
                         "1.")
837 838

        sleep_dir = astring.string_to_safe_path("1-60")
839 840 841 842
        debug_log_path = os.path.join(self.tmpdir, "latest", "test-results",
                                      sleep_dir, "debug.log")

        debug_log = genio.read_file(debug_log_path)
843 844 845 846 847 848 849
        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)
850

851
    def tearDown(self):
852 853
        self.pass_script.remove()
        self.fail_script.remove()
854
        shutil.rmtree(self.tmpdir)
855 856


A
Amador Pahim 已提交
857 858 859 860 861 862 863 864
class RunnerSimpleTestStatus(unittest.TestCase):

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

        self.config_file = script.TemporaryScript('avocado.conf',
                                                  "[simpletests.status]\n"
                                                  "warn_regex = ^WARN$\n"
865 866
                                                  "skip_regex = ^SKIP$\n"
                                                  "skip_location = stdout\n")
A
Amador Pahim 已提交
867 868 869 870
        self.config_file.save()
        os.chdir(basedir)

    def test_simpletest_status(self):
871
        # Multi-line warning in STDERR should by default be handled
A
Amador Pahim 已提交
872
        warn_script = script.TemporaryScript('avocado_warn.sh',
873
                                             '#!/bin/sh\n'
874
                                             '>&2 echo -e "\\n\\nWARN\\n"',
A
Amador Pahim 已提交
875 876 877 878 879 880
                                             'avocado_simpletest_'
                                             'functional')
        warn_script.save()
        cmd_line = ('%s --config %s run --job-results-dir %s --sysinfo=off'
                    ' %s --json -' % (AVOCADO, self.config_file.path,
                                      self.tmpdir, warn_script.path))
881 882
        result = process.run(cmd_line, ignore_status=True)
        json_results = json.loads(result.stdout_text)
883
        self.assertEqual(json_results['tests'][0]['status'], 'WARN')
A
Amador Pahim 已提交
884
        warn_script.remove()
885
        # Skip in STDOUT should be handled because of config
A
Amador Pahim 已提交
886 887 888 889 890 891 892 893
        skip_script = script.TemporaryScript('avocado_skip.sh',
                                             "#!/bin/sh\necho SKIP",
                                             'avocado_simpletest_'
                                             'functional')
        skip_script.save()
        cmd_line = ('%s --config %s run --job-results-dir %s --sysinfo=off'
                    ' %s --json -' % (AVOCADO, self.config_file.path,
                                      self.tmpdir, skip_script.path))
894 895
        result = process.run(cmd_line, ignore_status=True)
        json_results = json.loads(result.stdout_text)
896
        self.assertEqual(json_results['tests'][0]['status'], 'SKIP')
A
Amador Pahim 已提交
897
        skip_script.remove()
898 899 900 901 902 903 904 905 906 907 908
        # STDERR skip should not be handled
        skip2_script = script.TemporaryScript('avocado_skip.sh',
                                              "#!/bin/sh\n>&2 echo SKIP",
                                              'avocado_simpletest_'
                                              'functional')
        skip2_script.save()
        cmd_line = ('%s --config %s run --job-results-dir %s --sysinfo=off'
                    ' %s --json -' % (AVOCADO, self.config_file.path,
                                      self.tmpdir, skip2_script.path))
        result = process.run(cmd_line, ignore_status=True)
        json_results = json.loads(result.stdout_text)
909
        self.assertEqual(json_results['tests'][0]['status'], 'PASS')
910
        skip2_script.remove()
A
Amador Pahim 已提交
911 912 913 914 915 916

    def tearDown(self):
        self.config_file.remove()
        shutil.rmtree(self.tmpdir)


917
class ExternalRunnerTest(unittest.TestCase):
C
Cleber Rosa 已提交
918 919

    def setUp(self):
920
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
C
Cleber Rosa 已提交
921 922
        self.pass_script = script.TemporaryScript(
            'pass',
923
            "exit 0",
924
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
925 926 927
        self.pass_script.save()
        self.fail_script = script.TemporaryScript(
            'fail',
928
            "exit 1",
929
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
930
        self.fail_script.save()
931
        os.chdir(basedir)
C
Cleber Rosa 已提交
932

933
    def test_externalrunner_pass(self):
934 935 936
        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 已提交
937
        result = process.run(cmd_line, ignore_status=True)
938
        expected_rc = exit_codes.AVOCADO_ALL_OK
C
Cleber Rosa 已提交
939 940 941 942
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

943
    def test_externalrunner_fail(self):
944 945 946
        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 已提交
947
        result = process.run(cmd_line, ignore_status=True)
948
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
C
Cleber Rosa 已提交
949 950 951 952
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

953
    def test_externalrunner_chdir_no_testdir(self):
954 955 956
        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 已提交
957
        result = process.run(cmd_line, ignore_status=True)
958 959
        expected_output = (b'Option "--external-runner-chdir=test" requires '
                           b'"--external-runner-testdir" to be set')
C
Cleber Rosa 已提交
960
        self.assertIn(expected_output, result.stderr)
961
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
962 963 964 965 966
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

    def test_externalrunner_no_url(self):
967 968
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off '
                    '--external-runner=%s' % (AVOCADO, self.tmpdir, TRUE_CMD))
969
        result = process.run(cmd_line, ignore_status=True)
970 971
        expected_output = (b'No test references provided nor any other '
                           b'arguments resolved into tests')
972 973
        self.assertIn(expected_output, result.stderr)
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
C
Cleber Rosa 已提交
974 975 976 977 978 979 980 981 982 983
        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)


984
class AbsPluginsTest(object):
985

986
    def setUp(self):
987
        self.base_outputdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
988
        os.chdir(basedir)
989

990 991 992 993 994 995
    def tearDown(self):
        shutil.rmtree(self.base_outputdir)


class PluginsTest(AbsPluginsTest, unittest.TestCase):

996
    def test_sysinfo_plugin(self):
997
        cmd_line = '%s sysinfo %s' % (AVOCADO, self.base_outputdir)
998
        result = process.run(cmd_line, ignore_status=True)
999
        expected_rc = exit_codes.AVOCADO_ALL_OK
1000 1001 1002 1003 1004 1005
        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")

1006
    def test_list_plugin(self):
1007
        cmd_line = '%s list' % AVOCADO
1008
        result = process.run(cmd_line, ignore_status=True)
1009
        expected_rc = exit_codes.AVOCADO_ALL_OK
1010 1011 1012
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
1013 1014
        self.assertNotIn(b'No tests were found on current tests dir',
                         result.stdout)
1015

1016
    def test_list_error_output(self):
1017
        cmd_line = '%s list sbrubles' % AVOCADO
1018
        result = process.run(cmd_line, ignore_status=True)
1019
        expected_rc = exit_codes.AVOCADO_FAIL
1020 1021 1022
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
1023
        self.assertIn(b"Unable to resolve reference", result.stderr)
1024

1025 1026 1027 1028 1029 1030 1031
    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))
1032
        exp = (b"Type    Test                 Tag(s)\n"
1033
               b"MISSING this-wont-be-matched\n\n"
1034 1035 1036 1037
               b"TEST TYPES SUMMARY\n"
               b"==================\n"
               b"EXTERNAL: 0\n"
               b"MISSING: 1\n")
1038 1039 1040
        self.assertEqual(exp, result.stdout, "Stdout mismatch:\n%s\n\n%s"
                         % (exp, result))

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    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))
1053
        stdout_lines = result.stdout_text.splitlines()
1054 1055
        self.assertIn("Tag(s)", stdout_lines[0])
        full_test_name = "%s:MyTest.test" % test
1056 1057
        self.assertEqual("INSTRUMENTED %s BIG_TAG_NAME" % full_test_name,
                         stdout_lines[1])
1058 1059 1060
        self.assertIn("TEST TYPES SUMMARY", stdout_lines)
        self.assertIn("INSTRUMENTED: 1", stdout_lines)
        self.assertIn("TEST TAGS SUMMARY", stdout_lines)
1061
        self.assertEqual("BIG_TAG_NAME: 1", stdout_lines[-1])
1062

1063
    def test_plugin_list(self):
1064
        cmd_line = '%s plugins' % AVOCADO
1065
        result = process.run(cmd_line, ignore_status=True)
1066
        expected_rc = exit_codes.AVOCADO_ALL_OK
1067 1068 1069
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
1070
        if sys.version_info[:2] >= (2, 7, 0):
1071
            self.assertNotIn(b'Disabled', result.stdout)
1072

1073
    def test_config_plugin(self):
1074
        cmd_line = '%s config --paginator off' % AVOCADO
1075
        result = process.run(cmd_line, ignore_status=True)
1076
        expected_rc = exit_codes.AVOCADO_ALL_OK
1077 1078 1079
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
1080
        self.assertNotIn(b'Disabled', result.stdout)
1081 1082

    def test_config_plugin_datadir(self):
1083
        cmd_line = '%s config --datadir --paginator off' % AVOCADO
1084
        result = process.run(cmd_line, ignore_status=True)
1085
        expected_rc = exit_codes.AVOCADO_ALL_OK
1086 1087 1088
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
1089
        self.assertNotIn(b'Disabled', result.stdout)
1090

1091
    def test_disable_plugin(self):
1092
        cmd_line = '%s plugins' % AVOCADO
1093 1094 1095 1096 1097
        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))
1098
        self.assertIn(b"Collect system information", result.stdout)
1099 1100 1101 1102 1103

        config_content = "[plugins]\ndisable=['cli.cmd.sysinfo',]"
        config = script.TemporaryScript("disable_sysinfo_cmd.conf",
                                        config_content)
        with config:
1104
            cmd_line = '%s --config %s plugins' % (AVOCADO, config)
1105 1106 1107 1108 1109
            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))
1110
            self.assertNotIn(b"Collect system information", result.stdout)
1111

1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    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):
1124
            cmd = ('%s --config %s run passtest.py --archive '
1125
                   '--job-results-dir %s --sysinfo=off'
1126
                   % (AVOCADO, config_path, self.base_outputdir))
1127 1128 1129 1130 1131 1132 1133 1134
            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"]
1135
        if html_capable():
1136
            result_plugins.append("html")
1137
            result_outputs.append("results.html")
1138

1139
        cmd_line = '%s plugins' % AVOCADO
1140 1141 1142 1143 1144 1145
        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:
1146
            self.assertIn(result_plugin, result.stdout_text)
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

        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',"
1162 1163
                                   "'xunit', 'non_existing_plugin_is_ignored'"
                                   ",'zip_archive']")
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        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)

1175
    def test_Namespace_object_has_no_attribute(self):
1176
        cmd_line = '%s plugins' % AVOCADO
1177
        result = process.run(cmd_line, ignore_status=True)
1178
        expected_rc = exit_codes.AVOCADO_ALL_OK
1179 1180 1181
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
1182
        self.assertNotIn(b"'Namespace' object has no attribute", result.stderr)
1183

1184

1185 1186 1187 1188
class ParseXMLError(Exception):
    pass


1189
class PluginsXunitTest(AbsPluginsTest, unittest.TestCase):
1190

1191 1192
    @unittest.skipUnless(SCHEMA_CAPABLE,
                         'Unable to validate schema due to missing lxml.etree library')
1193
    def setUp(self):
1194
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
L
Lucas Meneghel Rodrigues 已提交
1195
        junit_xsd = os.path.join(os.path.dirname(__file__),
1196
                                 os.path.pardir, ".data", 'jenkins-junit.xsd')
L
Lucas Meneghel Rodrigues 已提交
1197
        self.junit = os.path.abspath(junit_xsd)
1198 1199
        super(PluginsXunitTest, self).setUp()

1200
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
1201
                      e_nnotfound, e_nfailures, e_nskip):
1202 1203
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' --xunit - %s' % (AVOCADO, self.tmpdir, testname))
1204 1205 1206 1207 1208 1209 1210
        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)
1211
        except Exception as detail:
1212 1213 1214
            raise ParseXMLError("Failed to parse content: %s\n%s" %
                                (detail, xml_output))

1215
        with open(self.junit, 'rb') as f:
1216
            xmlschema = etree.XMLSchema(etree.parse(f))   # pylint: disable=I1101
1217

1218
        # pylint: disable=I1101
1219
        self.assertTrue(xmlschema.validate(etree.parse(BytesIO(xml_output))),
1220 1221 1222 1223
                        "Failed to validate against %s, message:\n%s" %
                        (self.junit,
                         xmlschema.error_log.filter_from_errors()))

1224 1225 1226 1227
        testsuite_list = xunit_doc.getElementsByTagName('testsuite')
        self.assertEqual(len(testsuite_list), 1, 'More than one testsuite tag')

        testsuite_tag = testsuite_list[0]
1228 1229
        self.assertEqual(len(testsuite_tag.attributes), 7,
                         'The testsuite tag does not have 7 attributes. '
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
                         '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)

1247
        n_skip = int(testsuite_tag.attributes['skipped'].value)
1248 1249 1250 1251
        self.assertEqual(n_skip, e_nskip,
                         "Unexpected number of test skips, "
                         "XML:\n%s" % xml_output)

1252
    def test_xunit_plugin_passtest(self):
1253
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1254
                           1, 0, 0, 0, 0)
1255 1256

    def test_xunit_plugin_failtest(self):
1257
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1258
                           1, 0, 0, 1, 0)
1259

1260
    def test_xunit_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1261
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1262
                           1, 0, 0, 0, 1)
1263

1264
    def test_xunit_plugin_errortest(self):
1265
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1266
                           1, 1, 0, 0, 0)
1267

1268 1269 1270 1271
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsXunitTest, self).tearDown()

1272 1273 1274 1275 1276

class ParseJSONError(Exception):
    pass


1277
class PluginsJSONTest(AbsPluginsTest, unittest.TestCase):
1278

1279
    def setUp(self):
1280
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
1281 1282
        super(PluginsJSONTest, self).setUp()

1283
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
1284
                      e_nfailures, e_nskip, e_ncancel=0, external_runner=None):
1285 1286
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off --json - '
                    '--archive %s' % (AVOCADO, self.tmpdir, testname))
1287 1288
        if external_runner is not None:
            cmd_line += " --external-runner '%s'" % external_runner
1289
        result = process.run(cmd_line, ignore_status=True)
1290
        json_output = result.stdout_text
1291 1292 1293 1294 1295
        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)
1296
        except Exception as detail:
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
            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")
1314 1315
        n_cancel = json_data['cancel']
        self.assertEqual(n_cancel, e_ncancel)
1316
        return json_data
1317

1318
    def test_json_plugin_passtest(self):
1319
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1320
                           1, 0, 0, 0)
1321 1322

    def test_json_plugin_failtest(self):
1323
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1324
                           1, 0, 1, 0)
1325

1326
    def test_json_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1327
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1328
                           1, 0, 0, 0, 1)
1329

1330
    def test_json_plugin_errortest(self):
1331
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1332
                           1, 1, 0, 0)
1333

1334
    @unittest.skipIf(not GNU_ECHO_BINARY, 'echo binary not available')
1335
    def test_ugly_echo_cmd(self):
1336
        data = self.run_and_check('"-ne foo\\\\\\n\\\'\\\\\\"\\\\\\'
1337
                                  'nbar/baz"', exit_codes.AVOCADO_ALL_OK, 1, 0,
1338
                                  0, 0, external_runner=GNU_ECHO_BINARY)
1339
        # The executed test should be this
1340
        self.assertEqual(data['tests'][0]['id'],
1341
                         '1--ne foo\\\\n\\\'\\"\\\\nbar/baz')
1342 1343
        # logdir name should escape special chars (/)
        self.assertEqual(os.path.basename(data['tests'][0]['logdir']),
1344
                         "1--ne foo__n_'____nbar_baz")
1345

1346 1347 1348 1349
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsJSONTest, self).tearDown()

L
Lukáš Doktor 已提交
1350

1351 1352
if __name__ == '__main__':
    unittest.main()