示例#1
0
    def test_add_callback(self):
        """
        Test the add_callback function
        """
        loop = EventLoop.current()

        def the_callback():
            pass

        loop.add_callback(the_callback)
        self.assertEqual(loop.callbacks[0], (the_callback, None))

        # when we're testing the dictionary method of creating a deadline we need to drop the microseconds
        # component when we're comparing since they'll never be the same
        one_second_from_now = datetime.datetime.now() + datetime.timedelta(seconds=1)
        loop.add_callback(the_callback, {'seconds': 1})
        self.assertEqual(loop.callbacks[1][0], the_callback)
        self.assertEqual(loop.callbacks[1][1].replace(microsecond=0), one_second_from_now.replace(microsecond=0))

        one_minute_from_now = datetime.datetime.now() + datetime.timedelta(minutes=1)
        loop.add_callback(the_callback, one_minute_from_now)
        self.assertEqual(loop.callbacks[2], (the_callback, one_minute_from_now))

        loop.add_shutdown_callback(the_callback)
        self.assertEqual(loop.shutdown_callbacks, [the_callback])
示例#2
0
    def test_init(self, pygame):
        loop = EventLoop.current()
        manager = PlaybackManager(loop, self.sounds_dir)

        self.assertEqual(manager.stages, self.stages)

        for stage in self.stages:
            command = manager.commands[stage]
            self.assertEqual(len(command.sound_files), 3)
示例#3
0
    def test_init(self, pygame):
        loop = EventLoop.current()
        manager = PlaybackManager(loop, self.sounds_dir)

        self.assertEqual(manager.stages, self.stages)

        for stage in self.stages:
            command = manager.commands[stage]
            self.assertEqual(len(command.sound_files), 3)
示例#4
0
    def test_start(self, pygame, command_wait):
        """
        Test processing of the commands
        """
        loop = EventLoop.current()

        manager = MagicMock()
        manager.loop = loop
        commands = PlaybackCommands(manager, self.stage)
        commands.testing = True
        commands.test_wait_durations = []

        # we've mocked out the command_wait method of PlaybackCommands
        # use a side_effect to make it work again, but ignore durations
        def test_command_wait(duration):
            commands.test_wait_durations.append(int(duration))
            commands.next_command()
        command_wait.side_effect = test_command_wait

        # start command processing, this is a coroutine and requires that the loop run
        commands.start()

        # run the loop, stopping it in 0.25 seconds
        loop.add_callback(loop.stop, {'seconds': 0.25})
        loop.start()

        # make sure things worked as expected
        pygame.mixer.Sound.assert_has_calls([
            call(commands.sound_file),
            call().play(-1, fade_ms=5000),
            call().fadeout(5000),
            call().set_volume(0.9),

            call(commands.swap_sound_file),
            call().play(-1, fade_ms=5000),
            call().fadeout(5000)
        ])

        # command_wait was mocked out and we logged the durations
        self.assertEqual(commands.test_wait_durations, [5, 5, 5, 0, 5])

        # finish the swap
        original_sound_file = copy.copy(commands.sound_file)
        self.assertTrue(original_sound_file in commands.sounds)
        self.assertNotEqual(commands.swap_sound_file, None)
        self.assertTrue(commands.swapping)
        self.assertFalse(commands.swapped)

        commands._complete_swap()

        self.assertFalse(original_sound_file in commands.sounds)
        self.assertEqual(commands.swap_sound_file, None)
        self.assertFalse(commands.swapping)
        self.assertTrue(commands.swapped)
示例#5
0
    def test_start(self, pygame, command_wait):
        """
        Test processing of the commands
        """
        loop = EventLoop.current()

        manager = MagicMock()
        manager.loop = loop
        commands = PlaybackCommands(manager, self.stage)
        commands.testing = True
        commands.test_wait_durations = []

        # we've mocked out the command_wait method of PlaybackCommands
        # use a side_effect to make it work again, but ignore durations
        def test_command_wait(duration):
            commands.test_wait_durations.append(int(duration))
            commands.next_command()

        command_wait.side_effect = test_command_wait

        # start command processing, this is a coroutine and requires that the loop run
        commands.start()

        # run the loop, stopping it in 0.25 seconds
        loop.add_callback(loop.stop, {'seconds': 0.25})
        loop.start()

        # make sure things worked as expected
        pygame.mixer.Sound.assert_has_calls([
            call(commands.sound_file),
            call().play(-1, fade_ms=5000),
            call().fadeout(5000),
            call().set_volume(0.9),
            call(commands.swap_sound_file),
            call().play(-1, fade_ms=5000),
            call().fadeout(5000)
        ])

        # command_wait was mocked out and we logged the durations
        self.assertEqual(commands.test_wait_durations, [5, 5, 5, 0, 5])

        # finish the swap
        original_sound_file = copy.copy(commands.sound_file)
        self.assertTrue(original_sound_file in commands.sounds)
        self.assertNotEqual(commands.swap_sound_file, None)
        self.assertTrue(commands.swapping)
        self.assertFalse(commands.swapped)

        commands._complete_swap()

        self.assertFalse(original_sound_file in commands.sounds)
        self.assertEqual(commands.swap_sound_file, None)
        self.assertFalse(commands.swapping)
        self.assertTrue(commands.swapped)
