test_basic.py 61.2 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", "./scripts/avocado")

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

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

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

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

    def test(self):
        pass
'''

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

class MyTest(Test):

    non_existing_variable_causing_crash

    def test_my_name(self):
        pass
'''

76

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

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


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

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

99

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

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


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

L
Lukáš Doktor 已提交
130

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

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


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


156 157
class RunnerOperationTest(unittest.TestCase):

158
    def setUp(self):
159
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
160
        os.chdir(basedir)
161

162
    def test_show_version(self):
163
        result = process.run('%s -v' % AVOCADO, ignore_status=True)
164
        self.assertEqual(result.exit_status, 0)
165 166 167 168 169
        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 已提交
170
                        "Version string does not match 'Avocado \\d\\.\\d:'\n"
171
                        "%r" % (content))
172

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

195
        cmd = '%s --config %s config --datadir' % (AVOCADO, config_file)
196 197 198 199 200
        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))
201 202 203
        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)
204

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

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

249 250 251
    def test_runner_test_with_local_imports(self):
        mylib = script.TemporaryScript(
            'mylib.py',
252
            "def hello():\n    return 'Hello world'",
253 254 255 256 257 258
            '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()
259 260
        cmd_line = ("%s run --sysinfo=off --job-results-dir %s "
                    "%s" % (AVOCADO, self.tmpdir, mytest))
261 262
        process.run(cmd_line)

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

278 279 280
    @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")
281 282 283 284 285
    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:
286
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s "
287
                              "--json - --job-timeout 1" % (AVOCADO, self.tmpdir, tst),
288
                              ignore_status=True)
289
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
290
            results = json.loads(res.stdout_text)
291 292 293 294 295
            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"])
296 297 298 299 300
            # 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, "
301 302 303 304 305 306 307
                            "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:
308 309 310
            res = process.run("%s run --sysinfo=off --job-results-dir %s %s "
                              "--json -" % (AVOCADO, self.tmpdir, tst),
                              ignore_status=True)
311
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
312
            results = json.loads(res.stdout_text)
313 314 315 316 317 318
            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"])

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

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

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

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

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

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

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

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

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

431
    def test_empty_args_list(self):
432
        cmd_line = AVOCADO
433
        result = process.run(cmd_line, ignore_status=True)
434
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_FAIL)
435 436 437 438 439
        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)
440

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

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

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

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

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

483 484 485
    @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")
486 487 488 489
    def test_early_latest_result(self):
        """
        Tests that the `latest` link to the latest job results is created early
        """
490 491
        cmd_line = ('%s run --sysinfo=off --job-results-dir %s '
                    'examples/tests/passtest.py' % (AVOCADO, self.tmpdir))
492
        avocado_process = process.SubProcess(cmd_line)
493 494 495
        try:
            avocado_process.start()
            link = os.path.join(self.tmpdir, 'latest')
496
            for _ in range(0, 50):
497 498 499 500 501 502 503 504
                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()
505

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

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

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

556 557 558
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

559

560 561 562
class RunnerHumanOutputTest(unittest.TestCase):

    def setUp(self):
563
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
564
        os.chdir(basedir)
565 566

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

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

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

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

608 609
    @unittest.skipIf(sys.version_info[0] == 3,
                     "Test currently broken on Python 3")
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 625
        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',
626
                      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_text)
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
            u'\u00e1 \u00e9 \u00ed \u00f3 \u00fa',
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 745 746 747 748
        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)
749 750
        self.assertIn(b'Test passed but there were warnings', result.stdout,
                      result)
751

752 753 754 755 756 757 758 759 760 761 762 763
    @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))
764
        process.run(cmd_line)
765 766 767 768 769 770 771 772 773 774 775 776
        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 "_"
777 778 779 780 781 782
            # 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)
783
            # sysinfo replaces "_" with " "
784 785 786
            sysinfo = ("echo '________'" in html_results or
                       "echo &#x27;________&#x27;" in html_results)
            self.assertTrue(sysinfo)
787

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

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

        debug_log = genio.read_file(debug_log_path)
840 841 842 843 844 845 846
        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)
847

848
    def tearDown(self):
849 850
        self.pass_script.remove()
        self.fail_script.remove()
851
        shutil.rmtree(self.tmpdir)
