예제 #1
0
def test_unsubscribe_and_subscribe_again(nsproxy, socket_type):
    """
    Test resubscribing to topics after unsubscribing works fine.
    """
    server = run_agent('server', base=ServerNumbers)
    client = run_agent('client')

    addr = server.bind(socket_type, alias='pub', handler=append_received)
    client.set_attr(received=[])
    client.connect(addr, alias='sub', handler=append_received)

    # Establish a connection
    server.each(0.1, 'send', 'pub', 'connecting...', alias='tmp')
    assert wait_agent_attr(client, data='connecting...')
    server.stop_timer('tmp')

    # Subscribe to two topics
    client.unsubscribe('sub', '')
    client.subscribe('sub', handler={'negate': receive_negate,
                                     'normal': append_received})

    # Make server to start publishing messages
    server.each(0.1, 'publish')

    assert wait_agent_condition(client, match_tail, [-1, 2] * 4)

    # Unsubscribe from one topic
    client.unsubscribe('sub', 'negate')

    assert wait_agent_condition(client, match_tail, [2] * 8)

    # Subscribe again
    client.subscribe('sub', handler={'negate': receive_negate})

    assert wait_agent_condition(client, match_tail, [-1, 2] * 4)
예제 #2
0
def test_yield(nsproxy):
    """
    REQ-REP pattern using a handler that yields a value. This is useful in
    order to generate an early reply.
    """
    def reply_early(agent, message):
        yield message
        time.sleep(agent.delay)
        agent.delay = 'ok'

    delay = 1
    a0 = run_agent('a0')
    a0.set_attr(delay=delay)
    a1 = run_agent('a1')

    addr = a0.bind('REP', handler=reply_early)
    a1.connect(addr, alias='request')

    t0 = time.time()
    response = a1.send_recv('request', 'Working!')
    assert time.time() - t0 < delay / 2.
    assert response == 'Working!'
    assert a0.get_attr('delay') == delay
    # Sleep so that the replier has had time to update
    time.sleep(delay + 0.5)
    assert a0.get_attr('delay') == 'ok'
예제 #3
0
def test_resubscribe(nsproxy, socket_type):
    """
    After subscribing to the same topic with a different handler after a
    subscription to that topic was already made, we should override the
    original handler.

    Note that we will only override explicitly given topics (previous
    subscriptions of other topics will remain untouched).
    """
    server = run_agent('server', base=ServerNumbers)
    client = run_agent('client')

    addr = server.bind(socket_type, alias='pub', handler=append_received)
    client.set_attr(received=[])
    client.connect(addr, alias='sub', handler=append_received)

    # Establish a connection
    server.each(0.1, 'send', 'pub', 'connecting...', alias='tmp')
    assert wait_agent_attr(client, data='connecting...')
    server.stop_timer('tmp')

    # Subscribe to two topics
    client.unsubscribe('sub', '')
    client.subscribe('sub', handler={'negate': receive_negate,
                                     'normal': append_received})

    server.each(0.1, 'publish')

    assert wait_agent_condition(client, match_tail, [-1, 2] * 4)

    # Resubscribe, so as to store the 'normal' (2) messages negated
    client.subscribe('sub', handler={'normal': receive_negate})

    assert wait_agent_condition(client, match_tail, [-1, -2] * 4)
예제 #4
0
def test_agent_dies(nsproxy):
    """
    The function `agent_dies` should return `False` if the agent does not die
    after a timeout.
    """
    run_agent('a0')
    assert not agent_dies('a0', nsproxy, timeout=0.5)
def test_sync_pub_send_handlers(nsproxy, handler, check_function,
                                should_crash):
    """
    The handler for the requests MUST be specified in the `send` call.
    It can be specified in different ways: method, functions...
    """
    server = run_agent('server', base=ServerSyncPub)
    client = run_agent('client', base=ClientWithHandler)

    addr = server.addr('publish')

    # Use an alternative handler so as to guarantee connection is established
    client.connect(addr, alias='sub', handler='alternative_receive')
    server.each(0.01, 'publish')
    assert wait_agent_attr(client, name='alternative_received', length=2,
                           data='publication!')

    if should_crash:
        with pytest.raises(ValueError):
            client.send('sub', 'request!')
    else:
        client.send('sub', 'request!', handler=handler)
        assert wait_agent_attr(client, length=1)

        if check_function:
            # Check that the function was not stored as a method for the object
            with pytest.raises(AttributeError) as error:
                assert client.get_attr('append_received')
            assert 'object has no attribute' in str(error.value)
