Пример #1
0
def test_file(tmpdir):
    logfile = str(tmpdir.ensure("debug.log"))
    stderr = open(logfile, "w+")

    app = App()
    debugger = Debugger(file=stderr)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events

    e = Event()
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    debugger._events = False
    assert not debugger._events

    e = Event()
    app.fire(e)

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()
Пример #2
0
def test_IgnoreChannels():
    app = App()
    stderr = StringIO()
    debugger = Debugger(file=stderr)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events
    debugger.IgnoreChannels.extend([("*", "test")])

    e = Event()
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    e = test()
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()
Пример #3
0
def test_IgnoreChannels():
    app = App()
    stderr = StringIO()
    debugger = Debugger(file=stderr)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events
    debugger.IgnoreChannels.extend([("*", "test")])

    e = Event()
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    e = test()
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()
Пример #4
0
    def testIgnoreEvents(self):
        """Test Debugger's IgnoreEvents

        Test Debugger's IgnoreEvents
        """

        manager = Manager()
        debugger = Debugger()
        foo = Foo()

        manager += debugger
        manager += foo

        debugger.IgnoreEvents.extend([Test])
        debugger.events = True

        e = Event()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, str(e))

        sys.stderr.seek(0)
        sys.stderr.truncate()

        e = Test()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, "")

        sys.stderr.seek(0)
        sys.stderr.truncate()
        foo.unregister()
Пример #5
0
    def testDebugger(self):
        """Test Debugger

        Test Debugger
        """

        manager = Manager()
        debugger = Debugger()
        foo = Foo()

        manager += debugger
        manager += foo

        debugger.events = True
        e = Event()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, str(e))

        sys.stderr.seek(0)
        sys.stderr.truncate()

        debugger.events = False
        e = Event()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, "")

        sys.stderr.seek(0)
        sys.stderr.truncate()
Пример #6
0
def test_file(tmpdir):
    logfile = str(tmpdir.ensure("debug.log"))
    stderr = open(logfile, "w+")

    app = App()
    debugger = Debugger(file=stderr)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events

    e = Event()
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    debugger._events = False
    assert not debugger._events

    e = Event()
    app.fire(e)

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()
Пример #7
0
def test_main():
    app = App()
    stderr = StringIO()
    debugger = Debugger(file=stderr)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events

    e = Event()
    app.fire(e)
    app.flush()
    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    debugger._events = False
    assert not debugger._events

    e = Event()
    app.fire(e)

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()
Пример #8
0
    def testIgnoreEvents(self):
        """Test Debugger's IgnoreEvents

        Test Debugger's IgnoreEvents
        """

        manager = Manager()
        debugger = Debugger()
        foo = Foo()

        manager += debugger
        manager += foo

        debugger.IgnoreEvents.extend([Test])
        debugger.events = True

        e = Event()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, str(e))

        sys.stderr.seek(0)
        sys.stderr.truncate()

        e = Test()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, "")

        sys.stderr.seek(0)
        sys.stderr.truncate()
        foo.unregister()
Пример #9
0
def test_main():
    app = App()
    stderr = StringIO()
    debugger = Debugger(file=stderr)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events

    e = Event()
    app.fire(e)
    app.flush()
    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    debugger._events = False
    assert not debugger._events

    e = Event()
    app.fire(e)

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()
Пример #10
0
    def testDebugger(self):
        """Test Debugger

        Test Debugger
        """

        manager = Manager()
        debugger = Debugger()
        foo = Foo()

        manager += debugger
        manager += foo

        debugger.events = True
        e = Event()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, str(e))

        sys.stderr.seek(0)
        sys.stderr.truncate()

        debugger.events = False
        e = Event()
        manager.send(e, "foo")
        sys.stderr.seek(0)
        s = sys.stderr.read().strip()
        self.assertEquals(s, "")

        sys.stderr.seek(0)
        sys.stderr.truncate()
Пример #11
0
def test_Logger_debug():
    app = App()
    logger = Logger()
    debugger = Debugger(logger=logger)
    debugger.register(app)
    while app:
        app.flush()

    e = Event()
    app.fire(e)
    app.flush()

    assert logger.debug_msg == repr(e)
Пример #12
0
def test_Logger_debug():
    app = App()
    logger = Logger()
    debugger = Debugger(logger=logger)
    debugger.register(app)
    while app:
        app.flush()

    e = Event()
    app.fire(e)
    app.flush()

    assert logger.debug_msg == repr(e)
