def test_run(entries):
    test.assertPublish('t1',
                       'owrtwifi/status/mac-01-02-03-04-05/lastseen/epoch',
                       1576164173,
                       assertSubscribe={'device/device1/connected': ''},
                       assertEventsTopic='device/device1/connected',
                       assertEvents={'connected': {
                           'value': True
                       }})
    test.assertPublish(
        't2',
        'owrtwifi/status/mac-0A-0B-0C-0D-0E/lastseen/iso8601',
        '2019-12-12T16:22:53+0100',
        assertSubscribe={'device/device2/detected': ''},
        assertEventsTopic='device/device2/detected',
        assertEvents={'connected': {
            'value': True,
            'temporary': True
        }})
    # Test disconnection by timeout (connection_time)
    test.assertx('t3',
                 assertSubscribe={'device/device1/disconnected': ''},
                 assertEventsTopic='device/device1/disconnected',
                 assertEvents={'connected': {
                     'value': False
                 }},
                 timeoutms=6000)
    # Test "momentary_flood_time"
    test.assertPublish(
        't4',
        'owrtwifi/status/mac-0A-0B-0C-0D-0E/lastseen/iso8601',
        '2019-12-12T16:22:53+0100',
        assertSubscribeNotReceive={'device/device2/detected': ''})
def test_init():
  test.add_node_config({
    "listen_all_events": True,
    "entries": [
      { "module": "scripting" },
      {
        "caption": "Device",
        "device": "test",
        "...": "...",
      },
    ]
  })
      
  # ADVANCED: test a topic is publish during node initialization (before test_run)
  test.assertx('init', assertSubscribe = { 'device/toggle/get': '' }, wait = False)
Exemple #3
0
def test_run(entries):
  test.assertx('t1', assertSubscribe = {'device/device1/connected': ''}, assertEventsTopic = 'device/device1/connected', assertEvents = {'connected': {'value': True }}, wait = False)
  entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '01:02:03:04:05')
  test.waitRunning()
  test.assertx('t2', assertSubscribe = {'device/device2/detected': ''}, assertEventsTopic = 'device/device2/detected', assertEvents = {'connected': {'value': True, 'temporary': True }}, wait = False)
  entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '0A:0B:0C:0D:0E')
  test.waitRunning()
  # Test disconnection by timeout (connection_time)
  test.assertx('t3', assertSubscribe = {'device/device1/disconnected': ''}, assertEventsTopic = 'device/device1/disconnected', assertEvents = {'connected': {'value': False }}, timeoutms = 6000)
  # Test "momentary_flood_time"
  test.assertx('t4', assertSubscribeNotReceive = {'device/device2/detected': ''}, wait = False)
  entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '0A:0B:0C:0D:0E')
  test.waitRunning()
Exemple #4
0
def test_run(entries):
  test.assertx('t1', assertSubscribe = {'device/test-rf-1/detected': ''}, assertEventsTopic = 'device/test-rf-1/detected', assertEvents = {'connected': {'value': True, 'temporary': True }, 'input': {'value': 1, 'temporary': True }}, wait = False)
  entries['rf_listener@TEST'].module.rf_rx_callback(entries['rf_listener@TEST'], { "rx_code": "1234567", "rx_pulselength": "0", "rx_proto": "P" })
  test.waitRunning()
  test.assertx('t2', assertSubscribeNotReceive = [ 'device/test-rf-1/detected', 'device/test-rf-2/detected' ], wait = False)
  entries['rf_listener@TEST'].module.rf_rx_callback(entries['rf_listener@TEST'], { "rx_code": "1234566", "rx_pulselength": "0", "rx_proto": "P" })
  test.waitRunning()
  test.assertx('t3', assertSubscribe = {'device/test-rf-2/detected': 'port2'}, assertEventsTopic = 'device/test-rf-2/detected', assertEvents = {'connected': { 'value': True, 'temporary': True, 'port': 'port2' }, 'input': {'value': 1, 'temporary': True, 'port': 'port2'}}, wait = False)
  entries['rf_listener@TEST'].module.rf_rx_callback(entries['rf_listener@TEST'], { "rx_code": "1234569", "rx_pulselength": "0", "rx_proto": "P" })
  test.waitRunning()
def test_run(entries):
    test.assertx('t1',
                 assertSubscribe={
                     'device/device1/connected': {
                         'mac_address': '01:02:03:04:05:06'
                     }
                 },
                 assertEventsTopic='device/device1/connected',
                 assertEvents={
                     'connected': {
                         'value': True,
                         'ip_address': None,
                         'mac_address': '01:02:03:04:05:06'
                     }
                 },
                 wait=False)
    entries['net_sniffer_iw@TEST'].module._iwevent_process_line(
        entries['net_sniffer_iw@TEST'], 'new station 01:02:03:04:05:06')
    test.waitRunning()
    test.assertx('t2',
                 assertSubscribe={
                     'device/device2/detected': {
                         'mac_address': '0A:0B:0C:0D:0E:0F'
                     }
                 },
                 assertEventsTopic='device/device2/detected',
                 assertEvents={
                     'connected': {
                         'value': True,
                         'temporary': True,
                         'ip_address': None,
                         'mac_address': '0A:0B:0C:0D:0E:0F'
                     }
                 },
                 wait=False)
    entries['net_sniffer_iw@TEST'].module._iwevent_process_line(
        entries['net_sniffer_iw@TEST'], 'new station 0A:0B:0C:0D:0E:0F')
    test.waitRunning()
    # Test disconnection by timeout (connection_time)
    test.assertx('t3',
                 assertSubscribe={'device/device1/disconnected': ''},
                 assertEventsTopic='device/device1/disconnected',
                 assertEvents={
                     'connected': {
                         'value': False,
                         'ip_address': None,
                         'mac_address': '01:02:03:04:05:06'
                     }
                 },
                 timeoutms=5000)
    # Test "momentary_flood_time"
    test.assertx('t4',
                 assertSubscribeNotReceive={'device/device2/detected': ''},
                 wait=False)
    entries['net_sniffer_iw@TEST'].module._iwevent_process_line(
        entries['net_sniffer_iw@TEST'], 'new station 0A:0B:0C:0D:0E:0F')
    test.waitRunning()

    x = entries['net_sniffer_iw@TEST'].module._arp_process_line(
        "192.168.1.199    0x1         0x0         01:02:03:04:05:06     *        br-lan"
    )
    test.assertx('t5', assertEq=[(x, ['01:02:03:04:05:06', '192.168.1.199'])])
    env = {'arp_list': {x[0]: x[1]}}

    test.assertx('t6',
                 assertSubscribe={
                     'device/device1/connected': {
                         'mac_address': '01:02:03:04:05:06',
                         'ip_address': '192.168.1.199'
                     }
                 },
                 assertEventsTopic='device/device1/connected',
                 assertEvents={
                     'connected': {
                         'value': True,
                         'ip_address': '192.168.1.199',
                         'mac_address': '01:02:03:04:05:06'
                     }
                 },
                 wait=False)
    entries['net_sniffer_iw@TEST'].module.mac_address_detected(
        entries['net_sniffer_iw@TEST'], env, '01:02:03:04:05:06')
    test.waitRunning()
    test.assertx('t7',
                 assertSubscribe={
                     'device/device1/disconnected': {
                         'mac_address': '01:02:03:04:05:06'
                     }
                 },
                 assertEventsTopic='device/device1/disconnected',
                 assertEvents={
                     'connected': {
                         'value': False,
                         'ip_address': '192.168.1.199',
                         'mac_address': '01:02:03:04:05:06'
                     }
                 },
                 wait=False)
    entries['net_sniffer_iw@TEST'].module.mac_address_detected(
        entries['net_sniffer_iw@TEST'],
        env,
        '01:02:03:04:05:06',
        disconnected=True)
    test.waitRunning()