예제 #6
0
def test_subscribe(nsproxy, socket_type, subscribe_separately):
    """
    Test subscribing to various topics/handlers works fine.
    """
    server = run_agent('server', base=ServerNumbers)
    client = run_agent('client')

    addr = server.bind(socket_type, alias='pub', handler=append_received)
    client.set_attr(received=[])
    client.connect(addr, alias='sub', handler=append_received)

    # Establish a connection
    server.each(0.1, 'send', 'pub', 'connecting...', alias='tmp')
    assert wait_agent_attr(client, data='connecting...')
    server.stop_timer('tmp')

    # Subscribe to two topics. Client should only receive -1 and 2.
    client.unsubscribe('sub', '')
    if subscribe_separately:
        client.subscribe('sub', handler={'negate': receive_negate})
        client.subscribe('sub', handler={'normal': append_received})
    else:
        client.subscribe('sub', handler={'negate': receive_negate,
                                         'normal': append_received})

    server.each(0.1, 'publish')

    assert wait_agent_condition(client, match_tail, [-1, 2] * 4)
예제 #7
0
def async_client_server(server_handler=blocked_reply):
    server = run_agent('server', base=Server)
    client = run_agent('client', base=Client)

    addr = server.bind('ASYNC_REP', alias='replier', handler=server_handler)
    client.connect(addr, alias='async', handler=append_received)

    return (client, server)
예제 #8
0
def test_nameserver_proxy_shutdown_agents(nsproxy):
    """
    Shutdown agents registered in a name server from a name server proxy.
    """
    run_agent('Agent0', nsaddr=nsproxy.addr())
    run_agent('Agent1', nsaddr=nsproxy.addr())
    nsproxy.shutdown_agents()
    assert len(nsproxy.agents()) == 0
예제 #9
0
파일: test_proxy.py 프로젝트: Peque/osbrain
def setup_busy_worker(nsproxy):
    worker = run_agent('worker', base=BusyWorker)
    boss = run_agent('boss')
    boss.connect(worker.addr('pull'), alias='push')
    # Make worker busy for 2 seconds
    boss.send('push', 2)
    assert wait_agent_attr(worker, name='busy', value=True, timeout=.5)
    return worker
예제 #10
0
def test_nameserver_proxy_shutdown_with_agents():
    """
    Shutdown a name server from a name server proxy.
    """
    ns = run_nameserver()
    run_agent('Agent0', nsaddr=ns.addr())
    run_agent('Agent1', nsaddr=ns.addr())
    ns.shutdown()
예제 #11
0
파일: test_proxy.py 프로젝트: Peque/osbrain
def test_agent_proxy_wait_running_0_seconds(nsproxy):
    """
    Using `wait_for_running` on a proxy after initialization should block until
    the agent is running or time out.
    """
    run_agent('agent')

    proxy = Proxy('agent').wait_for_running(timeout=0)
    assert proxy.ping() == 'pong'
예제 #12
0
def test_run_agents_same_name(nsproxy):
    """
    Check that the user cannot create two agents with the same name. A
    RuntimeError should be raised.
    """
    run_agent('name')
    with pytest.raises(RuntimeError) as error:
        run_agent('name')
    assert 'name already registered' in str(error.value)
예제 #13
0
파일: test_proxy.py 프로젝트: Peque/osbrain
def test_agent_run_agent_safe_and_unsafe(nsproxy):
    """
    Using the `run_agent` function should allow us to set a `safe` attribute
    for the returned Proxy as well.
    """
    safe = run_agent('a0', safe=True)
    unsafe = run_agent('a1', safe=False)
    assert safe._safe
    assert not unsafe._safe
