test_basic.py 41.1 KB
Newer Older
1
import json
2
import os
3
import shutil
4
import time
5
import sys
6
import tempfile
7
import xml.dom.minidom
8
import glob
9 10
import aexpect
import signal
11
import re
12

13 14 15 16 17
if sys.version_info[:2] == (2, 6):
    import unittest2 as unittest
else:
    import unittest

18
from avocado.core import exit_codes
19 20 21 22
from avocado.utils import process
from avocado.utils import script


23
basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')
24 25 26
basedir = os.path.abspath(basedir)


27 28 29 30
PASS_SCRIPT_CONTENTS = """#!/bin/sh
true
"""

C
Cleber Rosa 已提交
31 32
PASS_SHELL_CONTENTS = "exit 0"

33 34 35 36
FAIL_SCRIPT_CONTENTS = """#!/bin/sh
false
"""

C
Cleber Rosa 已提交
37 38
FAIL_SHELL_CONTENTS = "exit 1"

39 40 41 42 43 44 45 46 47 48 49 50 51 52
HELLO_LIB_CONTENTS = """
def hello():
    return 'Hello world'
"""

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

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

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

class FakeStatusTest(Test):
    def run_avocado(self):
        super(FakeStatusTest, self).run_avocado()
        self.status = 'not supported'

    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

class RunnerOperationTest(unittest.TestCase):

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

82 83 84
    def test_show_version(self):
        result = process.run('./scripts/avocado -v', ignore_status=True)
        self.assertEqual(result.exit_status, 0)