示例#6
0
    def test_coroutine(self):
        """
        Test the @coroutine decorator
        """
        loop = EventLoop.current()

        # run the coroutine
        self.add_coroutine_results()

        # since the loop isn't running the results will still be empty
        self.assertEqual(self.coroutine_results, [])

        # run the loop, stopping it in 0.25 seconds
        loop.add_callback(loop.stop, {'seconds': 0.25})
        loop.start()

        # our results will now be populated
        self.assertEqual(self.coroutine_results, [1, 2, 3])
示例#7
0
文件: cli.py 项目: borgstrom/slumber
def main():
    """
    Main entry point
    """
    parser = argparse.ArgumentParser(description='Slumber - Sleep better')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Turn on debug logging and USR1 breakpoint')
    parser.add_argument(
        '--sounds',
        '-s',
        required=True,
        help=
        'The directory to load sounds from.  It should be organized into numbered directories.'
    )
    parser.add_argument('--timer',
                        '-t',
                        required=False,
                        type=int,
                        help='Set a sleep timer in minutes.')
    args = parser.parse_args()

    if args.debug:
        log_format = '%(asctime)s %(name)-10s %(levelname)-8s %(message)s'
        log_level = logging.DEBUG
    else:
        log_format = '%(asctime)s %(message)s'
        log_level = logging.INFO

    logging.basicConfig(level=log_level, format=log_format)

    log = logging.getLogger('main')

    log.info('Slumber - Starting...')

    if args.debug:
        import code, traceback

        def debug_interrupt(sig, frame):
            debug_locals = dict(frame=frame)
            debug_locals.update(frame.f_globals)
            debug_locals.update(frame.f_locals)

            console = code.InteractiveConsole(locals=debug_locals)
            console.interact("\n".join([
                "Signal %d received.  Entering Python shell." % sig, "-" * 50,
                "Traceback:", ''.join(traceback.format_stack(frame))
            ]))

        signal.signal(signal.SIGUSR1, debug_interrupt)

    # set a sleep timer in minutes, minimalist
    if args.timer:
        # use SystemExit since that's already caught for debug
        def stexit(sig, frame):
            raise SystemExit

        signal.signal(signal.SIGALRM, stexit)
        signal.alarm(args.timer * 60)

    loop = EventLoop.current()

    # create the playback manager
    playback_manager = PlaybackManager(loop, args.sounds)
    loop.add_callback(playback_manager.start)

    # run our event loop, this will block
    try:
        loop.start()
    except (KeyboardInterrupt, SystemExit):
        loop.stop()
示例#8
0
文件: cli.py 项目: borgstrom/slumber
def main():
    """
    Main entry point
    """
    parser = argparse.ArgumentParser(description='Slumber - Sleep better')
    parser.add_argument('--debug', action='store_true',
                        help='Turn on debug logging and USR1 breakpoint')
    parser.add_argument('--sounds', '-s', required=True,
                        help='The directory to load sounds from.  It should be organized into numbered directories.')
    parser.add_argument('--timer', '-t', required=False, type=int,
                        help='Set a sleep timer in minutes.')
    args = parser.parse_args()

    if args.debug:
        log_format = '%(asctime)s %(name)-10s %(levelname)-8s %(message)s'
        log_level = logging.DEBUG
    else:
        log_format = '%(asctime)s %(message)s'
        log_level = logging.INFO

    logging.basicConfig(level=log_level, format=log_format)

    log = logging.getLogger('main')

    log.info('Slumber - Starting...')

    if args.debug:
        import code, traceback 

        def debug_interrupt(sig, frame):
            debug_locals = dict(frame=frame)
            debug_locals.update(frame.f_globals)
            debug_locals.update(frame.f_locals)

            console = code.InteractiveConsole(locals=debug_locals)
            console.interact("\n".join([
                "Signal %d received.  Entering Python shell." % sig,
                "-" * 50,
                "Traceback:",
                ''.join(traceback.format_stack(frame))
            ]))

        signal.signal(signal.SIGUSR1, debug_interrupt)

    # set a sleep timer in minutes, minimalist
    if args.timer:
        # use SystemExit since that's already caught for debug
        def stexit(sig, frame):
          raise SystemExit
        signal.signal(signal.SIGALRM, stexit)
        signal.alarm(args.timer * 60)

    loop = EventLoop.current()

    # create the playback manager
    playback_manager = PlaybackManager(loop, args.sounds)
    loop.add_callback(playback_manager.start)

    # run our event loop, this will block
    try:
        loop.start()
    except (KeyboardInterrupt, SystemExit):
        loop.stop()