예제 #14
0
def test_nameserver_proxy_list(nsproxy):
    """
    Verify new agents get registered in the nameserver.
    """
    run_agent('a0', nsproxy.addr())
    run_agent('a1', nsproxy.addr())
    # List registered agents
    agent_list = nsproxy.list()
    assert 'a0' in agent_list
    assert 'a1' in agent_list
예제 #15
0
def test_lambda(nsproxy):
    """
    REQ-REP pattern using a lambda handler.
    """
    a0 = run_agent('a0')
    a1 = run_agent('a1')
    addr = a0.bind('REP', handler=lambda agent, message: 'x' + message)
    a1.connect(addr, alias='request')
    response = a1.send_recv('request', 'Hello world')
    assert response == 'xHello world'
예제 #16
0
def test_pushpull(nsproxy, serializer, message):
    """
    Simple push-pull pattern test, using different serializations.
    """
    a0 = run_agent('a0')
    a1 = run_agent('a1')
    a1.set_attr(received=None)
    addr = a1.bind('PULL', handler=set_received, serializer=serializer)
    a0.connect(addr, 'push')
    a0.send('push', message)
    assert wait_agent_attr(a1, name='received', value=message)
예제 #17
0
def test_nameserver_agent_address(nsproxy):
    """
    A name server proxy can be used to retrieve an agent's socket address as
    well, given the agent's alias and the socket's alias.
    """
    a0 = run_agent('a0')
    a1 = run_agent('a1')
    addr0 = a0.bind('PUB', alias='foo')
    addr1 = a1.bind('PUSH', alias='bar')
    assert nsproxy.addr('a0', 'foo') == addr0
    assert nsproxy.addr('a1', 'bar') == addr1
예제 #18
0
def test_nameserver_proxy_shutdown_raise_timeout():
    """
    A name server proxy should raise a TimeoutError if agents were not shutdown
    or killed before the set timeout.
    """
    ns = run_nameserver()
    run_agent('a0')
    with pytest.raises(TimeoutError) as error:
        ns.shutdown(timeout=0.)
    assert 'not shutdown after' in str(error.value)
    ns.shutdown()
예제 #19
0
def test_nameserver_environ(nsproxy):
    """
    When starting a nameserver, a environment variable should be set to ease
    the process of running new agents.
    """
    assert str(nsproxy.addr()) == os.environ.get('OSBRAIN_NAMESERVER_ADDRESS')
    run_agent('a0')
    run_agent('a1')
    # List registered agents
    agent_list = nsproxy.list()
    assert 'a0' in agent_list
    assert 'a1' in agent_list
예제 #20
0
def test_simple_pub_dict_handler(nsproxy, server):
    """
    SYNC_PUB should work just like a normal PUB. This test checks normal
    behavior when using multiple handlers (i.e.: filtering).

    When clients connect to a SYNC_PUB server, as long as they do not make
    requests, this communication pattern should behave exactly like a normal
    PUB-SUB pattern.
    """
    server = run_agent('server', base=server)
    both = run_agent('both', base=Client)
    positive = run_agent('positive', base=Client)
    bytestopic = run_agent('bytestopic', base=Client)

    # Connect clients
    addr = server.addr('publish')
    addr_both = both.connect(addr, handler={'positive': append_received,
                                            'negative': append_received})
    addr_positive = positive.connect(addr,
                                     handler={'positive': append_received})
    addr_bytestopic = bytestopic.connect(addr,
                                         handler={b'\xeb': append_received})
    assert addr_both == addr.twin()
    assert addr_positive == addr.twin()
    assert addr_bytestopic == addr.twin()

    # Publish from server
    server.each(0, 'publish_str')

    # Wait for clients to receive some data
    n = 10
    assert wait_agent_attr(both, length=n)
    assert wait_agent_attr(positive, length=n)
    assert wait_agent_attr(bytestopic, length=n)

    # both
    received = [int(x) for x in both.get_attr('received')]
    assert len(received) >= n
    for i in range(1, len(received)):
        if received[i] > 0:
            assert received[i - 1] == 1 - received[i]
        else:
            assert received[i - 1] == -received[i]

    # positive
    received = [int(x) for x in positive.get_attr('received')]
    assert len(received) >= n
    assert received == list(range(received[0], received[-1] + 1))

    # bytestopic
    received = bytestopic.get_attr('received')
    assert len(received) >= n
    assert all(x == 'bytes...' for x in received)