def test_run(entries):
    #print(utils.strftime(system.time()))

    test.assertx("check1-idle",
                 assertSubscribe={
                     'scheduler/status': {
                         "enabled": True,
                         "time": (),
                         "timer_to": 0,
                         "groups": {
                             "groupname": {
                                 "enabled": True,
                                 "timer_to": 0
                             },
                         },
                         "jobs": {
                             "7e78a032ef642f62": {
                                 "run_cron": "*/10 * * * *",
                                 "do": ["item1.action(params['value']='1')"],
                                 "enabled": True,
                                 "max_delay": 60,
                                 "last_run": 0,
                                 "next_run": (),
                                 "timer_to": 0
                             },
                             "testsched": {
                                 "entry_id": "item1@TEST",
                                 "run_interval": 86400,
                                 "do": [".action(params['value']='2')"],
                                 "enabled": True,
                                 "max_delay": 0,
                                 "last_run": 0,
                                 "next_run": (),
                                 "timer_to": 0
                             },
                             "groupname.6abc8cf88f7957a5": {
                                 "group": "groupname",
                                 "entry_id": "item1@TEST",
                                 "run_cron": "0 0 */7 * *",
                                 "do": [".action(params[\'value\']=\'3\')"],
                                 "enabled": True,
                                 "max_delay": 60,
                                 "last_run": 0,
                                 "next_run": (),
                                 "timer_to": 0
                             }
                         }
                     }
                 },
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    #entries['scheduler@TEST'].module.run(entries['scheduler@TEST'])
    test.waitRunning()

    system.time_offset(600)
    test.assertx("check2-run",
                 assertSubscribe={'item/item1/action': '1'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    system.time_offset(10)
    test.assertx("check3-idle",
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    # test max_delay: too much time waited, job should NOT be executed
    system.time_offset(660)
    test.assertx("check4-idle",
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    system.time_offset(530)
    test.assertx("check5-run",
                 assertSubscribe={'item/item1/action': '1'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    test.assertAction("check6-disable",
                      'scheduler',
                      'output-set', {
                          'value': 0,
                          'timer_to': '20m'
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': False,
                              'target': '',
                              'timer_to': '20m'
                          },
                          'scheduler/result': {
                              'enabled': False,
                              'target': '*',
                              'timer_to': ('d', system.time() + 1200)
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 0,
                              'port': '',
                              'timer_to': ('d', system.time() + 1200)
                          }
                      })

    system.time_offset(600)
    test.assertx("check7-idle",
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    test.waitRunning()
    """
  test.assertAction("check8-enable", 'scheduler', 'output-set', {'value': 1}, 
    assertSubscribe = { 'scheduler/set': { 'enabled': True, 'target': '', 'timer_to': 0 }, 'scheduler/result': { 'enabled': True, 'target': '*', 'timer_to': 0}}, 
    assertEventsTopic = 'scheduler/result', assertEvents = { 'output': {'value': 1, 'port': '', 'timer_to': 0}})
  """

    system.time_offset(600)
    test.assertx("check9-run",
                 assertSubscribe={'item/item1/action': '1'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    test.assertAction("check10-disable",
                      'scheduler',
                      'output-set', {
                          'value': 0,
                          'port': '7e78a032ef642f62',
                          'timer_to': 1200
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': False,
                              'target': '7e78a032ef642f62',
                              'timer_to': 1200
                          },
                          'scheduler/result': {
                              'enabled': False,
                              'target': '7e78a032ef642f62',
                              'timer_to': ('d', system.time() + 1200)
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 0,
                              'port': '7e78a032ef642f62',
                              'timer_to': ('d', system.time() + 1200)
                          }
                      })

    system.time_offset(600)
    test.assertx("check11-idle",
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    test.waitRunning()
    """
  test.assertAction("check12-enable", 'scheduler', 'output-set', {'value': 1, 'port': '7e78a032ef642f62'}, 
    assertSubscribe = { 'scheduler/set': { 'enabled': True, 'target': '7e78a032ef642f62', 'timer_to': 0}, 'scheduler/result': { 'enabled': True, 'target': '7e78a032ef642f62', 'timer_to': 0}}, 
    assertEventsTopic = 'scheduler/result', assertEvents = { 'output': {'value': 1, 'port': '7e78a032ef642f62', 'timer_to': 0}})
  """

    system.time_offset(600)
    test.assertx("check13-run",
                 assertSubscribe={'item/item1/action': '1'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    test.assertAction("check14-disable",
                      'scheduler',
                      'output-set', {
                          'value': 0,
                          'port': '7e78a032ef642f62'
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': False,
                              'target': '7e78a032ef642f62',
                              'timer_to': 0
                          },
                          'scheduler/result': {
                              'enabled': False,
                              'target': '7e78a032ef642f62',
                              'timer_to': 0
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 0,
                              'port': '7e78a032ef642f62',
                              'timer_to': 0
                          }
                      })

    system.time_offset(86400)
    test.assertx("check15-run",
                 assertSubscribe={'item/item1/action': '2'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    system.time_offset(43200)
    test.assertx("check16-idle",
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    test.assertAction("check17-disable",
                      'scheduler',
                      'output-set', {
                          'value': 0,
                          'port': '@item1'
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': False,
                              'target': '@item1',
                              'timer_to': 0
                          },
                          'scheduler/result': {
                              'enabled': False,
                              'target': 'testsched,groupname.6abc8cf88f7957a5',
                              'timer_to': 0
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 0,
                              'port': 'testsched,groupname.6abc8cf88f7957a5',
                              'timer_to': 0
                          }
                      })

    system.time_offset(86400)
    test.assertx("check18-idle",
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    test.assertAction("check19-enable",
                      'scheduler',
                      'output-set', {
                          'value': 1,
                          'port': '@item1@TEST'
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': True,
                              'target': '@item1@TEST',
                              'timer_to': 0
                          },
                          'scheduler/result': {
                              'enabled': True,
                              'target': 'testsched,groupname.6abc8cf88f7957a5',
                              'timer_to': 0
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 1,
                              'port': 'testsched,groupname.6abc8cf88f7957a5',
                              'timer_to': 0
                          }
                      })

    test.assertx("check20-run",
                 assertSubscribe={'item/item1/action': '2'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    test.assertAction("check20-disable",
                      'scheduler',
                      'output-set', {
                          'value': 0,
                          'port': 'testsched'
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': False,
                              'target': 'testsched',
                              'timer_to': 0
                          },
                          'scheduler/result': {
                              'enabled': False,
                              'target': 'testsched',
                              'timer_to': 0
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 0,
                              'port': 'testsched',
                              'timer_to': 0
                          }
                      })

    test.assertAction("check21-enable",
                      'scheduler',
                      'output-set', {
                          'value': 1,
                          'port': 'groupname'
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': True,
                              'target': 'groupname',
                              'timer_to': 0
                          },
                          'scheduler/result': {
                              'enabled': True,
                              'target': 'groupname',
                              'timer_to': 0
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 1,
                              'port': 'groupname',
                              'timer_to': 0
                          }
                      })

    system.time_set(1577833200 + 7 * 86400 + 30)  # 2020-01-01 00:00:00
    test.assertx("check22-run",
                 assertSubscribe={'item/item1/action': '3'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    t1 = system.time() + 14 * 86400
    test.assertAction("check23-disable",
                      'scheduler',
                      'output-set', {
                          'value': 0,
                          'port': 'groupname',
                          'timer_to': '2w'
                      },
                      assertSubscribe={
                          'scheduler/set': {
                              'enabled': False,
                              'target': 'groupname',
                              'timer_to': '2w'
                          },
                          'scheduler/result': {
                              'enabled': False,
                              'target': 'groupname',
                              'timer_to': ('d', t1)
                          }
                      },
                      assertEventsTopic='scheduler/result',
                      assertEvents={
                          'output': {
                              'value': 0,
                              'port': 'groupname',
                              'timer_to': ('d', t1)
                          }
                      })

    system.time_offset(7 * 86400)
    test.assertx("check24-idle",
                 assertSubscribeNotReceive=['item/item1/action'],
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    system.time_offset(1)
    test.assertx("check25-status",
                 assertSubscribe={
                     'scheduler/status': {
                         "enabled": True,
                         "time": (),
                         "timer_to": 0,
                         "groups": {
                             "groupname": {
                                 "enabled": False,
                                 "timer_to": ('d', t1)
                             },
                         },
                         "jobs": {
                             "7e78a032ef642f62": {
                                 "run_cron": "*/10 * * * *",
                                 "do": ["item1.action(params['value']='1')"],
                                 "enabled": False,
                                 "max_delay": 60,
                                 "last_run": (),
                                 "next_run": (),
                                 "timer_to": 0
                             },
                             "testsched": {
                                 "entry_id": "item1@TEST",
                                 "run_interval": 86400,
                                 "do": [".action(params['value']='2')"],
                                 "enabled": False,
                                 "max_delay": 0,
                                 "last_run": (),
                                 "next_run": (),
                                 "timer_to": 0
                             },
                             "groupname.6abc8cf88f7957a5": {
                                 "group": "groupname",
                                 "entry_id": "item1@TEST",
                                 "run_cron": "0 0 */7 * *",
                                 "do": [".action(params[\'value\']=\'3\')"],
                                 "enabled": True,
                                 "max_delay": 60,
                                 "last_run": (),
                                 "next_run": (),
                                 "timer_to": 0
                             }
                         }
                     }
                 },
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    system.time_offset(7 * 86400)
    test.assertx("check26-run",
                 assertSubscribe={'item/item1/action': '3'},
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    system.time_offset(2)
    test.assertx("check27-status",
                 assertSubscribe={
                     'scheduler/status': {
                         "enabled": True,
                         "time": (),
                         "timer_to": 0,
                         "groups": {
                             "groupname": {
                                 "enabled": True,
                                 "timer_to": 0
                             },
                         },
                         "jobs": {
                             "7e78a032ef642f62": {
                                 "run_cron": "*/10 * * * *",
                                 "do": ["item1.action(params['value']='1')"],
                                 "enabled": False,
                                 "max_delay": 60,
                                 "last_run": (),
                                 "next_run": (),
                                 "timer_to": 0
                             },
                             "testsched": {
                                 "entry_id": "item1@TEST",
                                 "run_interval": 86400,
                                 "do": [".action(params['value']='2')"],
                                 "enabled": False,
                                 "max_delay": 0,
                                 "last_run": (),
                                 "next_run": (),
                                 "timer_to": 0
                             },
                             "groupname.6abc8cf88f7957a5": {
                                 "group": "groupname",
                                 "entry_id": "item1@TEST",
                                 "run_cron": "0 0 */7 * *",
                                 "do": [".action(params[\'value\']=\'3\')"],
                                 "enabled": True,
                                 "max_delay": 60,
                                 "last_run": (),
                                 "next_run": (),
                                 "timer_to": 0
                             }
                         }
                     }
                 },
                 wait=False)
    node_system.run_step()
    test.waitRunning()
def test_init():
    test.add_node_config({
        #"listen_all_events": True,
        "entries": [
            {
                "module": "toggle"
            },
            {
                "module": "scripting"
            },
            {
                "device": "test-toggle-device",
                "data": {
                    "status": 0
                },
                "publish": {
                    "device/toggle-status": {
                        "type": "object",
                        "events": {
                            "output":
                            "js:({value: payload['value'] == 'on' ? 1 : 0})",
                            "clock": "js:({value: payload['time']})",
                        }
                    }
                },
                "subscribe": {
                    "device/toggle": {
                        "script": ["status = 1 if payload == 'on' else 0"],
                        "response": ["device/toggle-status"],
                        "publish": ["device/toggle-status"],
                        "actions": {
                            "output-set": "js:params['value'] ? 'on' : 'off'"
                        }
                    },
                    "device/toggle/get": {
                        "response": ["device/toggle-status"],
                        "publish": ["device/toggle-status"],
                        "actions": {
                            "output-get": ""
                        }
                    },
                },
            },
            {
                "item": "test-toggle",
                "caption": "Test toggle",
                "toggle_devices": "test-toggle-device",
                "toggle_detached": False,
                "config": {
                    "toggle_defaults": {
                        "timer-to-1": 10,
                    }
                },
                "events_listen": [".output"],
            },
            {
                "device": "test-toggle-device2",
                "data": {
                    "status": 0
                },
                "publish": {
                    "/^device2/toggle-status([0-9]+)$/": {
                        "type": "object",
                        "events": {
                            "output":
                            'js:({value: payload == "ON" ? 1 : 0, port: matches[1] ? matches[1] : "0"})',
                        }
                    }
                },
                'subscribe': {
                    '/^device2/toggle([0-9]*)$/': {
                        'type': ['ON', 'OFF'],
                        'actions': {
                            'output-set': {
                                'topic':
                                'js:"device2/toggle" + ("port" in params && params["port"] != "0" ? params["port"] : "")',
                                'payload': 'js:params["value"] ? "ON" : "OFF"'
                            },
                        }
                    }
                }
            },
            {
                "item": "test-toggle2",
                "caption": "Test toggle 2",
                "toggle_devices": "test-toggle-device2(params['port'] == '9')",
                "events_listen": [".output"],
            },
            {
                "device": "test-toggle-device3",
                "publish": {
                    "device3/toggle-status": {
                        "type": "object",
                        "events": {
                            "output":
                            "js:({value: payload['value'] == 'on' ? 1 : 0})",
                        }
                    }
                },
                "subscribe": {
                    "device3/toggle": {
                        "response": ["device3/toggle-status"],
                        "actions": {
                            "output-set": "js:params['value'] ? 'on' : 'off'"
                        }
                    },
                },
            },
            {
                "item": "test-toggle3",
                "caption": "Test toggle",
                "toggle_devices": "test-toggle-device3",
            },
        ],
    })

    # Check that during the init phase, the device status is requested (because it supports the "output-get" action)
    test.assertx('init', assertSubscribe={'device/toggle/get': ''}, wait=False)
def test_run(entries):
    test.waitRunning()

    # First device status to initialize the item
    #system.broker().publish('device/toggle-status', { 'value': 'off', 'time': system.time() })

    # First device status to initialize the item
    test.waitPublish('device/toggle-status', {
        'value': 'on',
        'time': system.time()
    })

    test.assertx('device-init',
                 assertSubscribeSomePayload={
                     'item/test-toggle': {
                         'state': 1,
                         'timer-to': 0,
                         'defaults': {
                             'timer-to-1': 10
                         },
                         'changed': False
                     }
                 },
                 wait=False)
    node_system.run_step()
    test.waitRunning()

    # Device OFF
    test.assertPublish('device-init-after',
                       'device/toggle-status', {
                           'value': 'off',
                           'time': system.time()
                       },
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 0,
                               'timer-to': 0,
                               'defaults': {
                                   'timer-to-1': 10
                               },
                               'changed': True
                           }
                       })

    # Test item set
    test.assertPublish('set-on',
                       'item/test-toggle/set',
                       1,
                       assertSubscribe={'device/toggle': 'on'},
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 1,
                               'timer-to': ('d', system.time() + 10),
                               'defaults': {
                                   'timer-to-1': 10
                               },
                               'changed': True
                           }
                       },
                       assertEventsTopic='item/test-toggle',
                       assertEvents={
                           'output': {
                               'value': 1,
                               'timer_to': ('d', system.time() + 10)
                           }
                       })

    # I need to simulate input button changed to on: so next test could switch if off - if i don't do this, next "device/toggle-status=off" i useless (it's already "off)
    test.assertPublish('device-on',
                       'device/toggle-status', {
                           'value': 'on',
                           'time': system.time()
                       },
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 1,
                               'timer-to': ('d', system.time() + 10),
                               'type': 'toggle',
                               'changed': False
                           }
                       },
                       assertEventsTopic='item/test-toggle',
                       assertEvents={
                           'output': {
                               'value': 1,
                               'timer_to': ('d', system.time() + 10)
                           }
                       })

    # Test device changing its status (was ON, now i put it OFF), and toggle item should follow
    system.time_offset(5)  # To avoid debounce
    t = system.time()
    test.assertPublish(
        'device-off',
        'device/toggle-status',
        {
            'value': 'off',
            'time': t
        },
        #assertEvents = {'output': {'value': 0}, 'clock': {'value': t}},
        assertSubscribeSomePayload={
            'item/test-toggle': {
                'state': 0,
                'timer-to': 0,
                'defaults': {
                    'timer-to-1': 10
                },
                'changed': True
            }
        },
        assertEventsTopic='item/test-toggle',
        assertEvents={'output': {
            'value': 0,
            'timer_to': 0
        }})

    # Test item set via action
    test.assertAction('set-on-action',
                      'test-toggle',
                      'output-set', {'value': 1},
                      assertSubscribe={'item/test-toggle/set': {
                          'state': 1
                      }})

    # I need to simulate input button changed to on: so next test could switch if off - if i don't do this, next "device/toggle-status=off" i useless (it's already "off)
    test.assertPublish('device-on2',
                       'device/toggle-status', {
                           'value': 'on',
                           'time': system.time()
                       },
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 1,
                               'timer-to': ('d', system.time() + 10),
                               'type': 'toggle',
                               'changed': False
                           }
                       })

    # Test a standard timer
    test.assertPublish('set-off-timer',
                       'item/test-toggle/set', {
                           'state': 0,
                           'timer-to': 1
                       },
                       assertSubscribe={'device/toggle': 'off'},
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 0,
                               'timer-to': ('d', system.time() + 1),
                               'defaults': {
                                   'timer-to-1': 10
                               },
                               'changed': True
                           }
                       })
    test.assertx('set-off-timer-after',
                 assertSubscribe={'device/toggle': 'on'},
                 assertSubscribeSomePayload={
                     'item/test-toggle': {
                         'state': 1,
                         'timer-to': 0,
                         'changed': True
                     }
                 })

    # Test timer via action
    test.assertAction('set-timer-action',
                      'test-toggle',
                      'output-set', {
                          'value': 0,
                          'timer_to': 1
                      },
                      assertSubscribe={
                          'item/test-toggle/set': {
                              'state': 0,
                              'timer-to': 1
                          },
                          'device/toggle': 'off'
                      })
    test.assertx('set-timer-action-after',
                 assertSubscribe={'device/toggle': 'on'},
                 assertSubscribeSomePayload={
                     'item/test-toggle': {
                         'state': 1,
                         'timer-to': 0,
                         'changed': True
                     }
                 })

    # Test toggle/invert
    test.assertPublish('invert',
                       'item/test-toggle/toggle', {},
                       assertSubscribe={'device/toggle': 'off'},
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 0,
                               'timer-to': 0,
                               'changed': True
                           }
                       })
    test.assertAction('invert-action',
                      'test-toggle',
                      'output-invert', {'timer_to': 0},
                      assertSubscribe={
                          'item/test-toggle/toggle': {
                              'timer-to': 0
                          },
                          'device/toggle': 'on'
                      },
                      assertSubscribeSomePayload={
                          'item/test-toggle': {
                              'state': 1,
                              'timer-to': 0,
                              'changed': True
                          }
                      })

    # Change default timer + get
    system.broker().publish('item/test-toggle/set-defaults', {
        'timer-to-1': 1,
        'timer-to-0': 1
    })
    test.assertPublish('set-defaults',
                       'item/test-toggle/get',
                       None,
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 1,
                               'timer-to': 0,
                               'defaults': {
                                   'timer-to-1': 1,
                                   'timer-to-0': 1
                               },
                               'changed': False
                           }
                       })
    test.assertPublish('set-off-default-timer',
                       'item/test-toggle/set',
                       0,
                       assertSubscribe={'device/toggle': 'off'},
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 0,
                               'timer-to': ('d', system.time() + 1),
                               'defaults': {
                                   'timer-to-1': 1,
                                   'timer-to-0': 1
                               },
                               'changed': True
                           }
                       })
    test.assertx('set-off-default-timer-after',
                 assertSubscribe={'device/toggle': 'on'},
                 assertSubscribeSomePayload={
                     'item/test-toggle': {
                         'state': 1,
                         'timer-to': 0,
                         'changed': True
                     }
                 })

    # Test toggle (with default timer setted before)
    test.assertPublish('toggle',
                       'item/test-toggle/toggle',
                       None,
                       assertSubscribe={'device/toggle': 'off'},
                       assertSubscribeSomePayload={
                           'item/test-toggle': {
                               'state': 0,
                               'timer-to': ('d', system.time() + 1),
                               'defaults': {
                                   'timer-to-1': 1,
                                   'timer-to-0': 1
                               },
                               'changed': True
                           }
                       })
    test.assertx('toggle-timer-after',
                 assertSubscribe={'device/toggle': 'on'},
                 assertSubscribeSomePayload={
                     'item/test-toggle': {
                         'state': 1,
                         'timer-to': 0,
                         'changed': True
                     }
                 })

    # First device status to initialize the item
    test.waitPublish('device2/toggle-status9', 'OFF')

    # Test toggle_devices: "test-toggle-device(port = 1)"
    test.assertPublish(
        'b-set-on',
        'item/test-toggle2/set',
        1,
        assertSubscribe={'device2/toggle9': 'ON'},
        assertSubscribeSomePayload={'item/test-toggle2': {
            'state': 1
        }},
        assertEventsTopic='item/test-toggle2',
        assertEvents={'output': {
            'value': 1,
            'timer_to': 0
        }})
    # TODO Missing ['publish'] directive in device subscribe, so i must publish it to simulate the device status change
    test.assertPublish('b-device-reponse',
                       'device2/toggle-status9',
                       'ON',
                       assertEvents={'output': {
                           'value': 1,
                           'port': '9'
                       }})
    test.assertPublish(
        'b-device-on',
        'device2/toggle-status9',
        'OFF',
        assertSubscribeSomePayload={
            'item/test-toggle2': {
                'state': 0,
                'type': 'toggle'
            }
        },
        assertEventsTopic='item/test-toggle2',
        assertEvents={'output': {
            'value': 0,
            'timer_to': 0
        }}
        #assertEvents = { 'output': { 'value': 0, 'port': '9' } }
    )

    # DEBOUNCE TEST (occour on debounce3)

    # First device status to initialize the item
    system.broker().publish('device3/toggle-status', {'value': 'off'})

    test.assertPublish(
        'debounce1',
        'item/test-toggle3/set',
        1,
        assertSubscribe={'device3/toggle': 'on'},
        assertSubscribeSomePayload={'item/test-toggle3': {
            'state': 1
        }})
    test.assertPublish(
        'debounce2',
        'item/test-toggle3/set',
        0,
        assertSubscribe={'device3/toggle': 'off'},
        assertSubscribeSomePayload={'item/test-toggle3': {
            'state': 0
        }})

    # If i put a system.sleep() > toggle_debounce_time the bug will occour
    #system.sleep(2)

    test.assertPublish(
        'debounce3',
        'device3/toggle-status', {'value': 'on'},
        assertSubscribeSomePayload={'item/test-toggle3': {
            'state': 0
        }})
    test.assertPublish(
        'debounce4',
        'device3/toggle-status', {'value': 'off'},
        assertSubscribeSomePayload={'item/test-toggle3': {
            'state': 0
        }})
Exemple #9
0
def test_run(entries):
    if test_history:
        entries['history@TEST'].module.run(entries['history@TEST'])

    if (True):
        # Test "events", "on" declarations and "payload_transform"
        test.assertPublish(
            's1',
            'entry_b/pub1',
            'test',
            assertChild=['entry_a_on_test_event1'],
            assertNotChild=[
                'entry_a_on_test_event2', 'entry_a_on_test_event_implicit'
            ],
            assertEvents={'test_event': {
                'port': 'test1'
            }},
            assertNotification=['info', 'Entry B published pub1=test'])
        test.assertPublish(
            's2',
            'entry_b/pub1',
            '',
            assertChild=['entry_a_on_test_event1', 'entry_a_on_test_event2'],
            assertEvents={'test_event': {
                'port': '1'
            }},
            assertNotification=['info', 'Entry B published pub1='])
        test.assertPublish(
            's3',
            'entry_b/pub2',
            '{"x": 1}',
            assertEvents={'test_event': {
                'port': '1transformed1'
            }},
            assertNotification=['info', 'Entry B published pub2=1transformed'])
        test.assertPublish('s4',
                           'entry_b/pub3',
                           'test',
                           assertNotChild=[
                               'entry_a_on_test_event1',
                               'entry_a_on_test_event2',
                               'entry_a_on_test_event_implicit'
                           ],
                           assertEvents={})

        # Test .on called programmatically on a specific entry
        system.entry_get('entry_a').on('test_event', on_test_on_event3,
                                       'js:params["port"] == "entry_a"')
        entries['entry_a@TEST'].on('test_event', on_test_on_event2,
                                   'js:params["port"] == "fake"')
        test.assertPublish(
            's5',
            'item/entry_a/event',
            '',
            assertChild=['entry_a_prog_on', 'entry_a_on_test_event_implicit'],
            assertNotChild=['entry_a_on_test_event2'],
            assertEvents={'test_event': {
                "port": "entry_a"
            }})

        #system.entry_reload('entry_a@TEST');

        # Test "actions" and "handler" declarations
        test.assertAction('s6',
                          'entry_b',
                          'test_action', {'value': '1'},
                          init='js:params["val2"] = "0"',
                          assertSubscribe={
                              'subs/entry_b': 'test10',
                              'subs/entry_b/response': 'ok'
                          },
                          assertChild=[
                              'entry_b_on_subscribed_message',
                              'entry_b_publish',
                              'entry_b_on_events_passthrough'
                          ],
                          assertEventsTopic='subs/entry_b/response',
                          assertEvents={'test_action_response': {}})
        test.assertAction(
            's7',
            'entry_b',
            'test_action2', {'value': '1'},
            init='js:params["val2"] = params["val2"] + "X"',
            assertSubscribe={
                'subs/entry_b/TEST0X': 'test10X',
                'subs/entry_b/response': 'ok'
            },
            assertChild=['entry_b_on_subscribed_message2', 'entry_b_publish'],
            assertEventsTopic='subs/entry_b/response',
            assertEvents={'test_action_response': {}})

        # Test "on"."do"
        test.assertPublish('s8',
                           'subs/entry_b/test_do',
                           2,
                           assertSubscribe={'entry_b/test_do_result': '3'})

        # Test changed_params
        test.assertPublish('s9',
                           'entry_b/pub1',
                           '',
                           assertEventsData=True,
                           assertEvents=[{
                               'name': 'test_event',
                               'params': {
                                   'port': '1'
                               },
                               'changed_params': {},
                               'keys': {
                                   'port': '1'
                               },
                               'time': ('*', )
                           }])
        test.assertPublish('s10',
                           'entry_b/pub1',
                           '1',
                           assertEventsData=True,
                           assertEvents=[{
                               'name': 'test_event',
                               'params': {
                                   'port': '11'
                               },
                               'changed_params': {},
                               'keys': {
                                   'port': '11'
                               },
                               'time': ('*', )
                           }])

        if test_history:
            entries['history@TEST'].module.run(entries['history@TEST'])

    ####################################################################################
    ### TEST event_get cache e event_keys

    if (True):
        test.assertPublish('e1',
                           'item/entry_c/event', {
                               'port': '1',
                               'value': 5
                           },
                           assertEvents={'data': {
                               'port': '1',
                               'value': 5
                           }})
        system.time_offset(10)
        test.assertx(
            'e2',
            assertEq=[
                (system.event_get("entry_c.data"), {
                    'port': '1',
                    'value': 5
                }),
                (system.event_get("entry_c.data", timeout=5), None),
                (system.event_get("entry_c.data(js:params['port'] == '1')"), {
                    'port': '1',
                    'value': 5
                }),
                (system.event_get("entry_c.data(js:params['port'] == '1')",
                                  timeout=5), None),
                (system.event_get("entry_c.data(js:params['port'] == '2')"),
                 None),
            ])
        test.assertPublish('e3',
                           'item/entry_c/event', {
                               'port': '2',
                               'value': 6
                           },
                           assertEvents={'data': {
                               'port': '2',
                               'value': 6
                           }})
        system.time_offset(10)
        test.assertx(
            'e4',
            assertEq=[
                (system.event_get("entry_c.data"), {
                    'port': '2',
                    'value': 6
                }),
                (system.event_get("entry_c.data", timeout=5), None),
                (system.event_get("entry_c.data(js:params['port'] == '1')"), {
                    'port': '1',
                    'value': 5
                }),
                (system.event_get("entry_c.data(js:params['port'] == '1')",
                                  timeout=5), None),
                (system.event_get("entry_c.data(js:params['port'] == '2')"), {
                    'port': '2',
                    'value': 6
                }),
                (system.event_get("entry_c.data(js:params['port'] == '2')",
                                  timeout=5), None),
            ])
        system.do_action("entry_c.data-set(js:params['port'] = '2')",
                         {'value': 7})  # invalidates port=2 cache
        test.assertx(
            'e5',
            assertEq=[
                (system.event_get("entry_c.data"), {
                    'port': '1',
                    'value': 5
                }),
                (system.event_get("entry_c.data", timeout=5), None),
                (system.event_get("entry_c.data(js:params['port'] == '1')"), {
                    'port': '1',
                    'value': 5
                }),
                (system.event_get("entry_c.data(js:params['port'] == '1')",
                                  timeout=5), None),
                (system.event_get("entry_c.data(js:params['port'] == '2')"),
                 None),
                (system.event_get("entry_c.data(js:params['port'] == '2')",
                                  timeout=5), None),
            ])
        test.assertPublish('e6',
                           'item/entry_c/event', {
                               'port': '2',
                               'value': 7
                           },
                           assertEvents={'data': {
                               'port': '2',
                               'value': 7
                           }})
        test.assertPublish('e7',
                           'item/entry_c/event', {
                               'port': '1',
                               'value': 8
                           },
                           assertEvents={'data': {
                               'port': '1',
                               'value': 8
                           }})
        system.do_action(
            "entry_c.data-set(js:params['port'] = '2')", {'value': 8},
            if_event_not_match="entry_c.data(js:params['port'] == 1)"
        )  # NOT invalidates cache, action is NOT done (event matched)
        test.assertx(
            'e7',
            assertEq=[
                (system.event_get("entry_c.data"), {
                    'port': '1',
                    'value': 8
                }),
                (system.event_get("entry_c.data", timeout=5), {
                    'port': '1',
                    'value': 8
                }),
                (system.event_get("entry_c.data(js:params['port'] == '1')"), {
                    'port': '1',
                    'value': 8
                }),
                (system.event_get("entry_c.data(js:params['port'] == '1')",
                                  timeout=5), {
                                      'port': '1',
                                      'value': 8
                                  }),
                (system.event_get("entry_c.data(js:params['port'] == '2')"), {
                    'port': '2',
                    'value': 7
                }),
                (system.event_get("entry_c.data(js:params['port'] == '2')",
                                  timeout=5), {
                                      'port': '2',
                                      'value': 7
                                  }),
            ])
        system.do_action(
            "entry_c.data-set(js:params['port'] = '2')", {'value': 5},
            if_event_not_match="entry_c.data(js:params['port'] == 1)"
        )  # invalidate port=1 cache
        test.assertx(
            'e8',
            assertEq=[
                (system.event_get("entry_c.data"), {
                    'port': '2',
                    'value': 7
                }),
                (system.event_get("entry_c.data(js:params['port'] == '1')"),
                 None),
                (system.event_get("entry_c.data(js:params['port'] == '2')"), {
                    'port': '2',
                    'value': 7
                }),
            ])
        # test event_keys definition (different cache for 'myport' param and NOT for 'port')
        # also test for cumulative data of events and temporary
        test.assertPublish(
            'e9',
            'item/entry_d/event', {
                'myport': '1',
                'port': 5,
                'cumulated': 9
            },
            assertEvents={'data': {
                'myport': '1',
                'port': 5,
                'cumulated': 9
            }})
        test.assertx(
            'e10',
            assertEq=[
                (system.event_get("entry_d.data"), {
                    'myport': '1',
                    'port': 5,
                    'cumulated': 9
                }),
                (system.event_get("entry_d.data(js:params['myport'] == '1')"),
                 {
                     'myport': '1',
                     'port': 5,
                     'cumulated': 9
                 }),
                (system.event_get("entry_d.data(js:params['myport'] == '2')"),
                 None),
                (system.event_get("entry_d.data(js:params['port'] == 5)"), {
                    'myport': '1',
                    'port': 5,
                    'cumulated': 9
                }),
            ])
        test.assertPublish('e11',
                           'item/entry_d/event', {
                               'myport': '2',
                               'port': 6
                           },
                           assertEvents={'data': {
                               'myport': '2',
                               'port': 6
                           }})
        test.assertPublish(
            'e12',
            'item/entry_d/event', {
                'myport': '1',
                'port': 6
            },
            assertEvents={'data': {
                'myport': '1',
                'port': 6,
                'cumulated': 9
            }})
        test.assertx(
            'e13',
            assertEq=[
                (system.event_get("entry_d.data"), {
                    'myport': '1',
                    'port': 6,
                    'cumulated': 9
                }),
                (system.event_get("entry_d.data(js:params['myport'] == '1')"),
                 {
                     'myport': '1',
                     'port': 6,
                     'cumulated': 9
                 }),
                (system.event_get("entry_d.data(js:params['myport'] == '1')",
                                  temporary=True), None),
                (system.event_get("entry_d.data(js:params['myport'] == '2')"),
                 {
                     'myport': '2',
                     'port': 6
                 }),
                (system.event_get("entry_d.data(js:params['port'] == 5)"),
                 None),
            ])
        test.assertPublish('e14',
                           'item/entry_d/event', {
                               'myport': '1',
                               'port': 7,
                               'temporary': True
                           },
                           assertEvents={
                               'data': {
                                   'myport': '1',
                                   'port': 7,
                                   'cumulated': 9,
                                   'temporary': True
                               }
                           })
        test.assertx(
            'e15',
            assertEq=[
                (system.event_get("entry_d.data"), {
                    'myport': '1',
                    'port': 6,
                    'cumulated': 9
                }),
                (system.event_get("entry_d.data(js:params['myport'] == '1')"),
                 {
                     'myport': '1',
                     'port': 6,
                     'cumulated': 9
                 }),
                (system.event_get("entry_d.data(js:params['myport'] == '1')",
                                  temporary=True), {
                                      'myport': '1',
                                      'port': 7,
                                      'cumulated': 9,
                                      'temporary': True
                                  }),
                (system.event_get("entry_d.data(js:params['myport'] == '2')"),
                 {
                     'myport': '2',
                     'port': 6
                 }),
            ])
        if test_history:
            entries['history@TEST'].module.run(entries['history@TEST'])

    ####################################################################################
    ### TEST multiple events / event:init / event groups

    if (True):
        # this one publish an event {'port': '2', 'x': 'y'} and an event {'port': 1, 'value': 1}
        test.assertPublish('e16',
                           'item/entry_e/event', {
                               'x': 'y',
                               'port': '2'
                           },
                           assertEventsData=True,
                           assertEvents=[{
                               'name': 'data',
                               'params': {
                                   'port': '2',
                                   'x': 'y',
                                   'unit': 'B',
                                   'all': 1
                               },
                               'changed_params': {
                                   'x': 'y'
                               },
                               'keys': {
                                   'port': '2'
                               },
                               'time': ()
                           }, {
                               'name': 'data',
                               'params': {
                                   'port': '1',
                                   'value': 1,
                                   'unit': 'A',
                                   'all': 1
                               },
                               'changed_params': {
                                   'value': 1
                               },
                               'keys': {
                                   'port': '1'
                               },
                               'time': ()
                           }])
        # this one publish an event {'z': 3} [with no keys => impact other events with keys] and an event {'port': 1, 'value': 1}
        test.assertPublish('e17',
                           'item/entry_e/event', {'z': 3},
                           assertEventsData=True,
                           assertEvents=[{
                               'name': 'data',
                               'params': {
                                   'all': 1,
                                   'z': 3
                               },
                               'changed_params': {
                                   'z': 3
                               },
                               'keys': {},
                               'time': ()
                           }, {
                               'name': 'data',
                               'params': {
                                   'port': '1',
                                   'value': 1,
                                   'unit': 'A',
                                   'all': 1,
                                   'z': 3
                               },
                               'changed_params': {},
                               'keys': {
                                   'port': '1'
                               },
                               'time': ()
                           }])
        # this one publish an event {'all': 2 } [with no keys => impact other events with keys] and an event {'port': 1, 'value': 1}
        test.assertPublish('e18',
                           'item/entry_e/event', {'all': 2},
                           assertEventsData=True,
                           assertEvents=[{
                               'name': 'data',
                               'params': {
                                   'all': 2,
                                   'z': 3
                               },
                               'changed_params': {
                                   'all': 2
                               },
                               'keys': {},
                               'time': ()
                           }, {
                               'name': 'data',
                               'params': {
                                   'port': '1',
                                   'value': 1,
                                   'unit': 'A',
                                   'all': 2,
                                   'z': 3
                               },
                               'changed_params': {},
                               'keys': {
                                   'port': '1'
                               },
                               'time': ()
                           }])
        if test_history:
            entries['history@TEST'].module.run(entries['history@TEST'])

        test.assertPublish('e20',
                           'item/entry_e/group', {'v1': 1},
                           assertNotChild=['entry_e.on_group_event'],
                           timeoutms=1000,
                           wait=False)
        test.assertPublish('e21',
                           'item/entry_e/group', {'v2': 2},
                           assertNotChild=['entry_e.on_group_event'],
                           timeoutms=1000,
                           wait=False)
        test.waitRunning()
        system.time_offset(60)
        test.assertx('e22', assertChild=['entry_e.on_group_event'])

    ####################################################################################
    ### TEST topic_matches

    if (True):
        test.assertx(
            'topic_matches',
            assertEq=[
                (system.topic_matches('a/b', 'a/b', ''), {
                    'matched': True,
                    'topic_matches': [True],
                    'use_payload': False,
                    'used': ('*', )
                }),
                (system.topic_matches('a/+/c', 'a/b/c', ''), {
                    'matched': True,
                    'topic_matches': [True],
                    'use_payload': False,
                    'used': ('*', )
                }),
                (system.topic_matches('a/#', 'a/b/c', ''), {
                    'matched': True,
                    'topic_matches': [True],
                    'use_payload': False,
                    'used': ('*', )
                }),
                (system.topic_matches('a/#', 'b/c', ''), {
                    'matched': False,
                    'topic_matches': [],
                    'use_payload': None,
                    'used': ('*', )
                }),
                (system.topic_matches('/^a(.*)$/', 'a/b/c', ''), {
                    'matched': True,
                    'topic_matches': ['a/b/c', '/b/c'],
                    'use_payload': False,
                    'used': ('*', )
                }),
                (system.topic_matches('/^a(.*)$/[1/|2/]', 'a/b/c', ''), {
                    'matched': False,
                    'topic_matches': ['a/b/c', '/b/c'],
                    'use_payload': True,
                    'used': ('*', )
                }),
                (system.topic_matches('/^a(.*)$/[1|2/]', 'a/b/c', '2/'), {
                    'matched': True,
                    'topic_matches': ['a/b/c', '/b/c'],
                    'use_payload': True,
                    'used': ('*', )
                }),
                (system.topic_matches('a/#[/^z.*z$/]', 'a/b/c', 'x'), {
                    'matched': False,
                    'topic_matches': [True],
                    'use_payload': True,
                    'used': ('*', )
                }),
                (system.topic_matches('a/#[/^z.*z$/]', 'a/b/c', 'zxz'), {
                    'matched': True,
                    'topic_matches': [True],
                    'use_payload': True,
                    'used': ('*', )
                }),
                (system.topic_matches('a/+[js: payload=="x"]', 'a/b', ''), {
                    'matched': False,
                    'topic_matches': [True],
                    'use_payload': True,
                    'used': ('*', )
                }),
                (system.topic_matches('a/+[js: payload=="x"]', 'a/b', 'x'), {
                    'matched': True,
                    'topic_matches': [True],
                    'use_payload': True,
                    'used': ('*', )
                }),
                (system.topic_matches('/^a(.*)$/[js: matches[1]=="/b/c"]',
                                      'a/b/c', ''), {
                                          'matched': True,
                                          'topic_matches': ['a/b/c', '/b/c'],
                                          'use_payload': False,
                                          'used': ('*', )
                                      }),
                (system.topic_matches('/^a(.*)$/[js: matches[1]=="/b/c"]',
                                      'a/d/e', ''), {
                                          'matched': False,
                                          'topic_matches': ['a/d/e', '/d/e'],
                                          'use_payload': False,
                                          'used': ('*', )
                                      }),
                (system.topic_matches(
                    '/^a(.*)$/[js: matches[1]=="/b/c" && payload=="x"]',
                    'a/b/c', ''), {
                        'matched': False,
                        'topic_matches': ['a/b/c', '/b/c'],
                        'use_payload': True,
                        'used': ('*', )
                    }),
                (system.topic_matches(
                    '/^a(.*)$/[js: matches[1]=="/b/c" && payload=="x"]',
                    'a/b/c', 'x'), {
                        'matched': True,
                        'topic_matches': ['a/b/c', '/b/c'],
                        'use_payload': True,
                        'used': ('*', )
                    }),
            ])
        if test_history:
            entries['history@TEST'].module.run(entries['history@TEST'])
def test_run(entries):
  system.on_entry_load(system_on_entry_load)
  
  e_scripting = { "module": "scripting" }
  e_module0 = {
      "module": "module0",
      "module1": "on",
      "methods": {
        "entry_load": [ "print('> Loading module0 on ' + str(args[1].id))", "test.assertChild('module0_loaded_on_' + str(args[1].id))" ],
      }
    }
  e_module1 = {
      "module": "module1",
      "install_on": { "module1": "on" },
      "methods": {
        "entry_install": [ "print('> Installing module1 on ' + str(args[1].id))", "test.assertChild('module1_installed_on_' + str(args[1].id))" ],
        "init": [ "print('> Initializing module1' + entry.id)", "entry.test_val = 'x'" ],
        "entry_init": [ "print('> Entry init module1 on ' + str(args[1].id))", "test.assertChild('module1_initialized_' + str(args[1].id), assertEq = [(hasattr(args[0], 'test_val') and args[0].test_val == 'x', True)])" ],
      }
    }
  
  # Installati in ordine, riesce a fare tutto
  test.assertx('t1', 
    assertChild = ['module0_loaded_on_scripting@TEST', 'module0_loaded_on_module1@TEST', 'module1_installed_on_module0@TEST', 'module1_initialized_module0@TEST', "system_started_loading_module0@TEST", "system_started_loading_module1@TEST"], 
    assertNotChild = ['module1_installed_on_module1@TEST', 'module1_initialized_module1@TEST'], wait = False)
  system.entry_load([e_scripting, e_module0, e_module1], id_from_definition = True)
  test.waitRunning()
  
  # Test signatures (non deve ricaricare se gli do le stesse definizioni)
  test.assertx('t1_sign_unchanged', 
    assertNotChild = ["system_started_loading_module0@TEST", "system_started_loading_module1@TEST"], wait = False)
  system.entry_load([e_module0, e_module1], id_from_definition = True)
  test.waitRunning()
  
  test.assertx('t1_sign_changed',
    # WARN module0_loaded_on_scripting@TEST is called with a warning "Calling [email protected]_load on scripting@TEST, but scripting@TEST has not been reloaded". See the code on node_system to understand the problem.
    assertChild = ['module0_loaded_on_scripting@TEST', 'module0_loaded_on_module1@TEST', 'module1_installed_on_module0@TEST', 'module1_initialized_module0@TEST', "system_started_loading_module0@TEST", "system_started_loading_module1@TEST"], 
    assertNotChild = ['system_started_loading_scripting@TEST'], wait = False)
  e_module1["description"] = "..."
  system.entry_load([e_module0, e_module1], id_from_definition = True)
  test.waitRunning()

  system.entry_unload(["scripting@TEST", "module0@TEST", "module1@TEST"])
  
  # Scripting per ultimo: non viene chiamato script entry_load dei moduli, perchè è un handler gestito via script che viene caricato dopo, però viene chiamato entry_install (perchè gli install sono dopo i load)
  test.assertx('t2', assertNotChild = ['module0_loaded_on_scripting@TEST', 'module0_loaded_on_module1@TEST'], assertChild = ['module1_installed_on_module0@TEST', 'module1_initialized_module0@TEST'], wait = False)
  system.entry_load([e_module0, e_module1, e_scripting], id_from_definition = True)
  test.waitRunning()
  system.entry_unload(["scripting@TEST", "module0@TEST", "module1@TEST"])

  # Caricando scripting in un secondo momento fa un reload generale, e quindi va (ma fa dei loading di troppo)
  test.assertx('t3a', assertNotChild = ['module0_loaded_on_scripting@TEST', 'module0_loaded_on_module1@TEST', 'module1_installed_on_module0@TEST', 'module1_initialized_module0@TEST'], wait = False)
  system.entry_load([e_module0, e_module1], id_from_definition = True)
  test.waitRunning()
  test.assertx('t3b', assertChild = ['module0_loaded_on_scripting@TEST', 'module0_loaded_on_module1@TEST', 'module1_installed_on_module0@TEST', 'module1_initialized_module0@TEST'], wait = False)
  system.entry_load([e_scripting], id_from_definition = True)
  test.waitRunning()
  system.entry_unload(["scripting@TEST", "module0@TEST", "module1@TEST"])
  test.assertAction('s6', 'entry_b', 'test_action', { 'value': '1' }, init = 'js:params["val2"] = "0"', 
    assertEventsTopic = 'subs/entry_b/response', assertEvents = {'test_action_response': {}} # To check for events you MUST specify an events topic
    assertSubscribe = {'subs/entry_b': 'test10', 'subs/entry_b/response': 'ok'},
    assertChild = ['entry_b_on_subscribed_message', 'entry_b_publish', 'entry_b_on_events_passthrough'], 
  )
  # NOTE: use assertEventsData = True to check full events data (not only "params" but also "changed_params")
  
  # Generic assert with no action performed (no publish / subscribe / action)
  test.assertx('t1', 
    waitPublish = {'topic1': 'payload1:', ...}, # Do some "waitPublish" commands before the rest of the start starts
    assertSubscribe = {'device/test-rf-1/detected': ''}, assertEventsTopic = 'device/test-rf-1/detected', assertEvents = {'detected': {}, 'input': {'value': 1, 'temporary': 1}}, wait = False)
  # ... DO SOMETHING
  test.waitRunning()
  
  # Generic eq assert
  test.assertx('t5', assertEq = [(a, 'test'), (b, None)])
  
  # Wait the specific topic/message is published
  test.waitPublish("device/test-device/check", "online")
  
  # To make a direct call to a module handler
  entries['name@TEST'].module.callback(...)
  
  # Move ahead clock time by that number of seconds
  system.time_offset(5)
  # Pause the clock
  system.time_pause()
  # Resume the clock
  system.time_resume()

def on_some_callback(entry, eventname, params):
Exemple #12
0
def test_run(entries):
  #print("DIST: " + str(entries['presence@TEST'].module.locations_distance((45.123,12.123), (45.127,12.123))))
  
  # Mary enters via device
  t1 = system.time()
  test.assertx('t1', 
    assertSubscribeSomePayload = {
      'home/presence/in': {'name': 'mary', 'before_someone_inside': False, 'time': ('d', t1)},
      'home/presence': {'occupants': {'mary': {"firstseen": ('d', t1), "lastseen": ('d', t1), "methods": ["connected/device1@TEST"]}}, "time": ('d', t1)}, },
    assertNotification = ['info', 'mary has entered', 'home/presence/in' ],
      # ['debug', ('re', 'People detected:.*mary.*'), 'home/presence' ],
    assertEventsTopic = 'home/presence/in', assertEvents = {
      'presence-in': {'who': 'mary', 'before_someone_inside': False, 'region': 'home' }, 
      'clock': {'value': ('d', t1)}},
    assertExports = {'presence_someone_inside': True, 'presence_no_one_inside': False},
    wait = False)
  entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '01:02:03:04:05')
  test.waitRunning()

  # ... via location region
  t2 = system.time()
  test.assertPublish('t2a', 'owntracks/device/xxx', '{"_type":"location","acc":78,"alt":0,"batt":86,"conn":"w","inregions":["Region"],"lat":35.123,"lon":22.123,"tid":"ic","tst":1546871086,"vac":0,"vel":0}', 
    assertEvents = {
      'location': {'latitude': 35.123, 'longitude': 22.123, 'altitude': 0, 'radius': 78, 'radius:unit': 'm', 'regions': ['Region'], 'source': 'owntracks'},
      'clock': {'value': 1546871086}
    },
    assertSubscribeNotReceive = ['home/presence/in'])

  test.assertx('t2b', 
    assertSubscribeSomePayload = {
      'home/presence': {'occupants': {'mary': {"firstseen": ('d', t1), "lastseen": ('d', t2), "methods": ["connected/device1@TEST", "location_region/owntracks"]}}, "time": ('d', system.time())}, },
    assertNotification = [ 'debug', ('re', 'People detected:.*mary.*'), 'home/presence' ],
    assertSubscribeNotReceive = ['home/presence/in'],
    wait = False)
  entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])
  test.waitRunning()
  
  # ... via location position
  t3 = system.time()
  test.assertPublish('t3a', 'owntracks/device/xxx', '{"_type":"location","acc":78,"alt":0,"batt":86,"conn":"w","inregions":["Out"],"lat":45.127,"lon":12.123,"tid":"ic","tst":1546871086,"vac":0,"vel":0}', 
    assertSubscribeNotReceive = ['home/presence/in'])

  test.assertx('t3b', 
    assertSubscribeSomePayload = {
      'home/presence': {'occupants': {'mary': {"firstseen": ('d', t1), "lastseen": ('d', t3), "methods": ["connected/device1@TEST", "location_region/owntracks", "location/owntracks"]}}, "time": ('d', system.time())}, },
    assertNotification = [ 'debug', ('re', 'People detected:.*mary.*'), 'home/presence' ],
    assertSubscribeNotReceive = ['home/presence/in'],
    wait = False)
  entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])
  test.waitRunning()
  
  # Also John enters via device
  t4 = system.time()
  test.assertx('t4', 
    assertSubscribeSomePayload = {
      'home/presence/in': {'name': 'john', 'before_someone_inside': True, 'time': ('d', t4)},
      'home/presence': {'occupants': {'mary': {"firstseen": ('d', t1), "lastseen": ('d', t3), "methods": ["connected/device1@TEST", "location_region/owntracks", "location/owntracks"]}, "john": {"firstseen": ('d', t4), "lastseen": ('d', t4), "methods": ["connected/device2@TEST"]}}, "time": ('d', t4)}, },
    assertNotification = [ 'info', 'john has entered', 'home/presence/in' ],
      # 'debug', ('re', 'People detected:.*mary.*john.*'), 'home/presence'
    assertEventsTopic = 'home/presence/in', assertEvents = {
      'presence-in': {'who': 'john', 'before_someone_inside': True, 'region': 'home' }, 
      'clock': {'value': ('d', t4)}},
    assertExports = {'presence_someone_inside': True, 'presence_no_one_inside': False},
    wait = False)
  entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '0A:0B:0C:0D:0E')
  test.waitRunning()
  
  # Mary should exit if we wait connection_time/presence_location_session_duration
  system.time_offset(40)
  t5 = system.time()
  test.assertx('t5', 
    assertSubscribeSomePayload = {
      'home/presence/out': {'name': 'mary', 'after_someone_inside': True, 'time': ('d', t5)},
      'home/presence': {'occupants': {"john": {"firstseen": ('d', t4), "lastseen": ('d', t4), "methods": ["connected/device2@TEST"]}}, "time": ('d', t5)}, },
    assertNotification = [ 'info', 'mary has gone away', 'home/presence/out' ],
      # 'debug', ('re', 'People detected:.*john.*'), 'home/presence'
    assertEventsTopic = 'home/presence/out', assertEvents = {
      'presence-out': {'who': 'mary', 'after_someone_inside': True, 'region': 'home' }, 
      'clock': {'value': ('d', t5)}},
    wait = False)
  entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '0A:0B:0C:0D:0E') # John should stay there
  entries['net_sniffer_scapy@TEST'].module.status_check(entries['net_sniffer_scapy@TEST'])
  system.sleep(1) # To ensure the execution of events callbacks
  entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])
  test.waitRunning()

  # And now its time for John to exit too
  system.time_offset(40)
  t6 = system.time()
  test.assertx('t6', 
    assertSubscribeSomePayload = {
      'home/presence/out': {'name': 'john', 'after_someone_inside': False, 'time': ('d', t6)},
      'home/presence': {'occupants': {}, "time": ('d', t6)}, },
    assertNotification = [ 'info', 'john has gone away', 'home/presence/out' ],
      # 'debug', 'No people detected', 'home/presence'
    assertEventsTopic = 'home/presence/out', assertEvents = {
      'presence-out': {'who': 'john', 'after_someone_inside': False, 'region': 'home' }, 
      'clock': {'value': ('d', t6)}},
    assertExports = {'presence_someone_inside': False, 'presence_no_one_inside': True},
    wait = False)
  entries['net_sniffer_scapy@TEST'].module.status_check(entries['net_sniffer_scapy@TEST'])
  system.sleep(1) # To ensure the execution of events callbacks
  entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])
  test.waitRunning()