Пример #13
0
def test_exceptions():
    app = App()
    stderr = StringIO()
    debugger = Debugger(file=stderr)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events
    assert debugger._errors

    e = test(raiseException=True)
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    app.flush()
    stderr.seek(0)
    s = stderr.read().strip()
    assert s.startswith("<exception[*]")
    stderr.seek(0)
    stderr.truncate()

    debugger._events = False
    debugger._errors = False

    assert not debugger._events
    assert not debugger._errors

    e = test(raiseException=True)
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()

    app.flush()
    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
Пример #14
0
def test_Logger_error():
    app = App()
    logger = Logger()
    debugger = Debugger(logger=logger)
    debugger.register(app)
    while app:
        app.flush()

    e = test(raiseException=True)
    app.fire(e)
    while app:
        app.flush()

    assert logger.error_msg.startswith("ERROR <handler[*][test] (App.test)> (")
Пример #15
0
def test_Logger_error():
    app = App()
    logger = Logger()
    debugger = Debugger(logger=logger)
    debugger.register(app)
    while app:
        app.flush()

    e = test(raiseException=True)
    app.fire(e)
    while app:
        app.flush()

    assert logger.error_msg.startswith("ERROR <handler[*.test] (App.test)> (")
Пример #16
0
def webapp(request):
    webapp = WebApp()

    if hasattr(request.module, "application"):
        from circuits.web.wsgi import Gateway
        application = getattr(request.module, "application")
        Gateway({"/": application}).register(webapp)

    Root = getattr(request.module, "Root", None)
    if Root is not None:
        Root().register(webapp)

    if request.config.option.verbose:
        Debugger().register(webapp)

    waiter = pytest.WaitEvent(webapp, "ready")
    webapp.start()
    assert waiter.wait()

    def finalizer():
        webapp.fire(close(), webapp.server)
        webapp.stop()

    request.addfinalizer(finalizer)

    return webapp
Пример #17
0
    def init(self, args):
        self.args = args

        self.logger = getLogger(__name__)
        if args.debug:
            self += Debugger(channel=self.channel,
                             IgnoreEvents=['_read', '_write', 'ping'])
            self += stdin
            #self += Debugger(logger=self.logger, channel=self.channel)

        self.buffers = defaultdict(bytes)

        self.nicks = {}
        self.users = {}
        self.channels = {}
        if ':' in args.bind:
            address, port = args.bind.split(':', 1)
            port = int(port)
        else:
            address, port = args.bind, 6667

        self.transport = TCPServer(bind=(address, port),
                                   channel=self.channel).register(self)

        self.protocol = IRC(
            channel=self.channel,
            getBuffer=self.buffers.__getitem__,
            updateBuffer=self.buffers.__setitem__).register(self)
Пример #18
0
    def __init__(self, engine_cls, debug=False, force_snmp_init=True):
        super(RedisStateHandler, self).__init__()

        self._state_tracker = EngineStateTracker()

        logger.info("Initializing websocket server...")
        # set up a web socket server
        socket_conf = {
            "host": os.environ.get("SIMENGINE_SOCKET_HOST"),
            "port": int(os.environ.get("SIMENGINE_SOCKET_PORT")),
        }
        self._server = Server(
            (socket_conf["host"], socket_conf["port"])).register(self)

        # Worker(process=False).register(self)
        Static().register(self._server)
        Logger().register(self._server)

        if debug:
            Debugger(events=False).register(self)
        self._ws = WebSocket().register(self._server)

        WebSocketsDispatcher("/simengine").register(self._server)

        logger.info("Initializing engine...")
        self._engine = engine_cls(
            force_snmp_init=force_snmp_init).register(self)
        self._engine.subscribe_tracker(self._ws)
        self._engine.subscribe_tracker(self._state_tracker)

        # Use redis pub/sub communication
        logger.info("Initializing redis connection...")
        self._redis_store = redis.StrictRedis(host="localhost", port=6379)
Пример #19
0
def construct_graph(args):
    """Preliminary HFOS application Launcher"""

    app = Core(args)

    setup_root(app)

    if args['debug']:
        from circuits import Debugger
        hfoslog("Starting circuits debugger", lvl=warn, emitter='GRAPH')
        dbg = Debugger().register(app)
        dbg.IgnoreEvents.extend(["read", "_read", "write", "_write",
                                 "stream_success", "stream_complete",
                                 "stream"])

    hfoslog("Beginning graph assembly.", emitter='GRAPH')

    if args['drawgraph']:
        from circuits.tools import graph

        graph(app)

    if args['opengui']:
        import webbrowser
        # TODO: Fix up that url:
        webbrowser.open("http://%s:%i/" % (args['host'], args['port']))

    hfoslog("Graph assembly done.", emitter='GRAPH')

    return app
Пример #20
0
    def init(self, args, opts):
        """Initialize our ``ChatServer`` Component.

        This uses the convenience ``init`` method which is called after the
        component is properly constructed and initialized and passed the
        same args and kwargs that were passed during construction.
        """

        self.args = args
        self.opts = opts

        self.clients = {}

        if opts.debug:
            Debugger().register(self)

        if ":" in opts.bind:
            address, port = opts.bind.split(":")
            port = int(port)
        else:
            address, port = opts.bind, 8000

        bind = (address, port)

        TCPServer(bind).register(self)
Пример #21
0
    def init(self, args, logger=None):
        self.args = args
        self.logger = logger or getLogger(__name__)

        self.buffers = defaultdict(bytes)

        self.nicks = {}
        self.users = {}
        self.channels = {}

        Debugger(events=args.debug, logger=self.logger).register(self)

        if ":" in args.bind:
            address, port = args.bind.split(":")
            port = int(port)
        else:
            address, port = args.bind, 6667

        bind = (address, port)

        self.transport = TCPServer(
            bind,
            channel=self.channel
        ).register(self)

        self.protocol = IRC(
            channel=self.channel,
            getBuffer=self.buffers.__getitem__,
            updateBuffer=self.buffers.__setitem__
        ).register(self)
Пример #22
0
def main():
    opts, args = parse_options()

    if ":" in opts.bind:
        address, port = opts.bind.split(":")
        port = int(port)
    else:
        address, port = opts.bind, 8000

    if args:
        x = args[0].split(":")
        if len(x) > 1:
            nodes = [(x[0], int(x[1]))]
        else:
            nodes = [(x[0], 8000)]
    else:
        nodes = []

    manager = Manager()

    debugger = Debugger()
    debugger.IgnoreEvents.extend(["Read", "Write"])
    manager += debugger

    bridge = Bridge(port, address=address, nodes=nodes)
    manager += bridge

    manager.run()
Пример #23
0
    def start(self):
        # Create a new circuits Manager
        #ignevents = [Update, MouseMove]
        ignchannames = [
            'update', 'started', 'on_mousemove', 'on_mousedrag', 'on_keydown',
            'on_input', 'on_mouseclick', 'on_entityupdated', 'on_exit',
            'on_keyup', 'on_login', 'on_inboundnetwork', 'on_genericmessage',
            'on_scene', 'on_entity_visuals_modified', 'on_logout',
            'on_worldstreamready', 'on_sceneadded'
        ]
        ignchannels = [('*', n) for n in ignchannames]

        # Note: instantiating Manager with debugger causes severe lag when running as a true windowed app (no console), so instantiate without debugger
        # Fix attempt: give the circuits Debugger a logger which uses Naali logging system, instead of the default which writes to sys.stderr
        # Todo: if the default stdout is hidden, the py stdout should be changed
        # to something that shows e.g. in console, so prints from scripts show
        # (people commonly use those for debugging so they should show somewhere)
        d = Debugger(IgnoreChannels=ignchannels,
                     logger=NaaliLogger())  #IgnoreEvents = ignored)
        self.m = Manager() + d
        #self.m = Manager()

        #or __all__ in pymodules __init__ ? (i.e. import pymodules would do that)
        if self.firstrun:
            import autoload
            self.firstrun = False
        else:  #reload may cause something strange sometimes, so better not do it always in production use, is just a dev tool.
            #print "reloading autoload"
            import autoload
            autoload = reload(autoload)
        #print "Autoload module:", autoload
        autoload.load(self.m)

        self.m.push(Started(
            self.m, None))  #webserver requires this now, temporarily XXX
Пример #24
0
def webapp(request, manager, watcher):
    webapp = WebApp().register(manager)
    assert watcher.wait("ready")

    if hasattr(request.module, "application"):
        from circuits.web.wsgi import Gateway
        application = getattr(request.module, "application")
        Gateway({"/": application}).register(webapp)
        assert watcher.wait("registered")

    Root = getattr(request.module, "Root", None)
    if Root is not None:
        Root().register(webapp)
        assert watcher.wait("registered")

    if request.config.option.verbose:
        Debugger().register(webapp)
        assert watcher.wait("registered")

    def finalizer():
        webapp.fire(close())
        assert watcher.wait("closed")

        webapp.unregister()
        assert watcher.wait("unregistered")

    request.addfinalizer(finalizer)

    return webapp
Пример #25
0
    def after_properties_set(self):
        """ Run by Spring Python after all the JMS container's properties have
        been set.
        """

        for idx in range(self.concurrent_listeners):
            # Create as many Circuits managers as there are JMS listeners.
            manager = Manager()
            manager.start()

            # A pool of handler threads for each listener.
            handlers_pool = ThreadPool(self.handlers_per_listener)

            # Each manager gets assigned its own listener.
            listener = WebSphereMQListener()

            # Assign the listener and a debugger component to the manager.
            manager += listener
            manager += Debugger(logger=self.logger)

            listener.factory = self.factory
            listener.destination = self.destination
            listener.handler = self.handler
            listener.handlers_pool = handlers_pool
            listener.wait_interval = self.wait_interval
            listener.start()
Пример #26
0
def construct_graph(ctx, name, instance, args):
    """Preliminary Isomer application Launcher"""

    app = Core(name, instance, **args)

    # TODO: This should probably be read-only
    BaseMeta.context = ctx

    setup_root(app)

    if args["debug"]:
        from circuits import Debugger

        isolog("Starting circuits debugger", lvl=warn, emitter="GRAPH")
        dbg = Debugger().register(app)
        # TODO: Make these configurable from modules, navdata is _very_ noisy
        # but should not be listed _here_
        dbg.IgnoreEvents.extend([
            "read",
            "_read",
            "write",
            "_write",
            "stream_success",
            "stream_complete",
            "serial_packet",
            "raw_data",
            "stream",
            "navdatapush",
            "referenceframe",
            "updateposition",
            "updatesubscriptions",
            "generatevesseldata",
            "generatenavdata",
            "sensordata",
            "reset_flood_offenders",
            "reset_flood_counters",  # Flood counters
            "task_success",
            "task_done",  # Thread completion
            "keepalive",  # IRC Gateway
            "peek",  # AVIO and others
            "joystickchange",  # AVIO
        ])

    isolog("Beginning graph assembly.", emitter="GRAPH")

    if args["draw_graph"]:
        from circuits.tools import graph

        graph(app)

    if args["open_gui"]:
        import webbrowser

        # TODO: Fix up that url:
        webbrowser.open("http://%s:%i/" % (args["host"], args["port"]))

    isolog("Graph assembly done.", emitter="GRAPH")

    return app
Пример #27
0
 def add_logger(self):
     self += Logger(self.arguments.logfile,
                    logformat=self.logformat,
                    channel=self.channel)
     if self.arguments.loglevel:
         self += Debugger()
     else:
         self += FallBackExceptionHandler()
Пример #28
0
 def init(self):
     self.channel = 'sender'
     self.tick_count = 0
     print('Sender Initialized')
     Debugger().register(self)
     Receiver('a').register(self)
     Receiver('b').register(self)
     Ticker(self).register(self)
Пример #29
0
 def __call__(self, args):
     if args.enable and not self._commander.debugger:
         self._commander.debugger = Debugger()
         self._commander.debugger.register(self._commander)
         return 'Enabled debugger'
     elif self._commander.debugger:
         self._commander.debugger.unregister()
         return 'Disabled debugger'
Пример #30
0
def main():
    opts, args = parse_options()

    bind = parse_bind(opts.bind)

    if opts.validate:
        application = (Application() + Root())
        app = validator(application)

        httpd = make_server(bind[0], bind[1], app)
        httpd.serve_forever()

        raise SystemExit(0)

    manager = Manager()

    opts.debug and Debugger().register(manager)

    Poller = select_poller(opts.poller.lower())
    Poller().register(manager)

    if opts.server.lower() == "base":
        BaseServer(bind).register(manager)
        HelloWorld().register(manager)
    else:
        Server(bind).register(manager)
        Root().register(manager)

    docroot = os.getcwd() if not args else args[0]

    Static(docroot=docroot, dirlisting=True).register(manager)

    opts.passwd and Authentication(passwd=opts.passwd).register(manager)

    opts.logging and Logger().register(manager)

    if opts.profile and hotshot:
        profiler = hotshot.Profile(".profile")
        profiler.start()

    if opts.debug:
        print(graph(manager, name="circuits.web"))
        print()
        print(inspect(manager))

    for i in range(opts.jobs):
        manager.start(process=True)

    manager.run()

    if opts.profile and hotshot:
        profiler.stop()
        profiler.close()

        stats = hotshot.stats.load(".profile")
        stats.strip_dirs()
        stats.sort_stats("time", "calls")
        stats.print_stats(20)
Пример #31
0
    def init(self, bind=None, verbose=False):
        self.bind = bind or ("0.0.0.0", 53)

        if verbose:
            Debugger().register(self)

        self.transport = UDPServer(self.bind).register(self)
        self.protocol = DNS().register(self)
        self.dummy = Dummy().register(self)
Пример #32
0
def main():
    bot = IRCBot(host="irc.sudo-rmrf.net", port=6667, channel="#bot", nick="testbot")
    h = Help("Intro", "Outro").register(bot)
    UserTracker().register(bot)
    LastMessage().register(bot)
    Stats().register(bot)
    IRCCommand('boop', lambda user, chan, args: bot.fire(sendmessage(chan, user.nick + ': bop'))).register(bot)
    d = Debugger().register(bot)
    bot.run()
Пример #33
0
def construct_graph(dodebug=False, dograph=False, dogui=False):
    """Preliminary HFOS application Launcher"""

    if dodebug:
        from circuits import Debugger

    server = Server(("0.0.0.0", 8055))
    setup_root(server)
    Logger().register(server)
    hfoslog("[HFOS] Beginning graph assembly.")

    HFDebugger().register(server)

    app = App().register(server)

    # Machineroom().register(app)

    navdata = NavData().register(server)
    NMEAParser('localhost', 2222).register(navdata)

    TileCache().register(server)
    Static("/", docroot="/var/lib/hfos/static").register(server)
    WebSocketsDispatcher("/websocket").register(server)

    clientmanager = ClientManager().register(server)
    AlertManager().register(clientmanager)
    SchemaManager().register(clientmanager)
    ObjectManager().register(clientmanager)
    Authenticator().register(clientmanager)
    Chat().register(clientmanager)
    MapViewManager().register(clientmanager)
    LayerManager().register(clientmanager)
    RemoteControlManager().register(clientmanager)
    WebDemo().register(clientmanager)
    Wiki().register(clientmanager)
    # CameraManager().register(clientmanager)

    # Logger().register(server)

    if dodebug:
        dbg = Debugger()
        dbg.IgnoreEvents.extend(["write", "_write", "streamsuccess"])
        # dbg.register(lm)

    if dograph:
        from circuits.tools import graph

        graph(server)

    if dogui:
        import webbrowser

        webbrowser.open("http://127.0.0.1:8055")

    hfoslog("[HFOS] Graph assembly done.")

    return server
Пример #34
0
    def init(self, args):
        if args.debug:
            Debugger().register(self)

        bind = parse_bind(args.bind)

        DockerRPCServer(bind, args.url).register(self)
        DockerEventManager(self, args.url).start()
        EventBroadcaster(*bind).register(self)
Пример #35
0
def main():
    opts, args = parse_options()

    # Configure and "run" the System.
    app = Telnet(*args, **opts.__dict__)
    if opts.verbose:
        from circuits import Debugger
        Debugger().register(app)
    stdin.register(app)
    app.run()
Пример #36
0
        def __init__(self):
            Manager.__init__(self)

            self += GtkDriver()
            self += Debugger()

            self.server = BaseServer(9999)

            self.server += wsgi.Gateway(dummy_app)

            self += self.server
Пример #37
0
    def init(self, args, opts):
        if opts.debug:
            Debugger().register(self)

        if ":" in opts.bind:
            address, port = opts.bind.split(":")
            port = int(port)
        else:
            address, port = opts.bind, 8000

        self.node = Node(port=port, server_ip=address).register(self)
Пример #38
0
    def init(self, server, port, query, verbose=False):
        self.server = server
        self.port = int(port)
        self.query = query

        if verbose:
            Debugger().register(self)

        self.transport = UDPClient(0).register(self)
        self.protocol = DNS().register(self)
        self.dummy = Dummy().register(self)
Пример #39
0
def test_filename(tmpdir):
    if "__pypy__" in sys.modules:
        pytest.skip("Broken on pypy")

    logfile = str(tmpdir.ensure("debug.log"))
    stderr = open(logfile, "r+")

    app = App()
    debugger = Debugger(file=logfile)
    debugger.register(app)
    while app:
        app.flush()
    stderr.seek(0)
    stderr.truncate()

    assert debugger._events

    e = Event()
    app.fire(e)
    app.flush()

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == str(e)
    stderr.seek(0)
    stderr.truncate()

    debugger._events = False
    assert not debugger._events

    e = Event()
    app.fire(e)

    stderr.seek(0)
    s = stderr.read().strip()
    assert s == ""
    stderr.seek(0)
    stderr.truncate()