예제 #21
0
def test_unsubscribe_various(nsproxy, socket_type):
    """
    Test that unsubscribing from various topics works fine.

    The server will be publishing zeroes through two topics quickly, and
    ones through a single topic slowly.

    A subscriber will subscribe to all numbers, and then unsubscribe from the
    topics related to the zeroes, therefore receiving three (or more) ones in
    a row.
    """
    def check_sum_three(agent):
        """
        Check whether the last three received numbers sum to three.

        For this test in particular, the last three numbers should be one,
        received through the 'one' topic.
        """
        return sum(agent.received[-3:]) == 3

    def publish_zeroes(agent):
        agent.send('pub', 0, topic='zero')
        agent.send('pub', 0, topic='other_zero')

    def publish_one(agent):
        agent.send('pub', 1, topic='one')

    # Set up the agents
    server = run_agent('server')
    client = run_agent('client', base=Client)

    addr = server.bind(socket_type, alias='pub', handler=append_received)
    client.connect(addr, alias='sub', handler={'zero': append_received,
                                               'other_zero': append_received,
                                               'one': append_received})

    # Make sure the connection is established
    server.each(0.1, 'send', 'pub', 'connecting...', topic='zero', alias='tmp')
    assert wait_agent_attr(client, data='connecting...')
    server.stop_timer('tmp')

    # Wait until client receives some numbers
    client.set_attr(received=[])
    server.each(0.1, publish_zeroes)
    server.each(0.2, publish_one)
    assert wait_agent_attr(client, length=5)
    assert not client.execute_as_method(check_sum_three)

    # Unsubscribe from zeroes numbers (receiving only ones)
    client.unsubscribe('sub', ('zero', 'other_zero'))

    assert wait_agent_condition(client, check_sum_three)
예제 #22
0
파일: test_proxy.py 프로젝트: Peque/osbrain
def test_agent_proxy_initialization_timeout(nsproxy):
    """
    An agent proxy should raise a TimeoutError at initialization if the agent
    is not ready after a number of seconds.
    """
    class InitTimeoutProxy(Proxy):
        def ping(self):
            time.sleep(0.1)
            raise TimeoutError()

    run_agent('foo')
    with pytest.raises(TimeoutError):
        InitTimeoutProxy('foo', timeout=1.)
예제 #23
0
def test_nameserverprocess_shutdown():
    """
    Name server shutdown can be called directly from the name server process.
    """
    nameserver = random_nameserver_process()
    run_agent('a0')
    run_agent('a1')
    while not len(nameserver.agents()) == 2:
        continue
    assert 'a0' in nameserver.agents()
    assert 'a1' in nameserver.agents()
    nameserver.shutdown()
    assert not nameserver.is_alive()
예제 #24
0
def test_reqrep(nsproxy, serializer, message, response):
    """
    Simple request-reply pattern between two agents with different
    serializations.
    """
    def rep_handler(agent, message):
        return response

    a0 = run_agent('a0')
    a1 = run_agent('a1')
    addr = a0.bind('REP', 'reply', rep_handler, serializer=serializer)
    a1.connect(addr, 'request')
    assert a1.send_recv('request', message) == response
예제 #25
0
def test_pubsub(nsproxy, serializer, message):
    """
    Simple publisher-subscriber pattern test with different serializations.
    """
    a0 = run_agent('a0')
    a1 = run_agent('a1')
    a1.set_attr(received=None)
    addr = a0.bind('PUB', alias='pub', serializer=serializer)
    a1.connect(addr, handler=set_received)
    while not a1.get_attr('received'):
        a0.send('pub', message)
        time.sleep(0.1)
    assert a1.get_attr('received') == message