Exemple #13
0
def test_run(entries):
    # INIT
    test.waitPublish("device/test-device/lwt", "online")
    test.waitPublish(
        "device/test-device/check",
        "")  # sending @/check topic to avoid the "check_interval" failure

    if True:
        # Test device really offline (more than 1seconds) and health of device and item (that requires the device)
        test.assertPublish("dead",
                           "device/test-device/lwt",
                           "offline",
                           assertSubscribeSomePayload={
                               'device/test-device/health': {
                                   'value': 'dead',
                                   'reason': 'disconnected for too long',
                                   'time': ('d', system.time() + 1, 2)
                               },
                               'item/test-item/health': {
                                   'value': 'failure',
                                   'reason': ('re', '.*test-device.*dead.*'),
                                   'time': ('d', system.time() + 1, 2)
                               },
                           },
                           timeoutms=3000)

        # Online again
        test.assertPublish("alive-after-dead",
                           "device/test-device/lwt",
                           "online",
                           assertSubscribeSomePayload={
                               'device/test-device/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                               'item/test-item/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                           })

        # Offline, but not really
        test.waitPublish("device/test-device/lwt", "offline")
        test.assertPublish("not-dead",
                           "device/test-device/lwt",
                           "online",
                           assertSubscribeNotReceive=[
                               'device/test-device/health',
                               'item/test-item/health'
                           ])

    # check_interval
    if True:
        system.time_offset(90)
        test.assertx("check-interval",
                     assertSubscribeSomePayload={
                         'device/test-device/health': {
                             'value': 'failure',
                             'reason': ('re', '.*device/test-device/check.*'),
                             'time': ('d', system.time(), 2)
                         },
                         'item/test-item/health': {
                             'value': 'failure',
                             'reason': ('re', '.*test-device.*failure.*'),
                             'time': ('d', system.time(), 2)
                         },
                     })

        test.assertPublish("check-interval-resume",
                           "device/test-device/check",
                           "",
                           assertSubscribeSomePayload={
                               'device/test-device/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                               'item/test-item/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                           })

    if True:
        test.assertPublish("no-response1",
                           "device/test-device/sub1",
                           "",
                           assertSubscribeSomePayload={
                               'device/test-device/health': {
                                   'value': 'failure',
                                   'reason':
                                   ('re', '.*device/test-device/sub1.*'),
                                   'time': ('d', system.time(), 6)
                               },
                               'item/test-item/health': {
                                   'value': 'failure',
                                   'reason':
                                   ('re', '.*test-device.*failure.*'),
                                   'time': ('d', system.time(), 6)
                               },
                           },
                           timeoutms=7000)

        # I repeat the "no-response" test to be sure the @/# catchall rulle wont invalidate results
        test.assertPublish("no-response2",
                           "device/test-device/sub1",
                           "",
                           assertSubscribeNotReceive=[
                               'device/test-device/health',
                               'item/test-item/health'
                           ],
                           timeoutms=7000)

        test.waitPublish("device/test-device/sub1", "")
        test.assertPublish("correct-response",
                           "device/test-device/sub1-res",
                           "",
                           assertSubscribeSomePayload={
                               'device/test-device/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                               'item/test-item/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                           })
        """ TODO Il testo sotto sarebbe per la gestione corretta del "count", ma al momento non funziona (basta una qualunque risposta per evitare il failure)
      Questo perchè per il momento si è deciso che "response_callback" viene chiamato (con final = False) per qualunque risposta, e no_response_callback se anche solo un response_callback è stato chiamato non viene chiamato
      Volendo gestire il check "stretto" bisognerebbe fare anche un response_incomplete_callback oppure cambiare no_response_callback in response_error_callback con errore che può essere "no_response" o "incomplete" ... ma per ora è eccessivo
    test.assertx("no-response2", waitPublish = [
      ("device/test-device/sub2", None), 
      ("device/test-device/sub2-resa", None), 
      #("device/test-device/sub2-resa", None), 
      ("device/test-device/sub2-resb", None), 
    ], assertSubscribeSomePayload = { 
      'device/test-device/health': { 'value': 'failure', 'reason': ('re', '.*device/test-device/sub2.*'), 'time': ('d', system.time(), 6) },
      'item/test-item/health': { 'value': 'failure', 'reason': ('re', '.*test-device.*failure.*'), 'time': ('d', system.time(), 6) },
    }, timeoutms = 7000)
    """

        test.waitPublish("device/test-device/sub3xxx", "")
        test.assertPublish("no-response3",
                           "device/test-device/sub3yyy-res",
                           "",
                           assertSubscribeSomePayload={
                               'device/test-device/health': {
                                   'value': 'failure',
                                   'reason':
                                   ('re', '.*device/test-device/sub3.*'),
                                   'time': ('d', system.time(), 6)
                               },
                               'item/test-item/health': {
                                   'value': 'failure',
                                   'reason':
                                   ('re', '.*test-device.*failure.*'),
                                   'time': ('d', system.time(), 6)
                               },
                           },
                           timeoutms=7000)

        test.waitPublish("device/test-device/sub3xxx", "")
        test.assertPublish("correct-response3",
                           "device/test-device/sub3xxx-res",
                           "",
                           assertSubscribeSomePayload={
                               'device/test-device/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                               'item/test-item/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time())
                               },
                           })

    if True:
        # dead-message-timeout
        test.assertPublish("dead-message-timeout-pre",
                           "item/test-item2/check",
                           "",
                           assertSubscribeSomePayload={
                               'item/test-item2/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time(), 2)
                               },
                           })
        test.assertx("dead-message-timeout",
                     assertSubscribeSomePayload={
                         'item/test-item2/health': {
                             'value': 'dead',
                             'reason': 'silent for too long',
                             'time': ('d', system.time(), 4)
                         },
                     },
                     timeoutms=3000)
        test.assertPublish("dead-message-timeout-post",
                           "item/test-item2/check",
                           "",
                           assertSubscribeSomePayload={
                               'item/test-item2/health': {
                                   'value': 'alive',
                                   'reason': '',
                                   'time': ('d', system.time(), 2)
                               },
                           })