852 853


A
Amador Pahim 已提交
854 855 856 857 858 859 860 861
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"
862 863
                                                  "skip_regex = ^SKIP$\n"
                                                  "skip_location = stdout\n")
A
Amador Pahim 已提交
864 865 866 867
        self.config_file.save()
        os.chdir(basedir)

    def test_simpletest_status(self):
868
        # Multi-line warning in STDERR should by default be handled
A
Amador Pahim 已提交
869
        warn_script = script.TemporaryScript('avocado_warn.sh',
870
                                             '#!/bin/sh\n'
871
                                             '>&2 echo -e "\\n\\nWARN\\n"',
A
Amador Pahim 已提交
872 873 874 875 876 877
                                             '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))
878 879
        result = process.run(cmd_line, ignore_status=True)
        json_results = json.loads(result.stdout_text)
A
Amador Pahim 已提交
880 881
        self.assertEquals(json_results['tests'][0]['status'], 'WARN')
        warn_script.remove()
882
        # Skip in STDOUT should be handled because of config
A
Amador Pahim 已提交
883 884 885 886 887 888 889 890
        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))
891 892
        result = process.run(cmd_line, ignore_status=True)
        json_results = json.loads(result.stdout_text)
A
Amador Pahim 已提交
893 894
        self.assertEquals(json_results['tests'][0]['status'], 'SKIP')
        skip_script.remove()
895 896 897 898 899 900 901 902 903 904 905 906 907
        # 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)
        self.assertEquals(json_results['tests'][0]['status'], 'PASS')
        skip2_script.remove()
A
Amador Pahim 已提交
908 909 910 911 912 913

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


914
class ExternalRunnerTest(unittest.TestCase):
C
Cleber Rosa 已提交
915 916

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

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

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

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

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


981
class AbsPluginsTest(object):
982

983
    def setUp(self):
984
        self.base_outputdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
985
        os.chdir(basedir)
986

987 988 989 990 991 992
    def tearDown(self):
        shutil.rmtree(self.base_outputdir)


class PluginsTest(AbsPluginsTest, unittest.TestCase):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1181

1182 1183 1184 1185
class ParseXMLError(Exception):
    pass


1186
class PluginsXunitTest(AbsPluginsTest, unittest.TestCase):
1187

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

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

1212
        with open(self.junit, 'rb') as f:
1213
            xmlschema = etree.XMLSchema(etree.parse(f))   # pylint: disable=I1101
1214

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

1221 1222 1223 1224
        testsuite_list = xunit_doc.getElementsByTagName('testsuite')
        self.assertEqual(len(testsuite_list), 1, 'More than one testsuite tag')

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

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

1249
    def test_xunit_plugin_passtest(self):
1250
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1251
                           1, 0, 0, 0, 0)
1252 1253

    def test_xunit_plugin_failtest(self):
1254
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1255
                           1, 0, 0, 1, 0)
1256

1257
    def test_xunit_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1258
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1259
                           1, 0, 0, 0, 1)
1260

1261
    def test_xunit_plugin_errortest(self):
1262
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1263
                           1, 1, 0, 0, 0)
1264

1265 1266 1267 1268
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsXunitTest, self).tearDown()

1269 1270 1271 1272 1273

class ParseJSONError(Exception):
    pass


1274
class PluginsJSONTest(AbsPluginsTest, unittest.TestCase):
1275

1276
    def setUp(self):
1277
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
1278 1279
        super(PluginsJSONTest, self).setUp()

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

1315
    def test_json_plugin_passtest(self):
1316
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
1317
                           1, 0, 0, 0)
1318 1319

    def test_json_plugin_failtest(self):
1320
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
1321
                           1, 0, 1, 0)
1322

1323
    def test_json_plugin_skiponsetuptest(self):
A
Amador Pahim 已提交
1324
        self.run_and_check('cancelonsetup.py', exit_codes.AVOCADO_ALL_OK,
1325
                           1, 0, 0, 0, 1)
1326

1327
    def test_json_plugin_errortest(self):
1328
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
1329
                           1, 1, 0, 0)
1330

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

1343 1344 1345 1346
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsJSONTest, self).tearDown()

L
Lukáš Doktor 已提交
1347

1348 1349
if __name__ == '__main__':
    unittest.main()