streamedinput_test.py 19.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
#!/usr/bin/env python
"""
Test that the Streamed Input works.

SUT:    Test code framework
Area:   Processing streams of data from subprocess
Class:  Functional
Type:   Unit test
"""

Charles Ferguson's avatar
Charles Ferguson committed
11 12 13
# Some tests just check that we don't crash.
# pylint: disable=no-self-use

14 15 16 17 18
import inspect
import os
import psutil
import sys
import time
19
import types
20 21 22 23 24
import unittest

import nose


25 26 27 28 29
if True:
    command_true = 'rem'
else:
    command_true = 'true'

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
streamedinput = None

# Ensure that the Coverage module is configured to instrument the package we
# care about (and to play nice with other people)
if os.environ.get('NOSE_WITH_COVERAGE') or '--with-coverage' in sys.argv:
    package = os.environ.get('NOSE_COVER_PACKAGE', '').split(',')
    package = set(pkg for pkg in package if pkg is not '')
    package.add('streamedinput')
    os.environ['NOSE_COVER_PACKAGE'] = ",".join(sorted(package))


class BaseStreamedInput(unittest.TestCase):

    def wait(self):
        """
        Insert a delay.

        This function is intended to be used by the ThreadedStreamedInput tests, to insert the necessary delay
        when we're running in threaded mode. In the normal mode, the callbacks happen whilst we're blocked,
        so there's no need to wait for anything.
        """
        pass


class Test01Basics(BaseStreamedInput):

    def test_000_import(self):
        global streamedinput
58 59 60 61 62 63 64 65 66
        try:
            import streamedinput.streamedinput as streamedinput  # pylint: disable=redefined-outer-name,relative-import,no-name-in-module
        except ImportError:
            import streamedinput  # pylint: disable=redefined-outer-name,relative-import

        self.assertIsInstance(streamedinput, types.ModuleType,
                              "'streamedinput' should have been imported as a module")
        self.assertTrue(hasattr(streamedinput, 'StreamedInput'),
                        "'streamedinput' should have a 'StreamedInput' object")
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

    def test_001_construct_array(self):
        _ = streamedinput.StreamedInput(['echo', 'foo'])

    def test_002_construct_string(self):
        _ = streamedinput.StreamedInput('echo foo')

    def test_003_construct_invalid(self):
        with self.assertRaises(ValueError):
            _ = streamedinput.StreamedInput(7)


class Test02StartStop(BaseStreamedInput):

    def test_001_start_stop(self):
82
        si = streamedinput.StreamedInput([command_true], shell=True)
83 84 85 86 87
        si.start()
        si.stop()

    def test_002_stop(self):
        # Stop is always safe.
88
        si = streamedinput.StreamedInput([command_true], shell=True)
89 90 91
        si.stop()

    def test_003_start_start(self):
92
        si = streamedinput.StreamedInput([command_true], shell=True)
93 94 95 96 97 98 99 100 101 102 103 104 105 106
        si.start()
        with self.assertRaises(streamedinput.StreamedInputCannotStartError):
            si.start()

    def test_004_unusable_command(self):
        # Ensures that we pass through the cleanup code without a proc being assigned
        si = streamedinput.StreamedInput([7])
        with self.assertRaises(Exception):
            si.start()


class Test10DataLength(BaseStreamedInput):

    def test_001_before_start(self):
107
        si = streamedinput.StreamedInput([command_true], shell=True)
108 109 110
        self.assertEqual(len(si), 0)

    def test_002_after_start_empty(self):
111
        si = streamedinput.StreamedInput([command_true], shell=True)
112 113 114 115
        si.start()
        self.assertEqual(len(si), 0)

    def test_003_after_start_1line(self):
116
        si = streamedinput.StreamedInput(['echo', 'foo'], shell=True)
117 118 119 120 121 122 123 124 125 126 127 128 129
        si.start()
        self.assertEqual(len(si), 1)

    def test_004_after_start_2lines(self):
        si = streamedinput.StreamedInput('echo foo && sleep 1 && echo bar', shell=True)
        si.start()
        self.wait()
        self.assertEqual(len(si), 2)


