How to use wait_for_message method in testcontainers-python

Best Python code snippet using testcontainers-python_python

test_pubsub.py

Source:test_pubsub.py Github

copy

Full Screen

...4import redis5from redis.exceptions import ConnectionError6from redis._compat import basestring, u, unichr7from .conftest import r as _redis_client8def wait_for_message(pubsub, timeout=0.1, ignore_subscribe_messages=False):9 now = time.time()10 timeout = now + timeout11 while now < timeout:12 message = pubsub.get_message(13 ignore_subscribe_messages=ignore_subscribe_messages)14 if message is not None:15 return message16 time.sleep(0.01)17 now = time.time()18 return None19def make_message(type, channel, data, pattern=None):20 return {21 'type': type,22 'pattern': pattern and pattern.encode('utf-8') or None,23 'channel': channel.encode('utf-8'),24 'data': data.encode('utf-8') if isinstance(data, basestring) else data25 }26def make_subscribe_test_data(pubsub, type):27 if type == 'channel':28 return {29 'p': pubsub,30 'sub_type': 'subscribe',31 'unsub_type': 'unsubscribe',32 'sub_func': pubsub.subscribe,33 'unsub_func': pubsub.unsubscribe,34 'keys': ['foo', 'bar', u('uni') + unichr(4456) + u('code')]35 }36 elif type == 'pattern':37 return {38 'p': pubsub,39 'sub_type': 'psubscribe',40 'unsub_type': 'punsubscribe',41 'sub_func': pubsub.psubscribe,42 'unsub_func': pubsub.punsubscribe,43 'keys': ['f*', 'b*', u('uni') + unichr(4456) + u('*')]44 }45 assert False, 'invalid subscribe type: %s' % type46class TestPubSubSubscribeUnsubscribe(object):47 def _test_subscribe_unsubscribe(self, p, sub_type, unsub_type, sub_func,48 unsub_func, keys):49 for key in keys:50 assert sub_func(key) is None51 # should be a message for each channel/pattern we just subscribed to52 for i, key in enumerate(keys):53 assert wait_for_message(p) == make_message(sub_type, key, i + 1)54 for key in keys:55 assert unsub_func(key) is None56 # should be a message for each channel/pattern we just unsubscribed57 # from58 for i, key in enumerate(keys):59 i = len(keys) - 1 - i60 assert wait_for_message(p) == make_message(unsub_type, key, i)61 def test_channel_subscribe_unsubscribe(self, r):62 kwargs = make_subscribe_test_data(r.pubsub(), 'channel')63 self._test_subscribe_unsubscribe(**kwargs)64 def test_pattern_subscribe_unsubscribe(self, r):65 kwargs = make_subscribe_test_data(r.pubsub(), 'pattern')66 self._test_subscribe_unsubscribe(**kwargs)67 def _test_resubscribe_on_reconnection(self, p, sub_type, unsub_type,68 sub_func, unsub_func, keys):69 for key in keys:70 assert sub_func(key) is None71 # should be a message for each channel/pattern we just subscribed to72 for i, key in enumerate(keys):73 assert wait_for_message(p) == make_message(sub_type, key, i + 1)74 # manually disconnect75 p.connection.disconnect()76 # calling get_message again reconnects and resubscribes77 # note, we may not re-subscribe to channels in exactly the same order78 # so we have to do some extra checks to make sure we got them all79 messages = []80 for i in range(len(keys)):81 messages.append(wait_for_message(p))82 unique_channels = set()83 assert len(messages) == len(keys)84 for i, message in enumerate(messages):85 assert message['type'] == sub_type86 assert message['data'] == i + 187 assert isinstance(message['channel'], bytes)88 channel = message['channel'].decode('utf-8')89 unique_channels.add(channel)90 assert len(unique_channels) == len(keys)91 for channel in unique_channels:92 assert channel in keys93 def test_resubscribe_to_channels_on_reconnection(self, r):94 kwargs = make_subscribe_test_data(r.pubsub(), 'channel')95 self._test_resubscribe_on_reconnection(**kwargs)96 def test_resubscribe_to_patterns_on_reconnection(self, r):97 kwargs = make_subscribe_test_data(r.pubsub(), 'pattern')98 self._test_resubscribe_on_reconnection(**kwargs)99 def _test_subscribed_property(self, p, sub_type, unsub_type, sub_func,100 unsub_func, keys):101 assert p.subscribed is False102 sub_func(keys[0])103 # we're now subscribed even though we haven't processed the104 # reply from the server just yet105 assert p.subscribed is True106 assert wait_for_message(p) == make_message(sub_type, keys[0], 1)107 # we're still subscribed108 assert p.subscribed is True109 # unsubscribe from all channels110 unsub_func()111 # we're still technically subscribed until we process the112 # response messages from the server113 assert p.subscribed is True114 assert wait_for_message(p) == make_message(unsub_type, keys[0], 0)115 # now we're no longer subscribed as no more messages can be delivered116 # to any channels we were listening to117 assert p.subscribed is False118 # subscribing again flips the flag back119 sub_func(keys[0])120 assert p.subscribed is True121 assert wait_for_message(p) == make_message(sub_type, keys[0], 1)122 # unsubscribe again123 unsub_func()124 assert p.subscribed is True125 # subscribe to another channel before reading the unsubscribe response126 sub_func(keys[1])127 assert p.subscribed is True128 # read the unsubscribe for key1129 assert wait_for_message(p) == make_message(unsub_type, keys[0], 0)130 # we're still subscribed to key2, so subscribed should still be True131 assert p.subscribed is True132 # read the key2 subscribe message133 assert wait_for_message(p) == make_message(sub_type, keys[1], 1)134 unsub_func()135 # haven't read the message yet, so we're still subscribed136 assert p.subscribed is True137 assert wait_for_message(p) == make_message(unsub_type, keys[1], 0)138 # now we're finally unsubscribed139 assert p.subscribed is False140 def test_subscribe_property_with_channels(self, r):141 kwargs = make_subscribe_test_data(r.pubsub(), 'channel')142 self._test_subscribed_property(**kwargs)143 def test_subscribe_property_with_patterns(self, r):144 kwargs = make_subscribe_test_data(r.pubsub(), 'pattern')145 self._test_subscribed_property(**kwargs)146 def test_ignore_all_subscribe_messages(self, r):147 p = r.pubsub(ignore_subscribe_messages=True)148 checks = (149 (p.subscribe, 'foo'),150 (p.unsubscribe, 'foo'),151 (p.psubscribe, 'f*'),152 (p.punsubscribe, 'f*'),153 )154 assert p.subscribed is False155 for func, channel in checks:156 assert func(channel) is None157 assert p.subscribed is True158 assert wait_for_message(p) is None159 assert p.subscribed is False160 def test_ignore_individual_subscribe_messages(self, r):161 p = r.pubsub()162 checks = (163 (p.subscribe, 'foo'),164 (p.unsubscribe, 'foo'),165 (p.psubscribe, 'f*'),166 (p.punsubscribe, 'f*'),167 )168 assert p.subscribed is False169 for func, channel in checks:170 assert func(channel) is None171 assert p.subscribed is True172 message = wait_for_message(p, ignore_subscribe_messages=True)173 assert message is None174 assert p.subscribed is False175class TestPubSubMessages(object):176 def setup_method(self, method):177 self.message = None178 def message_handler(self, message):179 self.message = message180 def test_published_message_to_channel(self, r):181 p = r.pubsub(ignore_subscribe_messages=True)182 p.subscribe('foo')183 assert r.publish('foo', 'test message') == 1184 message = wait_for_message(p)185 assert isinstance(message, dict)186 assert message == make_message('message', 'foo', 'test message')187 def test_published_message_to_pattern(self, r):188 p = r.pubsub(ignore_subscribe_messages=True)189 p.subscribe('foo')190 p.psubscribe('f*')191 # 1 to pattern, 1 to channel192 assert r.publish('foo', 'test message') == 2193 message1 = wait_for_message(p)194 message2 = wait_for_message(p)195 assert isinstance(message1, dict)196 assert isinstance(message2, dict)197 expected = [198 make_message('message', 'foo', 'test message'),199 make_message('pmessage', 'foo', 'test message', pattern='f*')200 ]201 assert message1 in expected202 assert message2 in expected203 assert message1 != message2204 def test_channel_message_handler(self, r):205 p = r.pubsub(ignore_subscribe_messages=True)206 p.subscribe(foo=self.message_handler)207 assert r.publish('foo', 'test message') == 1208 assert wait_for_message(p) is None209 assert self.message == make_message('message', 'foo', 'test message')210 def test_pattern_message_handler(self, r):211 p = r.pubsub(ignore_subscribe_messages=True)212 p.psubscribe(**{'f*': self.message_handler})213 assert r.publish('foo', 'test message') == 1214 assert wait_for_message(p) is None215 assert self.message == make_message('pmessage', 'foo', 'test message',216 pattern='f*')217 def test_unicode_channel_message_handler(self, r):218 p = r.pubsub(ignore_subscribe_messages=True)219 channel = u('uni') + unichr(4456) + u('code')220 channels = {channel: self.message_handler}221 p.subscribe(**channels)222 assert r.publish(channel, 'test message') == 1223 assert wait_for_message(p) is None224 assert self.message == make_message('message', channel, 'test message')225 def test_unicode_pattern_message_handler(self, r):226 p = r.pubsub(ignore_subscribe_messages=True)227 pattern = u('uni') + unichr(4456) + u('*')228 channel = u('uni') + unichr(4456) + u('code')229 p.psubscribe(**{pattern: self.message_handler})230 assert r.publish(channel, 'test message') == 1231 assert wait_for_message(p) is None232 assert self.message == make_message('pmessage', channel,233 'test message', pattern=pattern)234class TestPubSubAutoDecoding(object):235 "These tests only validate that we get unicode values back"236 channel = u('uni') + unichr(4456) + u('code')237 pattern = u('uni') + unichr(4456) + u('*')238 data = u('abc') + unichr(4458) + u('123')239 def make_message(self, type, channel, data, pattern=None):240 return {241 'type': type,242 'channel': channel,243 'pattern': pattern,244 'data': data245 }246 def setup_method(self, method):247 self.message = None248 def message_handler(self, message):249 self.message = message250 @pytest.fixture()251 def r(self, request):252 return _redis_client(request=request, decode_responses=True)253 def test_channel_subscribe_unsubscribe(self, r):254 p = r.pubsub()255 p.subscribe(self.channel)256 assert wait_for_message(p) == self.make_message('subscribe',257 self.channel, 1)258 p.unsubscribe(self.channel)259 assert wait_for_message(p) == self.make_message('unsubscribe',260 self.channel, 0)261 def test_pattern_subscribe_unsubscribe(self, r):262 p = r.pubsub()263 p.psubscribe(self.pattern)264 assert wait_for_message(p) == self.make_message('psubscribe',265 self.pattern, 1)266 p.punsubscribe(self.pattern)267 assert wait_for_message(p) == self.make_message('punsubscribe',268 self.pattern, 0)269 def test_channel_publish(self, r):270 p = r.pubsub(ignore_subscribe_messages=True)271 p.subscribe(self.channel)272 r.publish(self.channel, self.data)273 assert wait_for_message(p) == self.make_message('message',274 self.channel,275 self.data)276 def test_pattern_publish(self, r):277 p = r.pubsub(ignore_subscribe_messages=True)278 p.psubscribe(self.pattern)279 r.publish(self.channel, self.data)280 assert wait_for_message(p) == self.make_message('pmessage',281 self.channel,282 self.data,283 pattern=self.pattern)284 def test_channel_message_handler(self, r):285 p = r.pubsub(ignore_subscribe_messages=True)286 p.subscribe(**{self.channel: self.message_handler})287 r.publish(self.channel, self.data)288 assert wait_for_message(p) is None289 assert self.message == self.make_message('message', self.channel,290 self.data)291 # test that we reconnected to the correct channel292 p.connection.disconnect()293 assert wait_for_message(p) is None # should reconnect294 new_data = self.data + u('new data')295 r.publish(self.channel, new_data)296 assert wait_for_message(p) is None297 assert self.message == self.make_message('message', self.channel,298 new_data)299 def test_pattern_message_handler(self, r):300 p = r.pubsub(ignore_subscribe_messages=True)301 p.psubscribe(**{self.pattern: self.message_handler})302 r.publish(self.channel, self.data)303 assert wait_for_message(p) is None304 assert self.message == self.make_message('pmessage', self.channel,305 self.data,306 pattern=self.pattern)307 # test that we reconnected to the correct pattern308 p.connection.disconnect()309 assert wait_for_message(p) is None # should reconnect310 new_data = self.data + u('new data')311 r.publish(self.channel, new_data)312 assert wait_for_message(p) is None313 assert self.message == self.make_message('pmessage', self.channel,314 new_data,315 pattern=self.pattern)316class TestPubSubRedisDown(object):317 def test_channel_subscribe(self, r):318 r = redis.Redis(host='localhost', port=6390)319 p = r.pubsub()320 with pytest.raises(ConnectionError):...