C
Cleber Rosa 已提交
85 86 87
        self.assertTrue(re.match(r"^Avocado \d+\.\d+$", result.stderr),
                        "Version string does not match 'Avocado \\d\\.\\d:'\n"
                        "%r" % (result.stderr))
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    def test_alternate_config_datadir(self):
        """
        Uses the "--config" flag to check custom configuration is applied

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

        os.chdir(basedir)
        cmd = './scripts/avocado --config %s config --datadir' % config_file
        result = process.run(cmd)
        output = result.stdout
        expected_rc = exit_codes.AVOCADO_ALL_OK
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('    base     ' + mapping['base_dir'], result.stdout)
        self.assertIn('    data     ' + mapping['data_dir'], result.stdout)
        self.assertIn('    logs     ' + mapping['logs_dir'], result.stdout)

123 124
    def test_runner_all_ok(self):
        os.chdir(basedir)
125 126
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'passtest.py passtest.py' % self.tmpdir)
127 128
        process.run(cmd_line)

129 130
    def test_datadir_alias(self):
        os.chdir(basedir)
131 132 133 134 135 136 137 138 139
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'datadir.py' % self.tmpdir)
        process.run(cmd_line)

    def test_shell_alias(self):
        """ Tests that .sh files are also executable via alias """
        os.chdir(basedir)
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'env_variables.sh' % self.tmpdir)
140 141 142 143
        process.run(cmd_line)

    def test_datadir_noalias(self):
        os.chdir(basedir)
144 145
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s examples/tests/datadir.py '
                    'examples/tests/datadir.py' % self.tmpdir)
146 147
        process.run(cmd_line)

148 149
    def test_runner_noalias(self):
        os.chdir(basedir)
150 151
        cmd_line = ("./scripts/avocado run --sysinfo=off --job-results-dir %s examples/tests/passtest.py "
                    "examples/tests/passtest.py" % self.tmpdir)
152 153
        process.run(cmd_line)

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    def test_runner_test_with_local_imports(self):
        mylib = script.TemporaryScript(
            'mylib.py',
            HELLO_LIB_CONTENTS,
            'avocado_simpletest_functional')
        mylib.save()
        mytest = script.Script(
            os.path.join(os.path.dirname(mylib.path), 'test_local_imports.py'),
            LOCAL_IMPORT_TEST_CONTENTS)
        os.chdir(basedir)
        mytest.save()
        cmd_line = ("./scripts/avocado run --sysinfo=off --job-results-dir %s "
                    "%s" % (self.tmpdir, mytest))
        process.run(cmd_line)

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    def test_unsupported_status(self):
        os.chdir(basedir)
        with script.TemporaryScript("fake_status.py",
                                    UNSUPPORTED_STATUS_TEST_CONTENTS,
                                    "avocado_unsupported_status") as tst:
            res = process.run("./scripts/avocado run --sysinfo=off "
                              "--job-results-dir %s %s --json -"
                              % (self.tmpdir, tst), ignore_status=True)
            self.assertEqual(res.exit_status, exit_codes.AVOCADO_TESTS_FAIL)
            results = json.loads(res.stdout)
            self.assertEqual(results["tests"][0]["status"], "ERROR",
                             "%s != %s\n%s" % (results["tests"][0]["status"],
                                               "ERROR", res))
            self.assertIn("Original fail_reason: None",
                          results["tests"][0]["fail_reason"])

185 186
    def test_runner_tests_fail(self):
        os.chdir(basedir)
187 188
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'passtest.py failtest.py passtest.py' % self.tmpdir)
189
        result = process.run(cmd_line, ignore_status=True)
190
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
191 192 193 194 195
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

    def test_runner_nonexistent_test(self):
        os.chdir(basedir)
196 197
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir '
                    '%s bogustest' % self.tmpdir)
198
        result = process.run(cmd_line, ignore_status=True)
199 200
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
201 202 203 204 205
        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))

206 207
    def test_runner_doublefail(self):
        os.chdir(basedir)
208 209
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    '--xunit - doublefail.py' % self.tmpdir)
210 211
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
212 213
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
214 215 216 217
        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))
218
        self.assertIn("TestError: Failing during tearDown. Yay!", output,
219
                      "Cleanup exception not printed to log output")
220
        self.assertIn("TestFail: This test is supposed to fail",
221
                      output,
222
                      "Test did not fail with action exception:\n%s" % output)
223

224 225 226
    def test_uncaught_exception(self):
        os.chdir(basedir)
        cmd_line = ("./scripts/avocado run --sysinfo=off --job-results-dir %s "
227
                    "--json - uncaught_exception.py" % self.tmpdir)
228
        result = process.run(cmd_line, ignore_status=True)
229
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
230 231 232 233 234
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc,
                                                                result))
        self.assertIn('"status": "ERROR"', result.stdout)

235
    def test_fail_on_exception(self):
236 237
        os.chdir(basedir)
        cmd_line = ("./scripts/avocado run --sysinfo=off --job-results-dir %s "
238
                    "--json - fail_on_exception.py" % self.tmpdir)
239
        result = process.run(cmd_line, ignore_status=True)
240
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
241 242 243 244 245
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc,
                                                                result))
        self.assertIn('"status": "FAIL"', result.stdout)

246 247
    def test_runner_timeout(self):
        os.chdir(basedir)
248 249
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    '--xunit - timeouttest.py' % self.tmpdir)
250 251
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
252
        expected_rc = exit_codes.AVOCADO_JOB_INTERRUPTED
253
        unexpected_rc = exit_codes.AVOCADO_FAIL
254 255 256 257
        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))
258 259
        self.assertIn("RUNNER: Timeout reached", output,
                      "Timeout reached message not found in the output:\n%s" % output)
260 261
        # Ensure no test aborted error messages show up
        self.assertNotIn("TestAbortedError: Test aborted unexpectedly", output)
262

263 264
    def test_runner_abort(self):
        os.chdir(basedir)
265 266
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    '--xunit - abort.py' % self.tmpdir)
267
        result = process.run(cmd_line, ignore_status=True)
268 269
        output = result.stdout
        excerpt = 'Test process aborted'
270 271
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
        unexpected_rc = exit_codes.AVOCADO_FAIL
272 273 274 275
        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))
276
        self.assertIn(excerpt, output)
277

278 279
    def test_silent_output(self):
        os.chdir(basedir)
280 281
        cmd_line = ('./scripts/avocado --silent run --sysinfo=off '
                    '--job-results-dir %s passtest.py' % self.tmpdir)
282
        result = process.run(cmd_line, ignore_status=True)
283
        expected_rc = exit_codes.AVOCADO_ALL_OK
284 285
        expected_output = ''
        self.assertEqual(result.exit_status, expected_rc)
286
        self.assertEqual(result.stdout, expected_output)
287

288 289 290 291
    def test_empty_args_list(self):
        os.chdir(basedir)
        cmd_line = './scripts/avocado'
        result = process.run(cmd_line, ignore_status=True)
292
        expected_rc = exit_codes.AVOCADO_FAIL
293
        expected_output = 'error: too few arguments'
294
        self.assertEqual(result.exit_status, expected_rc)
295
        self.assertIn(expected_output, result.stderr)
296

297 298
    def test_empty_test_list(self):
        os.chdir(basedir)
299
        cmd_line = './scripts/avocado run --sysinfo=off'
300
        result = process.run(cmd_line, ignore_status=True)
301
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
302
        expected_output = 'No urls provided nor any arguments produced'
303
        self.assertEqual(result.exit_status, expected_rc)
304
        self.assertIn(expected_output, result.stderr)
305

306 307
    def test_not_found(self):
        os.chdir(basedir)
308
        cmd_line = './scripts/avocado run --sysinfo=off sbrubles'
309
        result = process.run(cmd_line, ignore_status=True)
310
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
311
        self.assertEqual(result.exit_status, expected_rc)
312 313
        self.assertIn('Unable to discover url', result.stderr)
        self.assertNotIn('Unable to discover url', result.stdout)
314

315
    def test_invalid_unique_id(self):
316 317
        cmd_line = ('./scripts/avocado run --sysinfo=off --force-job-id foobar'
                    ' passtest.py')
318
        result = process.run(cmd_line, ignore_status=True)
319
        self.assertNotEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
320
        self.assertIn('needs to be a 40 digit hex', result.stderr)
321
        self.assertNotIn('needs to be a 40 digit hex', result.stdout)
322 323

    def test_valid_unique_id(self):
324
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off '
325 326
                    '--force-job-id 975de258ac05ce5e490648dec4753657b7ccc7d1 '
                    'passtest.py' % self.tmpdir)
327
        result = process.run(cmd_line, ignore_status=True)
328
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
329
        self.assertNotIn('needs to be a 40 digit hex', result.stderr)
330
        self.assertIn('PASS', result.stdout)
331

332
    def test_automatic_unique_id(self):
333 334
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off '
                    'passtest.py --json -' % self.tmpdir)
335
        result = process.run(cmd_line, ignore_status=True)
336
        self.assertEqual(result.exit_status, exit_codes.AVOCADO_ALL_OK)
337 338 339 340
        r = json.loads(result.stdout)
        int(r['job_id'], 16)  # it's an hex number
        self.assertEqual(len(r['job_id']), 40)

341 342 343
    def test_skip_outside_setup(self):
        os.chdir(basedir)
        cmd_line = ("./scripts/avocado run --sysinfo=off --job-results-dir %s "
344
                    "--json - skip_outside_setup.py" % self.tmpdir)
345
        result = process.run(cmd_line, ignore_status=True)
346
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
347 348 349 350 351
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc,
                                                                result))
        self.assertIn('"status": "ERROR"', result.stdout)

352 353 354 355 356
    def test_early_latest_result(self):
        """
        Tests that the `latest` link to the latest job results is created early
        """
        os.chdir(basedir)
L
Lukáš Doktor 已提交
357 358
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'examples/tests/passtest.py' % self.tmpdir)
359 360 361 362 363 364
        avocado_process = process.SubProcess(cmd_line)
        avocado_process.start()
        link = os.path.join(self.tmpdir, 'latest')
        for trial in xrange(0, 50):
            time.sleep(0.1)
            if os.path.exists(link) and os.path.islink(link):
365
                avocado_process.wait()
366 367 368 369
                break
        self.assertTrue(os.path.exists(link))
        self.assertTrue(os.path.islink(link))

370 371
    def test_dry_run(self):
        os.chdir(basedir)
372 373 374
        cmd = ("./scripts/avocado run --sysinfo=off passtest.py failtest.py "
               "errortest.py --json - --mux-inject foo:1 bar:2 baz:3 foo:foo:a"
               " foo:bar:b foo:baz:c bar:bar:bar --dry-run")
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        result = json.loads(process.run(cmd).stdout)
        debuglog = result['debuglog']
        log = open(debuglog, 'r').read()
        # Remove the result dir
        shutil.rmtree(os.path.dirname(os.path.dirname(debuglog)))
        self.assertIn('/tmp', debuglog)   # Use tmp dir, not default location
        self.assertEqual(result['job_id'], u'0' * 40)
        # Check if all tests were skipped
        self.assertEqual(result['skip'], 3)
        for i in xrange(3):
            test = result['tests'][i]
            self.assertEqual(test['fail_reason'],
                             u'Test skipped due to --dry-run')
        # 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"):
            self.assertEqual(log.count(line), 3)

395 396 397 398 399 400 401 402 403 404 405
    def test_invalid_python(self):
        os.chdir(basedir)
        test = script.make_script(os.path.join(self.tmpdir, 'test.py'),
                                  INVALID_PYTHON_TEST)
        cmd_line = './scripts/avocado --show test run --sysinfo=off '\
                   '--job-results-dir %s %s' % (self.tmpdir, test)
        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))
406 407
        self.assertIn('1-%s:MyTest.test_my_name -> TestError' % test,
                      result.stdout)
408

409 410 411
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

412

413 414 415
class RunnerHumanOutputTest(unittest.TestCase):

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

    def test_output_pass(self):
        os.chdir(basedir)
420 421
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'passtest.py' % self.tmpdir)
422
        result = process.run(cmd_line, ignore_status=True)
423
        expected_rc = exit_codes.AVOCADO_ALL_OK
424 425 426 427 428 429 430
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('passtest.py:PassTest.test:  PASS', result.stdout)

    def test_output_fail(self):
        os.chdir(basedir)
431 432
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'failtest.py' % self.tmpdir)
433
        result = process.run(cmd_line, ignore_status=True)
434
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
435 436 437 438 439 440 441
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('failtest.py:FailTest.test:  FAIL', result.stdout)

    def test_output_error(self):
        os.chdir(basedir)
442 443
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'errortest.py' % self.tmpdir)
444
        result = process.run(cmd_line, ignore_status=True)
445
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
446 447 448 449 450 451 452
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertIn('errortest.py:ErrorTest.test:  ERROR', result.stdout)

    def test_output_skip(self):
        os.chdir(basedir)
453 454
        cmd_line = ('./scripts/avocado run --sysinfo=off --job-results-dir %s '
                    'skiponsetup.py' % self.tmpdir)
455
        result = process.run(cmd_line, ignore_status=True)
456
        expected_rc = exit_codes.AVOCADO_ALL_OK
457 458 459
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
L
Lukáš Doktor 已提交
460 461
        self.assertIn('skiponsetup.py:SkipOnSetupTest.test_wont_be_executed:'
                      '  SKIP', result.stdout)
462

463 464 465 466 467 468 469 470 471 472 473 474
    def test_ugly_echo_cmd(self):
        if not os.path.exists("/bin/echo"):
            self.skipTest("Program /bin/echo does not exist")
        os.chdir(basedir)
        cmd_line = ('./scripts/avocado run "/bin/echo -ne '
                    'foo\\\\\\n\\\'\\\\\\"\\\\\\nbar/baz" --job-results-dir %s'
                    ' --sysinfo=off  --show-job-log' % self.tmpdir)
        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))
475 476 477
        self.assertIn('[stdout] foo', result.stdout, result)
        self.assertIn('[stdout] \'"', result.stdout, result)
        self.assertIn('[stdout] bar/baz', result.stdout, result)
478
        self.assertIn('PASS 1-/bin/echo -ne foo\\\\n\\\'\\"\\\\nbar/baz',
479
                      result.stdout, result)
480 481 482 483 484 485 486
        # 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]),
487
                         '1-_bin_echo -ne foo\\\\n\\\'\\"\\\\nbar_baz')
488

489
    def test_replay_skip_skipped(self):
490
        result = process.run("./scripts/avocado run skiponsetup.py --json -")
491 492 493 494 495
        result = json.loads(result.stdout)
        jobid = result["job_id"]
        process.run(str("./scripts/avocado run --replay %s "
                        "--replay-test-status PASS" % jobid))

496 497 498
    def tearDown(self):
        shutil.rmtree(self.tmpdir)

499

500
class RunnerSimpleTest(unittest.TestCase):
501 502

    def setUp(self):
503
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
504 505 506
        self.pass_script = script.TemporaryScript(
            'avocado_pass.sh',
            PASS_SCRIPT_CONTENTS,
507
            'avocado_simpletest_functional')
508
        self.pass_script.save()
L
Lukáš Doktor 已提交
509 510 511 512
        self.fail_script = script.TemporaryScript('avocado_fail.sh',
                                                  FAIL_SCRIPT_CONTENTS,
                                                  'avocado_simpletest_'
                                                  'functional')
513
        self.fail_script.save()
514

515
    def test_simpletest_pass(self):
516
        os.chdir(basedir)
L
Lukáš Doktor 已提交
517 518
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off'
                    ' %s' % (self.tmpdir, self.pass_script.path))
519
        result = process.run(cmd_line, ignore_status=True)
520
        expected_rc = exit_codes.AVOCADO_ALL_OK
521 522 523 524
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

525
    def test_simpletest_fail(self):
526
        os.chdir(basedir)
L
Lukáš Doktor 已提交
527 528
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off'
                    ' %s' % (self.tmpdir, self.fail_script.path))
529
        result = process.run(cmd_line, ignore_status=True)
530
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
531 532 533 534
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

535 536 537
    def test_runner_onehundred_fail_timing(self):
        """
        We can be pretty sure that a failtest should return immediattely. Let's