class Test20EOF(BaseStreamedInput):

    def test_001_before_start(self):
130
        si = streamedinput.StreamedInput([command_true])
131 132 133 134
        with self.assertRaises(streamedinput.StreamedInputNotStartedError):
            self.assertFalse(si.eof())

    def test_002_after_start_empty(self):
135
        si = streamedinput.StreamedInput([command_true])
136 137 138 139 140 141 142 143 144 145 146 147 148 149
        si.start()
        self.assertTrue(si.eof())

    def test_003_after_start_1line(self):
        si = streamedinput.StreamedInput(['echo', 'foo'])
        si.start()
        self.assertFalse(si.eof())
        si.read()
        self.assertTrue(si.eof())


class Test30Read(BaseStreamedInput):

    def test_001_before_start(self):
150
        si = streamedinput.StreamedInput([command_true])
151 152 153 154
        with self.assertRaises(streamedinput.StreamedInputNotStartedError):
            self.assertIsNone(si.read())

    def test_002_after_start_empty(self):
155
        si = streamedinput.StreamedInput([command_true])
156 157 158 159 160 161 162 163 164 165 166 167 168
        si.start()
        self.assertIsNone(si.read())

    def test_003_after_start_1line(self):
        si = streamedinput.StreamedInput(['echo', 'foo'])
        si.start()
        self.assertIsNotNone(si.read())
        self.assertIsNone(si.read())


class Test31Iterate(BaseStreamedInput):

    def test_001_before_start(self):
169
        si = streamedinput.StreamedInput([command_true])
170 171 172 173 174 175 176
        number_iterated = 0
        with self.assertRaises(streamedinput.StreamedInputNotStartedError):
            for _ in si:
                number_iterated += 1
        self.assertEqual(number_iterated, 0, "Should have iterated no items")

    def test_002_after_start_empty(self):
177
        si = streamedinput.StreamedInput([command_true])
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        si.start()
        number_iterated = 0
        for _ in si:
            number_iterated += 1
        self.assertEqual(number_iterated, 0, "Should have iterated no items")

    def test_003_after_start_1line(self):
        si = streamedinput.StreamedInput(['echo', 'foo'])
        si.start()
        number_iterated = 0
        for _ in si:
            number_iterated += 1
        self.assertEqual(number_iterated, 1, "Should have iterated 1 item")


class BaseDataFunction(BaseStreamedInput):

    def setUp(self):
        super(BaseDataFunction, self).setUp()
        self.data_calls = 0
        self.data_expects = []

    def data_func(self, data):
        """
        Simple data function which checks that the input it received is that which is expected.
        """
        self.assertLess(self.data_calls, len(self.data_expects),
                        "Only expected %s call(s), but got %r at call %s" %
                        (len(self.data_expects), data, self.data_calls))
        self.assertEqual(data, self.data_expects[self.data_calls],
                         "Expected call %s did not match" % (self.data_calls,))
        self.data_calls += 1


class Test40DataFunctionInput(BaseDataFunction):

    def test_001_called(self):
        self.data_expects = ['foo\n']

        si = streamedinput.StreamedInput(['echo', 'foo'], data_function=self.data_func)
        si.start()

        self.assertEqual(self.data_calls, 1)

    def test_002_with_shell(self):
        self.data_expects = ['foo\n']

        si = streamedinput.StreamedInput('echo foo', shell=True, data_function=self.data_func)
        si.start()

        self.assertEqual(self.data_calls, 1)

    def test_003_with_shell_lines(self):
        self.data_expects = ['foo\n', 'bar\n']

        si = streamedinput.StreamedInput('echo foo && sleep 1 && echo bar', shell=True, data_function=self.data_func)
        si.start()
        self.wait()

        self.assertEqual(self.data_calls, 2)


class Test41DataFunctionObjectAPIs(BaseDataFunction):

    def test_001_iter_fails(self):
        self.data_expects = ['foo\n']
        si = streamedinput.StreamedInput(['echo', 'foo'], data_function=self.data_func)
        si.start()

        with self.assertRaises(streamedinput.StreamedInputNotSimpleError):
            for _ in si:
Charles Ferguson's avatar
Charles Ferguson committed
249
                self.assertTrue(False, "There should not be items here")  # pylint: disable=redundant-unittest-assert
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

    def test_002_read_fails(self):
        self.data_expects = ['foo\n']
        si = streamedinput.StreamedInput(['echo', 'foo'], data_function=self.data_func)
        si.start()

        with self.assertRaises(streamedinput.StreamedInputNotSimpleError):
            _ = si.read()

    def test_003_len_fails(self):
        self.data_expects = ['foo\n']
        si = streamedinput.StreamedInput(['echo', 'foo'], data_function=self.data_func)
        si.start()

        with self.assertRaises(streamedinput.StreamedInputNotSimpleError):
            _ = len(si)


class Test42DataFunctionEOF(BaseDataFunction):

    def test_001_before_start(self):
        self.data_expects = []
272
        si = streamedinput.StreamedInput([command_true], data_function=self.data_func)
273 274 275 276 277
        with self.assertRaises(streamedinput.StreamedInputNotStartedError):
            self.assertFalse(si.eof())

    def test_002_after_start_empty(self):
        self.data_expects = []
278
        si = streamedinput.StreamedInput([command_true], data_function=self.data_func)
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        si.start()
        self.assertTrue(si.eof())

    def test_003_after_start_1line(self):
        self.data_expects = ['foo\n']
        si = streamedinput.StreamedInput('echo foo', shell=True, data_function=self.data_func)
        si.start()
        # All the data was already delivered, so we should be at the end.
        self.assertTrue(si.eof())


class BaseCompleteFunction(BaseStreamedInput):

    def setUp(self):
        super(BaseCompleteFunction, self).setUp()
        self.complete_expected = False
        self.complete_calls = 0

    def complete_func(self):
        """
        Simple complete function which checks that we were only called once.
        """
        self.assertTrue(self.complete_expected,
                        "The 'complete' function was not expected to be called.")
        self.complete_calls += 1
        self.assertEqual(self.complete_calls, 1,
                         "The 'complete' function should only have been called once.")

    def assertNoComplete(self):
        self.assertEqual(self.complete_calls, 0,
                         "The 'complete' function should not have been called.")

    def assertComplete(self):
        self.assertEqual(self.complete_calls, 1,
                         "The 'complete' function should have been called once.")


class Test50CompleteFunction(BaseCompleteFunction):

    def test_001_not_called_before_start(self):
319
        _ = streamedinput.StreamedInput([command_true], complete_function=self.complete_func)
320 321 322
        self.assertNoComplete()

    def test_002_called_after_start(self):
323
        si = streamedinput.StreamedInput([command_true], complete_function=self.complete_func)
324 325 326 327 328 329 330
        self.complete_expected = True
        si.start()
        self.wait()
        self.assertComplete()


class Test80Repr(BaseStreamedInput):
Charles Ferguson's avatar
Charles Ferguson committed
331
    called = None
332 333

    def test_001_before_start(self):
334
        si = streamedinput.StreamedInput([command_true])
335 336 337 338 339 340 341
        self.assertIn('started=False', repr(si))
        self.assertIn("stopped=n/a", repr(si))
        self.assertIn('shell=False', repr(si))
        self.assertIn("command=['true']", repr(si))
        self.assertIn("data_chunks=0", repr(si))

    def test_002_started(self):
342
        si = streamedinput.StreamedInput([command_true])
343 344 345 346 347 348 349 350
        si.start()
        self.assertIn('started=True', repr(si))
        self.assertIn("stopped=stopped", repr(si))
        self.assertIn('shell=False', repr(si))
        self.assertIn("command=['true']", repr(si))
        self.assertIn("data_chunks=0", repr(si))

    def test_003_with_datafunc(self):
Charles Ferguson's avatar
Charles Ferguson committed
351
        def dummy(_):
352 353
            pass

354
        si = streamedinput.StreamedInput([command_true], data_function=dummy)