예제 #26
0
def test_return(nsproxy):
    """
    REQ-REP pattern using a handler that returns a value.
    """
    def rep_handler(agent, message):
        return message

    a0 = run_agent('a0')
    a1 = run_agent('a1')
    addr = a0.bind('REP', handler=rep_handler)
    a1.connect(addr, alias='request')
    response = a1.send_recv('request', 'Hello world')
    assert response == 'Hello world'
예제 #27
0
파일: test_proxy.py 프로젝트: Peque/osbrain
def test_agent_proxy_remote_exceptions(nsproxy):
    """
    Remote exceptions on method executions should be raised locally by the
    proxy with information on what did go wrong remotely.
    """
    a0 = run_agent('a0')
    a1 = run_agent('a1')
    with pytest.raises(TypeError) as error:
        a0.addr('asdf', 'qwer', 'foo', 'bar')
    assert 'positional arguments but 5 were given' in str(error.value)
    with pytest.raises(RuntimeError) as error:
        a1.raise_exception()
    assert 'User raised an exception' in str(error.value)
예제 #28
0
def test_unsubscribe(nsproxy, socket_type):
    """
    Test that unsubscribing from topics works fine.

    The server will be publishing the natural numbers, in ascending order,
    starting at one. Odd numbers will be sent with `odd` topic and even
    numbers with `even` topic.

    A subscriber will subscribe to all numbers, and then it will unsubscribe
    from the odd numbers.

    Two non consecutive numbers must be received consecutively at that point,
    since they both will be even.
    """
    def check_non_consecutive(agent):
        """
        Check whether the last two received numbers are non-consecutive.
        """
        return agent.received[-1] - agent.received[-2] != 1

    def publish(agent):
        assert agent.count % 2 == 1
        agent.send('pub', agent.count, topic='odd')
        agent.send('pub', agent.count + 1, topic='even')
        agent.count += 2

    # Set up the agents
    server = run_agent('server')
    client = run_agent('client', base=Client)

    server.set_attr(count=1)
    addr = server.bind(socket_type, alias='pub', handler=append_received)
    client.connect(addr, alias='sub', handler={'odd': append_received,
                                               'even': append_received})

    # Make sure the connection is established
    server.each(0.1, 'send', 'pub', 'connecting...', topic='odd', alias='tmp')
    assert wait_agent_attr(client, data='connecting...')
    server.stop_timer('tmp')

    # Wait until client receives some numbers
    client.set_attr(received=[])
    server.each(0.1, publish)
    assert wait_agent_attr(client, length=5)
    assert not client.execute_as_method(check_non_consecutive)

    # Unsubscribe from odd numbers (receiving only even numbers)
    client.unsubscribe('sub', 'odd')

    assert wait_agent_condition(client, check_non_consecutive)
    assert client.get_attr('received')[-1] % 2 == 0
예제 #29
0
def test_nameserver_proxy_shutdown_with_many_agents():
    """
    Shutdown a name server from a name server proxy when there are many agents
    registered in the name server (make sure proxies do not saturate the name
    server on shutdown).

    The shutdown process is given a long timeout to avoid raising exceptions.
    """
    import Pyro4
    Pyro4.config.THREADPOOL_SIZE = 4
    ns = run_nameserver()
    for i in range(20):
        run_agent('Agent%s' % i)
    ns.shutdown(timeout=60)
예제 #30
0
def test_wait(nsproxy):
    """
    Asynchronous request-reply pattern maximum wait.

    When a client makes a request, it can also set a maximum wait time and
    a function to be executed in case the message is not received after that
    period.
    """
    server = run_agent('server', base=ServerLate)
    client = run_agent('client', base=Client)
    logger = run_logger('logger')
    client.set_logger(logger)
    sync_agent_logger(client, logger)

    # Connect clients
    server_addr = server.addr('publish')
    client.connect(server_addr, alias='sub', handler=append_received)

    # Publish from server
    server.each(0, 'publish')

    # Wait for client to receive some data
    n = 10
    assert wait_agent_attr(client, length=n)

    # Response received in time
    fast = 0
    client.send('sub', fast, handler=append_received, wait=0.5)
    time.sleep(0.2)
    assert server.get_attr('received') == [fast]
    assert 'x' + str(fast) in client.get_attr('received')

    # Response not received in time
    slow = 1
    client.send('sub', slow, handler=append_received, wait=0.1)
    assert logger_received(logger,
                           log_name='log_history_warning',
                           message='not receive req',
                           timeout=0.5)
    assert server.get_attr('received') == [fast, slow]
    assert 'x' + str(slow) not in client.get_attr('received')

    # Response not received in time with error handler
    slow = 1
    client.send('sub', slow, handler=append_received, wait=0.1,
                on_error=on_error)
    assert wait_agent_attr(client, name='error_log', length=1, timeout=0.5)
    assert server.get_attr('received') == [fast, slow]
    assert 'x' + str(slow) not in client.get_attr('received')