538
        run 100 of them and assure they not take more than 30 seconds to run.
539

540 541
        Notice: on a current machine this takes about 0.12s, so 30 seconds is
        considered to be pretty safe here.
542 543
        """
        os.chdir(basedir)
544
        one_hundred = 'failtest.py ' * 100
L
Lukáš Doktor 已提交
545 546
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off'
                    ' %s' % (self.tmpdir, one_hundred))
547 548 549
        initial_time = time.time()
        result = process.run(cmd_line, ignore_status=True)
        actual_time = time.time() - initial_time
550
        self.assertLess(actual_time, 30.0)
551
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
552 553 554 555 556 557 558 559 560
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

    def test_runner_sleep_fail_sleep_timing(self):
        """
        Sleeptest is supposed to take 1 second, let's make a sandwich of
        100 failtests and check the test runner timing.
        """
        os.chdir(basedir)
561 562
        sleep_fail_sleep = ('sleeptest.py ' + 'failtest.py ' * 100 +
                            'sleeptest.py')
L
Lukáš Doktor 已提交
563 564
        cmd_line = './scripts/avocado run --job-results-dir %s --sysinfo=off %s' % (
            self.tmpdir, sleep_fail_sleep)
565 566 567
        initial_time = time.time()
        result = process.run(cmd_line, ignore_status=True)
        actual_time = time.time() - initial_time
568
        self.assertLess(actual_time, 33.0)
569
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
570 571 572
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" % (expected_rc, result))

573 574 575 576 577
    def test_simplewarning(self):
        """
        simplewarning.sh uses the avocado-bash-utils
        """
        os.chdir(basedir)
578 579
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off '
                    'examples/tests/simplewarning.sh --show-job-log' % self.tmpdir)
580
        result = process.run(cmd_line, ignore_status=True)
581 582 583 584
        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))
585 586
        self.assertIn('DEBUG| Debug message', result.stdout, result)
        self.assertIn('INFO | Info message', result.stdout, result)
587
        self.assertIn('WARN | Warning message (should cause this test to '
588
                      'finish with warning)', result.stdout, result)
589
        self.assertIn('ERROR| Error message (ordinary message not changing '
590
                      'the results)', result.stdout, result)
591

592 593 594 595 596 597 598 599 600 601 602 603 604
    def test_non_absolute_path(self):
        avocado_path = os.path.join(basedir, 'scripts', 'avocado')
        test_base_dir = os.path.dirname(self.pass_script.path)
        test_file_name = os.path.basename(self.pass_script.path)
        os.chdir(test_base_dir)
        cmd_line = ('%s run --job-results-dir %s --sysinfo=off'
                    ' %s' % (avocado_path, self.tmpdir, test_file_name))
        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))

605 606 607 608 609 610 611 612 613 614 615 616 617
    def test_kill_stopped_sleep(self):
        sleep = process.run("which sleep", ignore_status=True, shell=True)
        if sleep.exit_status:
            self.skipTest("Sleep binary not found in PATH")
        sleep = "'%s 60'" % sleep.stdout.strip()
        proc = aexpect.Expect("./scripts/avocado run %s --job-results-dir %s "
                              "--sysinfo=off --job-timeout 3"
                              % (sleep, self.tmpdir))
        proc.read_until_output_matches(["\(1/1\)"], timeout=3,
                                       internal_timeout=0.01)
        # We need pid of the avocado, not the shell executing it
        pid = int(process.get_children_pids(proc.get_pid())[0])
        os.kill(pid, signal.SIGTSTP)   # This freezes the process
618
        deadline = time.time() + 9
619 620 621
        while time.time() < deadline:
            if not proc.is_alive():
                break
622
            time.sleep(0.1)
623 624
        else:
            proc.kill(signal.SIGKILL)
625
            self.fail("Avocado process still alive 5s after job-timeout:\n%s"
626 627 628 629 630 631 632
                      % 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")
633
        self.assertEqual(proc.get_status(), 8, "Avocado did not finish with "
634
                         "1.")
635 636 637 638 639 640 641 642 643
        debug_log = os.path.join(self.tmpdir, "latest", "test-results",
                                 "1-_bin_sleep 60", "debug.log")
        debug_log = open(debug_log).read()
        self.assertIn("RUNNER: Timeout reached", debug_log, "RUNNER: Timeout "
                      "reached message not in the test's debug.log:\n%s"
                      % debug_log)
        self.assertNotIn("Traceback", 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)
644

645
    def tearDown(self):
646 647
        self.pass_script.remove()
        self.fail_script.remove()
648
        shutil.rmtree(self.tmpdir)
649 650


651
class ExternalRunnerTest(unittest.TestCase):
C
Cleber Rosa 已提交
652 653

    def setUp(self):
654
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
C
Cleber Rosa 已提交
655 656 657
        self.pass_script = script.TemporaryScript(
            'pass',
            PASS_SHELL_CONTENTS,
658
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
659 660 661 662
        self.pass_script.save()
        self.fail_script = script.TemporaryScript(
            'fail',
            FAIL_SHELL_CONTENTS,
663
            'avocado_externalrunner_functional')
C
Cleber Rosa 已提交
664 665
        self.fail_script.save()

666
    def test_externalrunner_pass(self):
C
Cleber Rosa 已提交
667
        os.chdir(basedir)
668
        cmd_line = './scripts/avocado run --job-results-dir %s --sysinfo=off --external-runner=/bin/sh %s'
C
Cleber Rosa 已提交
669 670
        cmd_line %= (self.tmpdir, self.pass_script.path)
        result = process.run(cmd_line, ignore_status=True)
671
        expected_rc = exit_codes.AVOCADO_ALL_OK
C
Cleber Rosa 已提交
672 673 674 675
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

676
    def test_externalrunner_fail(self):
C
Cleber Rosa 已提交
677
        os.chdir(basedir)
678
        cmd_line = './scripts/avocado run --job-results-dir %s --sysinfo=off --external-runner=/bin/sh %s'
C
Cleber Rosa 已提交
679 680
        cmd_line %= (self.tmpdir, self.fail_script.path)
        result = process.run(cmd_line, ignore_status=True)
681
        expected_rc = exit_codes.AVOCADO_TESTS_FAIL
C
Cleber Rosa 已提交
682 683 684 685
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

686
    def test_externalrunner_chdir_no_testdir(self):
C
Cleber Rosa 已提交
687
        os.chdir(basedir)
688 689
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off --external-runner=/bin/sh '
                    '--external-runner-chdir=test %s')
C
Cleber Rosa 已提交
690 691
        cmd_line %= (self.tmpdir, self.pass_script.path)
        result = process.run(cmd_line, ignore_status=True)
692 693
        expected_output = ('Option "--external-runner-chdir=test" requires '
                           '"--external-runner-testdir" to be set')
C
Cleber Rosa 已提交
694
        self.assertIn(expected_output, result.stderr)
695
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
696 697 698 699 700 701 702 703 704
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))

    def test_externalrunner_no_url(self):
        os.chdir(basedir)
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off '
                    '--external-runner=/bin/true' % self.tmpdir)
        result = process.run(cmd_line, ignore_status=True)
705
        expected_output = ('No urls provided nor any arguments produced')
706 707
        self.assertIn(expected_output, result.stderr)
        expected_rc = exit_codes.AVOCADO_JOB_FAIL
C
Cleber Rosa 已提交
708 709 710 711 712 713 714 715 716 717
        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)


718
class AbsPluginsTest(object):
719

720
    def setUp(self):
721
        self.base_outputdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
722

723 724 725 726 727 728
    def tearDown(self):
        shutil.rmtree(self.base_outputdir)


class PluginsTest(AbsPluginsTest, unittest.TestCase):

729 730 731 732
    def test_sysinfo_plugin(self):
        os.chdir(basedir)
        cmd_line = './scripts/avocado sysinfo %s' % self.base_outputdir
        result = process.run(cmd_line, ignore_status=True)
733
        expected_rc = exit_codes.AVOCADO_ALL_OK
734 735 736 737 738 739
        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")

740 741 742 743 744
    def test_list_plugin(self):
        os.chdir(basedir)
        cmd_line = './scripts/avocado list'
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
745
        expected_rc = exit_codes.AVOCADO_ALL_OK
746 747 748 749 750
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn('No tests were found on current tests dir', output)

751 752 753 754 755
    def test_list_error_output(self):
        os.chdir(basedir)
        cmd_line = './scripts/avocado list sbrubles'
        result = process.run(cmd_line, ignore_status=True)
        output = result.stderr
756
        expected_rc = exit_codes.AVOCADO_FAIL
757 758 759
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
760
        self.assertIn("Unable to discover url", output)
761

762 763 764 765 766
    def test_plugin_list(self):
        os.chdir(basedir)
        cmd_line = './scripts/avocado plugins'
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
767
        expected_rc = exit_codes.AVOCADO_ALL_OK
768 769 770
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
771 772
        if sys.version_info[:2] >= (2, 7, 0):
            self.assertNotIn('Disabled', output)
773

774
    def test_config_plugin(self):
775
        os.chdir(basedir)
776
        cmd_line = './scripts/avocado config --paginator off'
777 778
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
779
        expected_rc = exit_codes.AVOCADO_ALL_OK
780 781 782 783 784 785 786
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn('Disabled', output)

    def test_config_plugin_datadir(self):
        os.chdir(basedir)
787
        cmd_line = './scripts/avocado config --datadir --paginator off'
788 789
        result = process.run(cmd_line, ignore_status=True)
        output = result.stdout
790
        expected_rc = exit_codes.AVOCADO_ALL_OK
791 792 793 794 795
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn('Disabled', output)

796 797 798 799 800
    def test_Namespace_object_has_no_attribute(self):
        os.chdir(basedir)
        cmd_line = './scripts/avocado plugins'
        result = process.run(cmd_line, ignore_status=True)
        output = result.stderr
801
        expected_rc = exit_codes.AVOCADO_ALL_OK
802 803 804 805 806
        self.assertEqual(result.exit_status, expected_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (expected_rc, result))
        self.assertNotIn("'Namespace' object has no attribute", output)

807

808 809 810 811
class ParseXMLError(Exception):
    pass


812
class PluginsXunitTest(AbsPluginsTest, unittest.TestCase):
813

814
    def setUp(self):
815
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
816 817
        super(PluginsXunitTest, self).setUp()

818
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
819
                      e_nnotfound, e_nfailures, e_nskip):
820
        os.chdir(basedir)
L
Lukáš Doktor 已提交
821 822
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off'
                    ' --xunit - %s' % (self.tmpdir, testname))
823 824 825 826 827 828 829
        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)
830
        except Exception as detail:
831 832 833 834 835 836 837
            raise ParseXMLError("Failed to parse content: %s\n%s" %
                                (detail, xml_output))

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

        testsuite_tag = testsuite_list[0]
838 839
        self.assertEqual(len(testsuite_tag.attributes), 7,
                         'The testsuite tag does not have 7 attributes. '
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
                         '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)

857
        n_skip = int(testsuite_tag.attributes['skipped'].value)
858 859 860 861
        self.assertEqual(n_skip, e_nskip,
                         "Unexpected number of test skips, "
                         "XML:\n%s" % xml_output)

862
    def test_xunit_plugin_passtest(self):
863
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
864
                           1, 0, 0, 0, 0)
865 866

    def test_xunit_plugin_failtest(self):
867
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
868
                           1, 0, 0, 1, 0)
869

870
    def test_xunit_plugin_skiponsetuptest(self):
871
        self.run_and_check('skiponsetup.py', exit_codes.AVOCADO_ALL_OK,
872
                           1, 0, 0, 0, 1)
873

874
    def test_xunit_plugin_errortest(self):
875
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
876
                           1, 1, 0, 0, 0)
877

878 879 880 881
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsXunitTest, self).tearDown()

882 883 884 885 886

class ParseJSONError(Exception):
    pass


887
class PluginsJSONTest(AbsPluginsTest, unittest.TestCase):
888

889
    def setUp(self):
890
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
891 892
        super(PluginsJSONTest, self).setUp()

893
    def run_and_check(self, testname, e_rc, e_ntests, e_nerrors,
894 895
                      e_nfailures, e_nskip):
        os.chdir(basedir)
896 897
        cmd_line = ('./scripts/avocado run --job-results-dir %s --sysinfo=off --json - --archive %s' %
                    (self.tmpdir, testname))
898 899 900 901 902 903 904
        result = process.run(cmd_line, ignore_status=True)
        json_output = result.stdout
        self.assertEqual(result.exit_status, e_rc,
                         "Avocado did not return rc %d:\n%s" %
                         (e_rc, result))
        try:
            json_data = json.loads(json_output)
905
        except Exception as detail:
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
            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")
923
        return json_data
924

925
    def test_json_plugin_passtest(self):
926
        self.run_and_check('passtest.py', exit_codes.AVOCADO_ALL_OK,
927
                           1, 0, 0, 0)
928 929

    def test_json_plugin_failtest(self):
930
        self.run_and_check('failtest.py', exit_codes.AVOCADO_TESTS_FAIL,
931
                           1, 0, 1, 0)
932

933
    def test_json_plugin_skiponsetuptest(self):
934
        self.run_and_check('skiponsetup.py', exit_codes.AVOCADO_ALL_OK,
935
                           1, 0, 0, 1)
936

937
    def test_json_plugin_errortest(self):
938
        self.run_and_check('errortest.py', exit_codes.AVOCADO_TESTS_FAIL,
939
                           1, 1, 0, 0)
940

941 942 943 944 945 946 947 948
    def test_ugly_echo_cmd(self):
        if not os.path.exists("/bin/echo"):
            self.skipTest("Program /bin/echo does not exist")
        data = self.run_and_check('"/bin/echo -ne foo\\\\\\n\\\'\\\\\\"\\\\\\'
                                  'nbar/baz"', exit_codes.AVOCADO_ALL_OK, 1, 0,
                                  0, 0)
        # The executed test should be this
        self.assertEqual(data['tests'][0]['url'],
949
                         '1-/bin/echo -ne foo\\\\n\\\'\\"\\\\nbar/baz')
950 951
        # logdir name should escape special chars (/)
        self.assertEqual(os.path.basename(data['tests'][0]['logdir']),
952
                         '1-_bin_echo -ne foo\\\\n\\\'\\"\\\\nbar_baz')
953

954 955 956 957
    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(PluginsJSONTest, self).tearDown()

958 959
if __name__ == '__main__':
    unittest.main()