Full Screen

Full Screen

window.test.js

Source:window.test.js Github

copy

Full Screen

...32 await server.start()33 //start the display34 let display = await new HeadlessDisplay(server.hostname, server.websocket_port)35 console.log("waiting for connected message")36 await display.wait_for_message(WINDOWS.TYPE_window_list)37 console.log("================")38 //start the test app39 let app = await start_testapp(server,async (app)=>{40 await app.send(WINDOWS.MAKE_WindowOpen({41 x:50,42 y:50,43 width:70,44 height:80,45 sender:app.id,46 window_type:'plain',47 }))48 })49 //wait for the app to receive it's open window50 log('waiting for open response')51 let open_msg = await app.wait_for_message(WINDOWS.TYPE_WindowOpenResponse)52 log("got the window open response",open_msg)53 assert.strictEqual(server.wids.has_window_id(open_msg.window),true)54 let win = server.wids.window_for_id(open_msg.window)55 assert.strictEqual(win.type,'root')56 assert.strictEqual(win.width,70)57 assert.strictEqual(win.height,80)58 {59 //set the focused window60 await server.send(WINDOWS.MAKE_SetFocusedWindow({window: open_msg.window}))61 await app.wait_for_message(WINDOWS.TYPE_SetFocusedWindow)62 log("app is now the focused window")63 }64 //move the window65 {66 await server.send(WINDOWS.MAKE_WindowSetPosition({67 window: open_msg.window,68 app: open_msg.target,69 x:100,70 y:100,71 }))72 let msg = await app.wait_for_message(WINDOWS.TYPE_WindowSetPosition)73 console.log("message was",msg)74 assert.strictEqual(msg.x,100)75 assert.strictEqual(msg.y,100)76 let win = server.wids.window_for_id(open_msg.window)77 log("now window is",win)78 assert.strictEqual(win.x,100)79 assert.strictEqual(win.y,100)80 }81 await server.shutdown()82 })83 it('uses the menu', async function() {84 // let applist = await load_applist("test/resources/good.applist.json")85 let applist = {86 system:[],87 user:[]88 }89 let server = new CentralServer({90 hostname:'127.0.0.1',91 websocket_port:8081,92 apps:applist,93 })94 try {95 await server.start()96 let display = await new HeadlessDisplay(server.hostname, server.websocket_port)97 await display.wait_for_message(GENERAL.TYPE_Connected)98 await display.send(GENERAL.MAKE_ScreenStart())99 await server.start_app({name: 'menubar', entrypoint: 'src/clients/menubar.js', args: []})100 await display.wait_for_message(DEBUG.TYPE_AppStarted)101 await display.wait_for_message(WINDOWS.TYPE_WindowOpenDisplay)102 let app = await start_testapp(server, async (app) => {103 app.ws.send(JSON.stringify(WINDOWS.MAKE_WindowOpen({104 x: 50,105 y: 50,106 width: 70,107 height: 80,108 sender: app.id,109 window_type: 'plain'110 })))111 app.on(WINDOWS.TYPE_SetFocusedWindow, () => {112 app.log("set focused window")113 let menu = {114 type: "root",115 children: [116 {117 type: 'top',118 label: 'App',119 children: [120 {121 type: 'item',122 label: 'pause',123 command: 'pause'124 },125 ]126 },127 ]128 }129 app.send(MENUS.MAKE_SetMenubar({menu: menu}))130 .then(() => {131 app.log("updating the menubar with ", menu)132 })133 })134 })135 await display.wait_for_message(DEBUG.TYPE_AppStarted)136 log("test app launched")137 {138 let open_msg = await app.wait_for_message(WINDOWS.TYPE_WindowOpenResponse)139 log("open message", open_msg)140 server.send(WINDOWS.MAKE_SetFocusedWindow({window: open_msg.window}))141 await app.wait_for_message(WINDOWS.TYPE_SetFocusedWindow)142 log("app is now the focused window")143 }144 await sleep(100)145 //send menubar input146 {147 await display.dispatch_mousedown({x: 5, y: 5})148 await sleep(100)149 await display.dispatch_mouseup({x: 5, y: 5})150 await display.wait_for_message(WINDOWS.TYPE_create_child_window_display)151 log("child window opened")152 }153 //now click on the menubar item154 {155 await display.dispatch_mousedown({x: 5, y: 25})156 await display.dispatch_mouseup({x: 5, y: 25})157 await app.wait_for_message(INPUT.TYPE_Action)158 log("action sent to app")159 }160 //start menubar161 await server.shutdown()162 } catch (e) {163 console.log(e)164 await server.shutdown()165 }166 })167})168describe("textboxes",function() {169 it("sends keyboard events",async function () {170 let applist = {171 system:[],172 user:[]173 }174 let server = new CentralServer({175 hostname:'127.0.0.1',176 websocket_port:8081,177 apps:applist,178 })179 try {180 await server.start()181 let display = await new HeadlessDisplay(server.hostname, server.websocket_port)182 await display.wait_for_message(GENERAL.TYPE_Connected)183 await display.send(GENERAL.MAKE_ScreenStart())184 let app = await start_testapp(server, async (app) => {185 await app.send(WINDOWS.MAKE_WindowOpen({186 x: 50,187 y: 50,188 width: 70,189 height: 80,190 sender: app.id,191 window_type: 'plain'192 }))193 })194 //wait for the app to receive it's open window195 let open_msg = await app.wait_for_message(WINDOWS.TYPE_WindowOpenResponse)196 await display.dispatch_keydown_to_window(open_msg.window, INFO.KEY_NAMES.Enter, INFO.KEY_NAMES.Enter)197 let msg = await app.wait_for_message(INPUT.TYPE_KeyboardDown)198 assert.deepStrictEqual(msg, {199 type: INPUT.TYPE_KeyboardDown,200 code: INFO.KEY_NAMES.Enter,201 key: INFO.KEY_NAMES.Enter,202 shift: false,203 app: app.id,204 window: open_msg.window205 }206 )207 await server.shutdown()208 } catch (e) {209 console.log(e)210 await server.shutdown()211 }212 })213 it("types text",async function() {214 let applist = {215 system:[],216 user:[]217 }218 let server = new CentralServer({219 hostname:'127.0.0.1',220 websocket_port:8081,221 apps:applist,222 })223 try {224 await server.start()225 let display = await start_headless_display()226 await display.wait_for_message(GENERAL.TYPE_Connected)227 await display.send(GENERAL.MAKE_ScreenStart())228 let app = await start_testguiapp(server, async (wrapper) => {229 let main_window = await wrapper.app.open_window(0, 0, 100, 120, 'plain')230 main_window.root = new TextBox({text: "hello"})231 main_window.redraw()232 })233 //wait for the app window to fully open234 let open_msg = await app.wait_for_message(WINDOWS.TYPE_WindowOpenResponse)235 assert.strictEqual(app.app.windows[0].root.text, 'hello')236 await sleep(500)237 log("sleept")238 // assert.strictEqual(app.app.windows)239 //send a keyboard event to the focused component240 let win_move = WINDOWS.MAKE_WindowSetPosition({241 window: open_msg.window,242 app: open_msg.target,243 x: 0,244 y: 0,245 })246 display.handle(win_move)247 display.send(win_move)248 await app.wait_for_message(WINDOWS.TYPE_WindowSetPosition)249 await display.dispatch_mousedown({x: 10, y: 10})250 await app.wait_for_message(INPUT.TYPE_MouseDown)251 await display.dispatch_keydown_to_window(open_msg.window, INFO.KEY_NAMES.KeyA, "a")252 let msg = await app.wait_for_message(INPUT.TYPE_KeyboardDown)253 assert.strictEqual(app.app.windows[0].root.text, 'helloa')254 log("yay. the text box is now helloa")255 await server.shutdown()256 } catch (e) {257 console.log(e)258 await server.shutdown()259 }260 })...