예제 #31
0
def test_agent_proxy_safe_and_unsafe_property(monkeypatch, nsproxy):
    """
    Using the safe/unsafe property from a proxy should allow us to
    override the environment global configuration.
    """
    run_agent('foo')
    # Safe environment
    monkeypatch.setitem(osbrain.config, 'SAFE', True)
    proxy = Proxy('foo')
    assert proxy._safe
    assert proxy.safe._safe
    assert not proxy.unsafe._safe
    # Unsafe environment
    monkeypatch.setitem(osbrain.config, 'SAFE', False)
    proxy = Proxy('foo')
    assert not proxy._safe
    assert proxy.safe._safe
    assert not proxy.unsafe._safe
예제 #32
0
def test_agent_proxy_safe_and_unsafe_parameter(monkeypatch, nsproxy):
    """
    Using the safe/unsafe parameter when initializing a proxy should allow
    us to override the environment global configuration.
    """
    run_agent('foo')
    # Safe environment
    monkeypatch.setitem(osbrain.config, 'SAFE', True)
    proxy = Proxy('foo')
    assert proxy._safe
    proxy = Proxy('foo', safe=False)
    assert not proxy._safe
    # Unsafe environment
    monkeypatch.setitem(osbrain.config, 'SAFE', False)
    proxy = Proxy('foo')
    assert not proxy._safe
    proxy = Proxy('foo', safe=True)
    assert proxy._safe
예제 #33
0
def test_close_linger(nsproxy, linger, sleep_time, should_receive):
    """
    Test closing a socket with a linger value passed as parameter.
    """
    class AgentTest(Agent):
        def on_init(self):
            self.received = []

    puller = run_agent('puller', base=AgentTest)
    pusher = run_agent('pusher', base=AgentTest)

    address = puller.bind('PULL',
                          alias='pull',
                          handler=append_received,
                          transport='tcp')

    pusher.connect(address, alias='push')

    # Make sure connection is well established
    pusher.send('push', 'ping')
    assert wait_agent_attr(puller, data='ping', timeout=1)

    # Shutdown the puller and restart it without binding
    puller.shutdown()
    assert agent_dies('puller', nsproxy)
    puller = run_agent('puller', base=AgentTest)

    # Push a new message, which should block during linger period
    pusher.send('push', 'foo')
    pusher.close(alias='push', linger=linger)

    # After this timeout, depending on linger value, 'foo' will no longer be
    # on queue to be sent
    time.sleep(sleep_time)

    # Bind to receive the message (if still in queue)
    puller.bind('PULL',
                alias='pull',
                handler=append_received,
                addr=address.address,
                transport='tcp')

    assert should_receive == wait_agent_attr(puller, data='foo', timeout=1)
예제 #34
0
def test_async_rep_handler_exists(nsproxy):
    """
    When binding an ASYNC_REP socket without a handler, an exception must be
    thrown, letting the user know that a handler must be specified.
    """
    server = run_agent('server', base=Agent)

    with pytest.raises(ValueError) as error:
        server.bind('ASYNC_REP', alias='should_crash')
    assert 'This socket requires a handler!' in str(error.value)