355 356 357 358 359 360 361 362
        si.start()
        self.assertIn('started=True', repr(si))
        self.assertIn("stopped=stopped", repr(si))
        self.assertIn('shell=False', repr(si))
        self.assertIn("command=['true']", repr(si))
        self.assertNotIn("data_chunks=0", repr(si))

    def test_004_shell(self):
363
        si = streamedinput.StreamedInput([command_true], shell=True)
364 365 366 367 368 369 370 371 372 373
        si.start()
        self.assertIn('started=True', repr(si))
        self.assertIn("stopped=stopped", repr(si))
        self.assertIn('shell=True', repr(si))
        self.assertIn("command=['true']", repr(si))
        self.assertIn("data_chunks=0", repr(si))

    def test_005_running_state(self):
        self.called = False

Charles Ferguson's avatar
Charles Ferguson committed
374
        def test_func(_):
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
            self.assertIn('started=True', repr(si))
            self.assertIn("stopped=running", repr(si))
            self.called = True

        si = streamedinput.StreamedInput('echo foo && sleep 1', shell=True, data_function=test_func)
        si.start()
        self.wait()
        self.assertTrue(self.called, "The test function should have been called")
        self.assertIn('started=True', repr(si))
        self.assertIn("stopped=stopped", repr(si))

    def test_006_running_stop_requested(self):
        self.called = False

        def test_func(data):
            self.assertNotEqual(data, 'bar', "We should never receive the 'bar' line")
            self.assertIn('started=True', repr(si))
            self.assertIn("stopped=running", repr(si))
            si.stop()
            self.assertIn('started=True', repr(si))
            self.assertIn("stopped=requested", repr(si))
            self.called = True

        si = streamedinput.StreamedInput('echo foo && sleep 1 && echo bar', shell=True, data_function=test_func)
        si.start()
        self.assertTrue(self.called, "The test function should have been called")
        self.assertIn('started=True', repr(si))
        self.assertIn("stopped=stopped", repr(si))

    def test_007_running_eof_check(self):
        self.called = False

        def test_func(data):
            if data == 'foo\n':
                self.assertFalse(si.eof(), "We should NOT be at the end of the stream yet")
            elif data == 'bar\n':
                # Give the process a moment to actually exit
                # (it would be rare to call eof on the stream in this way)
                time.sleep(0.2)
                self.assertTrue(si.eof(), "We should be at the end of the stream")
            else:
Charles Ferguson's avatar
Charles Ferguson committed
416
                self.assertTrue(False, "Invalid data received") # pylint: disable=redundant-unittest-assert
417 418 419 420 421 422 423 424 425 426 427
            self.called = True

        si = streamedinput.StreamedInput('echo foo && sleep 1 && echo bar', shell=True, data_function=test_func)
        si.start()
        self.wait()
        self.assertTrue(self.called, "The test function should have been called")
        self.assertIn('started=True', repr(si))
        self.assertIn("stopped=stopped", repr(si))


class BaseThreadedInput(BaseStreamedInput):
428 429 430 431 432 433 434 435
    """
    Base class which replaces the implementation of StreamedInputClass as called,
    with the Threaded version. This allows us to check that the classes work without
    duplicating code.

    Special magic is needed to ensure that we only replace the calls within the
    test code with those to the threaded version.
    """
436 437 438 439 440 441 442 443 444 445 446 447

    def setUp(self):
        super(BaseThreadedInput, self).setUp()
        self.old_StreamedInputClass = streamedinput.StreamedInput

        def really_call_ThreadedStreamedInput(*args, **kwargs):
            # There are two ways we can be called:
            #   1. from this test code (which we want to replace with the threaded call)
            #   2. from elsewhere (which we want to pass through)
            frames = inspect.stack()
            try:
                caller = frames[1]
Charles Ferguson's avatar
Charles Ferguson committed
448 449
                # We'll check whether the name of the module we're in matches the
                # caller. If so, we're really inside this test code.
450
                if caller[0].f_globals['__name__'] == \
451
                   really_call_ThreadedStreamedInput.__globals__['__name__']:  # pylint: disable=no-member
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
                    # We're in this test code, so divert to the threaded call
                    return streamedinput.ThreadedStreamedInput(*args, **kwargs)
                else:
                    return self.old_StreamedInputClass(*args, **kwargs)
            finally:
                del frames

        streamedinput.StreamedInput = really_call_ThreadedStreamedInput

    def tearDown(self):
        super(BaseThreadedInput, self).tearDown()
        streamedinput.StreamedInput = self.old_StreamedInputClass


class TestThreaded01Basics(BaseThreadedInput, Test01Basics):
    pass


class TestThreaded02StartStop(BaseThreadedInput, Test02StartStop):
    pass


class TestThreaded10DataLength(BaseThreadedInput, Test10DataLength):

    def wait(self):
        time.sleep(1.2)


class TestThreaded20EOF(BaseThreadedInput, Test20EOF):
    pass


class TestThreaded30Read(BaseThreadedInput, Test30Read):
    pass


class TestThreaded31Iterate(BaseThreadedInput, Test31Iterate):
    pass


class TestThreaded40DataFunctionInput(BaseThreadedInput, Test40DataFunctionInput):

    def wait(self):
        time.sleep(1.2)


class TestThreaded41DataFunctionObjectAPIs(BaseThreadedInput, Test41DataFunctionObjectAPIs):
    pass


class TestThreaded42DataFunctionEOF(BaseThreadedInput, Test42DataFunctionEOF):
    pass


class TestThreaded80Repr(BaseThreadedInput, Test80Repr):

    def wait(self):
        time.sleep(1.2)


class TestThreaded90ThreadControl(BaseThreadedInput):

514 515 516
    def __init__(self, *args, **kwargs):
        super(TestThreaded90ThreadControl, self).__init__(*args, **kwargs)
        if sys.platform == 'darwin':
517
            self.cmd = ['netstat', '-i', '-w1']
518
        elif sys.platform.startswith('linux'):
519
            self.cmd = ['ping', '-c', '4', '127.0.0.1']
520 521 522 523 524 525 526 527 528
        else:
            raise NotImplementedError

        self.si = None

    def tearDown(self):
        self.si.stop()
        super(TestThreaded90ThreadControl, self).tearDown()

529
    def test_001_start_and_stop_long_process(self):
530
        self.si = streamedinput.StreamedInput(self.cmd)
531
        self.si.start()
532
        time.sleep(0.1)
533 534 535
        initial_datalen = len(self.si)
        time.sleep(1.2)
        second_datalen = len(self.si)
536
        self.assertGreater(second_datalen, initial_datalen, "We should have got more data by now")
537

538 539
        # Read all the data
        chunks = 0
540
        while self.si.read():
541 542
            chunks += 1
            self.assertLess(chunks, 20, "We should not have read this much data")
543 544
        self.assertFalse(self.si.eof(), "We shouldn't be at the end of the input yet")
        self.si.stop()
545 546 547 548

        time.sleep(0.1)

        chunks = 0
549
        while self.si.read():
550 551 552
            chunks += 1
            self.assertLess(chunks, 5, "We should not have read this much data")

553
        self.assertTrue(self.si.eof(), "We should now be at the end of the list, and the process should be gone")
554 555

    def test_002_context_handler_stops(self):
556
        with streamedinput.ThreadedStreamedInput(self.cmd) as self.si:
557 558
            test_process = psutil.Process(self.si.proc.pid)
            self.assertTrue(self.si.is_running(), "Process should be running")
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573

        # Wait a moment for the thread to terminate
        time.sleep(0.1)
        try:
            running = test_process.is_running()
            self.assertFalse(running, "The process should not be running now")
        finally:
            if test_process.is_running():
                test_process.terminate()


if __name__ == '__main__':
    __name__ = os.path.basename(sys.argv[0][:-3])  # pylint: disable=redefined-builtin
    env = os.environ
    env['NOSE_WITH_XUNIT'] = '1'
574
    env['NOSE_VERBOSE'] = '1'
575
    exit(nose.runmodule(env=env))