Full Screen

Full Screen

ros_bridge_client.py

Source:ros_bridge_client.py Github

copy

Full Screen

...32 """33 Tests clock34 """35 rospy.init_node('test_node', anonymous=True)36 clock_msg = rospy.wait_for_message("/clock", Clock, timeout=TIMEOUT)37 self.assertNotEqual(Clock(), clock_msg)38 def test_vehicle_status(self):39 """40 Tests vehicle_status41 """42 rospy.init_node('test_node', anonymous=True)43 msg = rospy.wait_for_message(44 "/carla/ego_vehicle/vehicle_status", CarlaEgoVehicleStatus, timeout=TIMEOUT)45 self.assertNotEqual(msg.header, Header()) # todo: check frame-id46 self.assertNotEqual(msg.orientation, Quaternion())47 def test_vehicle_info(self):48 """49 Tests vehicle_info50 """51 rospy.init_node('test_node', anonymous=True)52 msg = rospy.wait_for_message(53 "/carla/ego_vehicle/vehicle_info", CarlaEgoVehicleInfo, timeout=TIMEOUT)54 self.assertNotEqual(msg.id, 0)55 self.assertEqual(msg.type, "vehicle.tesla.model3")56 self.assertEqual(msg.rolename, "ego_vehicle")57 self.assertEqual(len(msg.wheels), 4)58 self.assertNotEqual(msg.max_rpm, 0.0)59 self.assertNotEqual(msg.moi, 0.0)60 self.assertNotEqual(msg.damping_rate_full_throttle, 0.0)61 self.assertNotEqual(msg.damping_rate_zero_throttle_clutch_engaged, 0.0)62 self.assertNotEqual(63 msg.damping_rate_zero_throttle_clutch_disengaged, 0.0)64 self.assertTrue(msg.use_gear_autobox)65 self.assertNotEqual(msg.gear_switch_time, 0.0)66 self.assertNotEqual(msg.mass, 0.0)67 self.assertNotEqual(msg.clutch_strength, 0.0)68 self.assertNotEqual(msg.drag_coefficient, 0.0)69 self.assertNotEqual(msg.center_of_mass, Vector3())70 def test_odometry(self):71 """72 Tests Odometry73 """74 rospy.init_node('test_node', anonymous=True)75 msg = rospy.wait_for_message(76 "/carla/ego_vehicle/odometry", Odometry, timeout=TIMEOUT)77 self.assertEqual(msg.header.frame_id, "map")78 self.assertEqual(msg.child_frame_id, "ego_vehicle")79 self.assertNotEqual(msg.pose, Pose())80 def test_gnss(self):81 """82 Tests Gnss83 """84 rospy.init_node('test_node', anonymous=True)85 msg = rospy.wait_for_message(86 "/carla/ego_vehicle/gnss/gnss1/fix", NavSatFix, timeout=TIMEOUT)87 self.assertEqual(msg.header.frame_id, "ego_vehicle/gnss/gnss1")88 self.assertNotEqual(msg.latitude, 0.0)89 self.assertNotEqual(msg.longitude, 0.0)90 self.assertNotEqual(msg.altitude, 0.0)91 def test_imu(self):92 """93 Tests IMU sensor node94 """95 rospy.init_node('test_node', anonymous=True)96 msg = rospy.wait_for_message("/carla/ego_vehicle/imu", Imu, timeout=15)97 self.assertEqual(msg.header.frame_id, "ego_vehicle/imu")98 self.assertNotEqual(msg.linear_acceleration, 0.0)99 self.assertNotEqual(msg.angular_velocity, 0.0)100 self.assertNotEqual(msg.orientation, 0.0)101 def test_camera_info(self):102 """103 Tests camera_info104 """105 rospy.init_node('test_node', anonymous=True)106 msg = rospy.wait_for_message(107 "/carla/ego_vehicle/camera/rgb/front/camera_info", CameraInfo, timeout=TIMEOUT)108 self.assertEqual(msg.header.frame_id, "ego_vehicle/camera/rgb/front")109 self.assertEqual(msg.height, 600)110 self.assertEqual(msg.width, 800)111 def test_camera_image(self):112 """113 Tests camera_images114 """115 rospy.init_node('test_node', anonymous=True)116 msg = rospy.wait_for_message(117 "/carla/ego_vehicle/camera/rgb/front/image_color", Image, timeout=TIMEOUT)118 self.assertEqual(msg.header.frame_id, "ego_vehicle/camera/rgb/front")119 self.assertEqual(msg.height, 600)120 self.assertEqual(msg.width, 800)121 self.assertEqual(msg.encoding, "bgra8")122 def test_dvs_camera_info(self):123 """124 Tests dvs camera info125 """126 rospy.init_node('test_node', anonymous=True)127 msg = rospy.wait_for_message(128 "/carla/ego_vehicle/camera/dvs/front/camera_info", CameraInfo, timeout=TIMEOUT)129 self.assertEqual(msg.header.frame_id, "ego_vehicle/camera/dvs/front")130 self.assertEqual(msg.height, 600)131 self.assertEqual(msg.width, 800)132 def test_dvs_camera_image(self):133 """134 Tests dvs camera images135 """136 rospy.init_node('test_node', anonymous=True)137 msg = rospy.wait_for_message(138 "/carla/ego_vehicle/camera/dvs/front/image_events", Image, timeout=TIMEOUT)139 self.assertEqual(msg.header.frame_id, "ego_vehicle/camera/dvs/front")140 self.assertEqual(msg.height, 600)141 self.assertEqual(msg.width, 800)142 self.assertEqual(msg.encoding, "bgr8")143 def test_dvs_camera_events(self):144 """145 Tests dvs camera events146 """147 rospy.init_node('test_node', anonymous=True)148 msg = rospy.wait_for_message(149 "/carla/ego_vehicle/camera/dvs/front/events", PointCloud2, timeout=TIMEOUT)150 self.assertEqual(msg.header.frame_id, "ego_vehicle/camera/dvs/front")151 def test_lidar(self):152 """153 Tests Lidar sensor node154 """155 rospy.init_node('test_node', anonymous=True)156 msg = rospy.wait_for_message(157 "/carla/ego_vehicle/lidar/lidar1/point_cloud", PointCloud2, timeout=TIMEOUT)158 self.assertEqual(msg.header.frame_id, "ego_vehicle/lidar/lidar1")159 def test_semantic_lidar(self):160 """161 Tests semantic_lidar sensor node162 """163 rospy.init_node('test_node', anonymous=True)164 msg = rospy.wait_for_message(165 "/carla/ego_vehicle/semantic_lidar/lidar1/point_cloud", PointCloud2, timeout=TIMEOUT)166 self.assertEqual(msg.header.frame_id, "ego_vehicle/semantic_lidar/lidar1")167 def test_radar(self):168 """169 Tests Radar sensor node170 """171 rospy.init_node('test_node', anonymous=True)172 msg = rospy.wait_for_message(173 "/carla/ego_vehicle/radar/front/radar_points", PointCloud2, timeout=TIMEOUT)174 self.assertEqual(msg.header.frame_id, "ego_vehicle/radar/front")175 def test_ego_vehicle_objects(self):176 """177 Tests objects node for ego_vehicle178 """179 rospy.init_node('test_node', anonymous=True)180 msg = rospy.wait_for_message(181 "/carla/ego_vehicle/objects", ObjectArray, timeout=15)182 self.assertEqual(msg.header.frame_id, "map")183 self.assertEqual(len(msg.objects), 0)184 def test_objects(self):185 """186 Tests carla objects187 """188 rospy.init_node('test_node', anonymous=True)189 msg = rospy.wait_for_message("/carla/objects", ObjectArray, timeout=TIMEOUT)190 self.assertEqual(msg.header.frame_id, "map")191 self.assertEqual(len(msg.objects), 1) # only ego vehicle exists192 def test_marker(self):193 """194 Tests marker195 """196 rospy.init_node('test_node', anonymous=True)197 msg = rospy.wait_for_message("/carla/marker", Marker, timeout=TIMEOUT)198 self.assertEqual(msg.header.frame_id, "ego_vehicle")199 self.assertNotEqual(msg.id, 0)200 self.assertEqual(msg.type, 1)201 self.assertNotEqual(msg.pose, Pose())202 self.assertNotEqual(msg.scale, Vector3())203 self.assertEqual(msg.color.r, 0.0)204 self.assertEqual(msg.color.g, 255.0)205 self.assertEqual(msg.color.b, 0.0)206 def test_world_info(self):207 """208 Tests world_info209 """210 rospy.init_node('test_node', anonymous=True)211 msg = rospy.wait_for_message(212 "/carla/world_info", CarlaWorldInfo, timeout=TIMEOUT)213 self.assertNotEqual(len(msg.map_name), 0)214 self.assertNotEqual(len(msg.opendrive), 0)215 def test_actor_list(self):216 """217 Tests actor_list218 """219 rospy.init_node('test_node', anonymous=True)220 msg = rospy.wait_for_message(221 "/carla/actor_list", CarlaActorList, timeout=TIMEOUT)222 self.assertNotEqual(len(msg.actors), 0)223 def test_traffic_lights(self):224 """225 Tests traffic_lights226 """227 rospy.init_node('test_node', anonymous=True)228 msg = rospy.wait_for_message(229 "/carla/traffic_lights", CarlaTrafficLightStatusList, timeout=TIMEOUT)230 self.assertNotEqual(len(msg.traffic_lights), 0)231 def test_traffic_lights_info(self):232 """233 Tests traffic_lights234 """235 rospy.init_node('test_node', anonymous=True)236 msg = rospy.wait_for_message(237 "/carla/traffic_lights_info", CarlaTrafficLightInfoList, timeout=TIMEOUT)238 self.assertNotEqual(len(msg.traffic_lights), 0)239if __name__ == '__main__':...