예제 #35
0
def test_agent_bind_transport_global(nsproxy):
    """
    Test global default transport.
    """
    # Default transport
    agent = run_agent('a0')
    address = agent.bind('PUSH')
    assert address.transport == 'ipc'

    # Changing default global transport
    osbrain.config['TRANSPORT'] = 'tcp'
    agent = run_agent('a1')
    address = agent.bind('PUSH')
    assert address.transport == 'tcp'

    osbrain.config['TRANSPORT'] = 'ipc'
    agent = run_agent('a2')
    address = agent.bind('PUSH')
    assert address.transport == 'ipc'
예제 #36
0
 def do_connect(self, extra):
     """Connect to the robot."""
     self.ns = run_nameserver()
     self.proxy = run_agent("proxy", base=Proxy)
     if extra == "bluetooth":
         self.proxy.after(0, "setup", interface_class=BluetoothInterface)
     elif extra == "serial":
         self.proxy.after(0, "setup", interface_class=SerialInterface)
     else:
         print('Unsupported connection "{}"'.format(extra))
예제 #37
0
    def create_air_agents(self):
        # Room Air Agent
        self.room_air = run_agent('room_air', base=AirConditioner)
        self.agents.append(self.room_air)
        self.room_air.set_attr(
            active_area=[ROOM_X1, ROOM_Y1, ROOM_X2, ROOM_Y2],
            element_tag='room')

        # self.connect(self.room_air.addr('to_gui'))
        self.room_air.connect(self.addr('from_gui'))

        # Bedroom Air Agent
        self.bedroom_air = run_agent('bedroom_air', base=AirConditioner)
        self.agents.append(self.bedroom_air)
        self.bedroom_air.set_attr(
            active_area=[BEDROOM_X1, BEDROOM_Y1, BEDROOM_X2, BEDROOM_Y2],
            element_tag='bedroom')

        # self.connect(self.bedroom_air.addr('to_gui'))
        self.bedroom_air.connect(self.addr('from_gui'))
예제 #38
0
def agent_start(start_date, stop_date, most_common_countries, country_code,
                root_codes, correlated_countries):
    # System deployment
    ns = run_nameserver()
    gd_agent = run_agent('GDELT',
                         base=AgentGDELT,
                         attributes=dict(
                             date1=start_date,
                             date2=stop_date,
                             country_code=country_code,
                             root_codes=root_codes,
                             countries_amount=most_common_countries,
                             correlated_countries=correlated_countries))
    if gd_agent.get_len_comm_countries() == 0:
        print("There are no countries with given interaction")
        sys.exit()

    first_layer_agents = FirstLayerAgent.create_first_layer_agents(gd_agent)
    second_layer_agents = SecondLayerAgents.create_second_layer_agents(
        root_codes, first_layer_agents)

    # System configuration
    FirstLayerAgent.connect_agents(first_layer_agents, gd_agent)
    SecondLayerAgents.connect_agents(second_layer_agents, first_layer_agents)

    # Send messages
    gd_agent.publish_gdelt()
    FirstLayerAgent.publish_events(first_layer_agents, country_code)

    # Plot informations
    all_combinations_count = sum(list(range(1, len(correlated_countries))))
    stats_agents = [
        a for a in second_layer_agents
        if a.get_attr('topic')[0] == AGENT_DATA['stats_agents_id']
    ]
    trends_agents = [
        a for a in stats_agents if 'trend_line' in a.get_attr('topic')
    ]
    diplomacy_agents = [
        a for a in stats_agents if 'diplomacy' in a.get_attr('topic')
    ]
    cameo_agents = [
        a for a in second_layer_agents
        if a.get_attr('topic')[0] != AGENT_DATA['stats_agents_id']
    ]
    SecondLayerAgents.plot_countries_interaction(cameo_agents, root_codes,
                                                 country_code, start_date,
                                                 stop_date)
    SecondLayerAgents.calculate_correlations_and_find_allies(
        diplomacy_agents, all_combinations_count, correlated_countries)
    SecondLayerAgents.plot_trends(trends_agents, correlated_countries)

    # Server shutdown
    ns.shutdown()
예제 #39
0
def test_agent_close_ipc_socket_nameserver_shutdown():
    """
    Check that the socket is closed and the socket file removed after the name
    server is shut down.
    """
    ns = run_nameserver()
    agent = run_agent('agent')
    addr = agent.bind('PUSH', 'main')
    ns.shutdown()

    assert wait_condition(addr.address.exists, negate=True)
예제 #40
0
def test_agent_close_ipc_socket_agent_kill(nsproxy):
    """
    Check that the socket is closed and the socket file removed after the agent
    is killed.
    """
    agent = run_agent('name')
    address = agent.bind('PUSH')
    agent.oneway.kill()

    assert agent_dies('name', nsproxy)
    assert wait_condition(address.address.exists, negate=True)
예제 #41
0
def test_timer_each_stop_alias(nsproxy):
    """
    Test a timer executed periodically and stopped by an alias.
    """
    def tick(agent):
        agent.send('push', agent.count)
        agent.count += 1

    sender = run_agent('sender')
    receiver = run_agent('receiver')
    addr = sender.bind('PUSH', alias='push')
    receiver.connect(addr, handler=set_received)

    sender.set_attr(count=0)
    sender.each(0.1, tick, alias='aliased_timer')
    time.sleep(1)
    assert abs(receiver.get_attr('received') - 10) <= 1
    sender.stop_timer('aliased_timer')
    time.sleep(1)
    assert abs(receiver.get_attr('received') - 10) <= 1
    assert 'aliased_timer' not in sender.list_timers()
예제 #42
0
 def __init__(self, alias):
     self.agent = run_agent(alias)
     self.name = alias
     self.weight = random.randint(0, 20)
     self.type = 'sensor'
     self.posX = random.randint(1, 30)
     self.posY = random.randint(1, 30)
     self.agentList.append({
         'name': alias,
         'posX': self.posX,
         'posY': self.posY
     })
예제 #43
0
def test_agent_loopback(nsproxy):
    """
    An agent should always have a _loopback_safe inproc socket.
    """
    a0 = run_agent('a0')
    assert a0.addr('_loopback_safe') == AgentAddress(
        transport='inproc',
        address='_loopback_safe',
        kind='REP',
        role='server',
        serializer='pickle',
    )
예제 #44
0
def test_async_rep_send_handler_types(nsproxy, handler, check_function):
    """
    We should be able to make requests even if we do not specify a handler
    on the `connect` call, as long as we specify it on the `send` call.
    """
    server = run_agent('server', base=ServerAsyncRep)
    client = run_agent('client', base=ClientWithHandler)

    addr = server.addr('publish')

    # Connect without a handler
    client.connect(addr, alias='sub')

    client.send('sub', 'request!', handler=handler)
    assert wait_agent_attr(client, length=1)

    if check_function:
        # Check that the function was not stored as a method for the object
        with pytest.raises(AttributeError) as error:
            assert client.get_attr('append_received')
        assert 'object has no attribute' in str(error.value)
예제 #45
0
def test_simple_pub_single_handler(nsproxy, server):
    """
    SYNC_PUB should work just like a normal PUB. This test checks normal
    behavior when using a single handler (i.e.: no filtering).

    When clients connect to a SYNC_PUB server, as long as they do not make
    requests, this communication pattern should behave exactly like a normal
    PUB-SUB pattern.
    """
    server = run_agent('server', base=server)
    alltopics = run_agent('alltopics', base=Client)

    # Connect clients
    addr = server.addr('publish')
    addr_alltopics = alltopics.connect(addr, handler=receive)
    assert addr_alltopics == addr.twin()

    # Publish from server
    server.each(0, 'publish_str')

    # Wait for clients to receive some data
    N = 10
    assert wait_agent_attr(alltopics, length=N)

    # alltopics
    received = [
        int(x) for x in alltopics.get_attr('received') if x != 'bytes...'
    ]
    assert len(received) >= N
    for i in range(2, len(received)):
        if received[i] > 0:
            if received[i - 1] == 'bytes...':
                assert received[i - 2] == 1 - received[i]
            else:
                assert received[i - 1] == 1 - received[i]
        else:
            if received[i - 1] == 'bytes...':
                assert received[i - 2] == -received[i]
            else:
                assert received[i - 1] == -received[i]