Full Screen

Full Screen

jelly-bf-processhandler.js

Source:jelly-bf-processhandler.js Github

copy

Full Screen

...13 14};15JellyBFProcessHandler.prototype.initialize=function(callback){16 this.worker=new Worker("jelly-bf-worker.max.js");17 wait_for_message(this.worker,"ready",function(message){18 callback();19 });20};21JellyBFProcessHandler.prototype.compile=function(sourcecode,options,callback){22 if(options.debug){23 callback({success:true});24 }25 else{26 this.worker.postMessage({type:"compile",sourcecode:sourcecode,options:options});27 wait_for_message(this.worker,"compiled",function(message){28 callback({success:true});29 });30 wait_for_message(this.worker,"compileerror",function(message){31 callback({success:false});32 });33 }34};35JellyBFProcessHandler.prototype.execute=function(inputstr,options,callback){36 if(options.debug){37 38 }39 else{40 var encodedinput=new TextEncoder().encode(inputstr);41 this.worker.postMessage({type:"execute",inputuint8array:encodedinput,options:options},[encodedinput.buffer]);42 wait_for_message(this.worker,"executed",function(message){43 callback({success:true,output:new TextDecoder().decode(message.outputuint8array)});44 });45 wait_for_message(this.worker,"executeerror",function(message){46 callback({success:false});47 });48 }49};50JellyBFProcessHandler.prototype.executeInteractive=function(options,inputRequestCallback,outputCallback,doneCallback,pausedCallback){51 var WaitArrayId={52 READ_HEAD:0,53 WRITE_HEAD:1,54 TERMINATED_FLAG:255 };56 57 options.bufferlength=options.bufferlength||1024;58 59 60 var inputBuffer=new SharedArrayBuffer(1024);61 var outputBuffer=new SharedArrayBuffer(1024);62 var inputWaitBuffer=new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT);63 var outputWaitBuffer=new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT);64 65 var pendingInputData=[];//{data:typedarray,ptrdone:integer}66 var inputTimeout=undefined;67 68 var inputuint8array=new Uint8Array(inputBuffer);69 var outputuint8array=new Uint8Array(outputBuffer);70 var inputwaitint32array=new Int32Array(inputWaitBuffer);71 var outputwaitint32array=new Int32Array(outputWaitBuffer);72 73 74 var output_read_head=0,output_write_head=0,output_terminated=false; // cache values75 76 var outputUpdated=function(){77 output_write_head=Atomics.load(outputwaitint32array,WaitArrayId.WRITE_HEAD);78 output_terminated=(Atomics.load(outputwaitint32array,WaitArrayId.TERMINATED_FLAG)!==0);79 if(output_terminated){80 output_write_head=Atomics.load(outputwaitint32array,WaitArrayId.WRITE_HEAD);81 }82 var newData;83 if(output_terminated){84 newData=new Uint8Array(output_write_head-1-output_read_head);85 for(var i=output_read_head;i<output_write_head-1;++i){86 newData[i-output_read_head]=Atomics.load(outputuint8array,i%options.bufferlength);87 }88 output_read_head=output_write_head-1;89 }90 else{91 newData=new Uint8Array(output_write_head-output_read_head);92 for(var i=output_read_head;i<output_write_head;++i){93 newData[i-output_read_head]=Atomics.load(outputuint8array,i%options.bufferlength);94 }95 output_read_head=output_write_head;96 }97 Atomics.store(outputwaitint32array,WaitArrayId.READ_HEAD,output_read_head);98 Atomics.notify(outputwaitint32array,WaitArrayId.READ_HEAD,1);99 var newText=new TextDecoder().decode(newData);100 outputCallback(newText);101 };102 103 104 var input_read_head=0,input_write_head=0,input_terminated=false; // cache values105 106 var inputAdded=function(text){107 var newData=new TextEncoder().encode(text);108 pendingInputData.push({data:newData,ptrdone:0});109 110 111 if(!inputTimeout)do_input();112 };113 114 var do_input=function(){115 inputTimeout=undefined;116 117 if(pendingInputData.length===0)return;118 119 input_read_head=Atomics.load(inputwaitint32array,WaitArrayId.READ_HEAD);120 while(pendingInputData[0].ptrdone<pendingInputData[0].data.length&&input_read_head+options.bufferlength>input_write_head){121 Atomics.store(inputuint8array,(input_write_head++)%options.bufferlength,pendingInputData[0].data[pendingInputData[0].ptrdone++]);122 }123 if(pendingInputData[0].ptrdone===pendingInputData[0].data.length){124 pendingInputData.shift();125 }126 Atomics.store(inputwaitint32array,WaitArrayId.WRITE_HEAD,input_write_head);127 console.log(Atomics.notify(inputwaitint32array,WaitArrayId.WRITE_HEAD,1));128 129 if(pendingInputData.length>0){130 inputTimeout=setTimeout(do_input,40);131 }132 };133 134 var inputRequested=function(read_head){135 do_input();136 if(input_write_head===read_head){137 inputRequestCallback();138 }139 };140 141 142 var outputUpdatedHandler=function(e){143 if(e.data.type==="output-updated"){144 outputUpdated();145 }146 else if(e.data.type==="input-requested"){147 inputRequested(e.data.readhead);148 }149 };150 151 this.worker.addEventListener("message",outputUpdatedHandler);152 153 if(options.debug){154 var that=this;155 var sourcecode=options.sourcecode;156 var breakpointBuffer=options.breakpointBuffer;157 var globalpauseBuffer=options.globalPauseBuffer;158 delete options.sourcecode;159 delete options.breakpointBuffer;160 delete options.globalPauseBuffer;161 162 var memoryBuffer=new SharedArrayBuffer(30000);163 164 var resumer=function(){165 that.worker.postMessage({type:"interpret-continue"});166 };167 168 var interpretHandler=function(e){169 if(e.data.type==="interpret-breakpoint"){170 pausedCallback({breakpoint:true,resume:resumer,index:e.data.index,memoryuint8array:new Uint8Array(memoryBuffer),memory_ptr:e.data.memory_ptr});171 }172 else if(e.data.type==="interpret-paused"){173 pausedCallback({breakpoint:false,resume:resumer,index:e.data.index,memoryuint8array:new Uint8Array(memoryBuffer),memory_ptr:e.data.memory_ptr});174 }175 };176 177 this.worker.addEventListener("message",interpretHandler);178 179 wait_for_message(this.worker,"parsecomplete",function(message){180 resumer();181 });182 183 wait_for_message(this.worker,"parseerror",function(message){184 that.worker.removeEventListener("message",interpretHandler);185 that.worker.removeEventListener("message",outputUpdatedHandler);186 doneCallback({success:false,data:message});187 });188 wait_for_message(this.worker,"runtimeerror",function(message){189 that.worker.removeEventListener("message",interpretHandler);190 that.worker.removeEventListener("message",outputUpdatedHandler);191 doneCallback({success:false,data:message});192 });193 194 wait_for_message(this.worker,"interpreted",function(message){195 that.worker.removeEventListener("message",interpretHandler);196 that.worker.removeEventListener("message",outputUpdatedHandler);197 doneCallback({success:true});198 });199 wait_for_message(this.worker,"interpreterror",function(message){200 that.worker.removeEventListener("message",interpretHandler);201 that.worker.removeEventListener("message",outputUpdatedHandler);202 doneCallback({success:false});203 });204 205 this.worker.postMessage({type:"interpret-interactive",sourcecode:sourcecode,inputbuffer:inputBuffer,outputbuffer:outputBuffer,inputwaitbuffer:inputWaitBuffer,outputwaitbuffer:outputWaitBuffer,breakpointbuffer:breakpointBuffer,globalpausebuffer:globalpauseBuffer,memorybuffer:memoryBuffer,options:options});206 }207 else{208 var that=this;209 wait_for_message(this.worker,"executed",function(message){210 that.worker.removeEventListener("message",outputUpdatedHandler);211 doneCallback({success:true});212 });213 wait_for_message(this.worker,"executeerror",function(message){214 that.worker.removeEventListener("message",outputUpdatedHandler);215 doneCallback({success:false});216 });217 this.worker.postMessage({type:"execute-interactive",inputbuffer:inputBuffer,outputbuffer:outputBuffer,inputwaitbuffer:inputWaitBuffer,outputwaitbuffer:outputWaitBuffer,options:options});218 }219 220 return {inputAddedCallback:inputAdded};221};222JellyBFProcessHandler.prototype.terminate=function(){223 this.worker.terminate();224};...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run testcontainers-python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful