Best Python code snippet using playwright-python
test_receive_async.py
Source:test_receive_async.py
...24 assert list(received[-1].body)[0] == b"Receiving only a single event"25 except:26 raise27 finally:28 await client.stop_async()29@pytest.mark.asyncio30async def test_receive_with_offset_async(connstr_senders):31 connection_str, senders = connstr_senders32 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)33 receiver = client.add_async_receiver("$default", "0", offset=Offset('@latest'))34 await client.run_async()35 try:36 received = await receiver.receive(timeout=5)37 assert len(received) == 038 senders[0].send(EventData(b"Data"))39 time.sleep(1)40 received = await receiver.receive(timeout=3)41 assert len(received) == 142 offset = received[0].offset43 offset_receiver = client.add_async_receiver("$default", "0", offset=offset)44 await client.run_async()45 received = await offset_receiver.receive(timeout=5)46 assert len(received) == 047 senders[0].send(EventData(b"Message after offset"))48 received = await offset_receiver.receive(timeout=5)49 assert len(received) == 150 except:51 raise52 finally:53 await client.stop_async()54@pytest.mark.asyncio55async def test_receive_with_inclusive_offset_async(connstr_senders):56 connection_str, senders = connstr_senders57 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)58 receiver = client.add_async_receiver("$default", "0", offset=Offset('@latest'))59 await client.run_async()60 try:61 received = await receiver.receive(timeout=5)62 assert len(received) == 063 senders[0].send(EventData(b"Data"))64 time.sleep(1)65 received = await receiver.receive(timeout=5)66 assert len(received) == 167 offset = received[0].offset68 offset_receiver = client.add_async_receiver("$default", "0", offset=Offset(offset.value, inclusive=True))69 await client.run_async()70 received = await offset_receiver.receive(timeout=5)71 assert len(received) == 172 except:73 raise74 finally:75 await client.stop_async()76@pytest.mark.asyncio77async def test_receive_with_datetime_async(connstr_senders):78 connection_str, senders = connstr_senders79 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)80 receiver = client.add_async_receiver("$default", "0", offset=Offset('@latest'))81 await client.run_async()82 try:83 received = await receiver.receive(timeout=5)84 assert len(received) == 085 senders[0].send(EventData(b"Data"))86 received = await receiver.receive(timeout=5)87 assert len(received) == 188 offset = received[0].enqueued_time89 offset_receiver = client.add_async_receiver("$default", "0", offset=Offset(offset))90 await client.run_async()91 received = await offset_receiver.receive(timeout=5)92 assert len(received) == 093 senders[0].send(EventData(b"Message after timestamp"))94 time.sleep(1)95 received = await offset_receiver.receive(timeout=5)96 assert len(received) == 197 except:98 raise99 finally:100 await client.stop_async()101@pytest.mark.asyncio102async def test_receive_with_sequence_no_async(connstr_senders):103 connection_str, senders = connstr_senders104 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)105 receiver = client.add_async_receiver("$default", "0", offset=Offset('@latest'))106 await client.run_async()107 try:108 received = await receiver.receive(timeout=5)109 assert len(received) == 0110 senders[0].send(EventData(b"Data"))111 received = await receiver.receive(timeout=5)112 assert len(received) == 1113 offset = received[0].sequence_number114 offset_receiver = client.add_async_receiver("$default", "0", offset=Offset(offset))115 await client.run_async()116 received = await offset_receiver.receive(timeout=5)117 assert len(received) == 0118 senders[0].send(EventData(b"Message next in sequence"))119 time.sleep(1)120 received = await offset_receiver.receive(timeout=5)121 assert len(received) == 1122 except:123 raise124 finally:125 await client.stop_async()126@pytest.mark.asyncio127async def test_receive_with_inclusive_sequence_no_async(connstr_senders):128 connection_str, senders = connstr_senders129 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)130 receiver = client.add_async_receiver("$default", "0", offset=Offset('@latest'))131 await client.run_async()132 try:133 received = await receiver.receive(timeout=5)134 assert len(received) == 0135 senders[0].send(EventData(b"Data"))136 received = await receiver.receive(timeout=5)137 assert len(received) == 1138 offset = received[0].sequence_number139 offset_receiver = client.add_async_receiver("$default", "0", offset=Offset(offset, inclusive=True))140 await client.run_async()141 received = await offset_receiver.receive(timeout=5)142 assert len(received) == 1143 except:144 raise145 finally:146 await client.stop_async()147@pytest.mark.asyncio148async def test_receive_batch_async(connstr_senders):149 connection_str, senders = connstr_senders150 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)151 receiver = client.add_async_receiver("$default", "0", prefetch=500, offset=Offset('@latest'))152 await client.run_async()153 try:154 received = await receiver.receive(timeout=5)155 assert len(received) == 0156 for i in range(10):157 senders[0].send(EventData(b"Data"))158 received = await receiver.receive(max_batch_size=5, timeout=5)159 assert len(received) == 5160 except:161 raise162 finally:163 await client.stop_async()164async def pump(receiver, sleep=None):165 messages = 0166 count = 0167 if sleep:168 await asyncio.sleep(sleep)169 batch = await receiver.receive(timeout=10)170 while batch:171 count += 1172 if count >= 10:173 break174 messages += len(batch)175 batch = await receiver.receive(timeout=10)176 return messages177@pytest.mark.asyncio178async def test_epoch_receiver_async(connstr_senders):179 connection_str, senders = connstr_senders180 senders[0].send(EventData(b"Receiving only a single event"))181 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)182 receivers = []183 for epoch in [10, 20]:184 receivers.append(client.add_async_epoch_receiver("$default", "0", epoch, prefetch=5))185 try:186 await client.run_async()187 outputs = await asyncio.gather(188 pump(receivers[0]),189 pump(receivers[1]),190 return_exceptions=True)191 assert isinstance(outputs[0], EventHubError)192 assert outputs[1] == 1193 except:194 raise195 finally:196 await client.stop_async()197@pytest.mark.asyncio198async def test_multiple_receiver_async(connstr_senders):199 connection_str, senders = connstr_senders200 senders[0].send(EventData(b"Receiving only a single event"))201 client = EventHubClientAsync.from_connection_string(connection_str, debug=True)202 partitions = await client.get_eventhub_info_async()203 assert partitions["partition_ids"] == ["0", "1"]204 receivers = []205 for i in range(2):206 receivers.append(client.add_async_receiver("$default", "0", prefetch=10))207 try:208 await client.run_async()209 more_partitions = await client.get_eventhub_info_async()210 assert more_partitions["partition_ids"] == ["0", "1"]211 outputs = await asyncio.gather(212 pump(receivers[0]),213 pump(receivers[1]),214 return_exceptions=True)215 assert isinstance(outputs[0], int) and outputs[0] == 1216 assert isinstance(outputs[1], int) and outputs[1] == 1217 except:218 raise219 finally:220 await client.stop_async()221@pytest.mark.asyncio222async def test_epoch_receiver_after_non_epoch_receiver_async(connstr_senders):223 connection_str, senders = connstr_senders224 senders[0].send(EventData(b"Receiving only a single event"))225 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)226 receivers = []227 receivers.append(client.add_async_receiver("$default", "0", prefetch=10))228 receivers.append(client.add_async_epoch_receiver("$default", "0", 15, prefetch=10))229 try:230 await client.run_async()231 outputs = await asyncio.gather(232 pump(receivers[0]),233 pump(receivers[1], sleep=5),234 return_exceptions=True)235 assert isinstance(outputs[0], EventHubError)236 assert isinstance(outputs[1], int) and outputs[1] == 1237 except:238 raise239 finally:240 await client.stop_async()241@pytest.mark.asyncio242async def test_non_epoch_receiver_after_epoch_receiver_async(connstr_senders):243 connection_str, senders = connstr_senders244 senders[0].send(EventData(b"Receiving only a single event"))245 client = EventHubClientAsync.from_connection_string(connection_str, debug=False)246 receivers = []247 receivers.append(client.add_async_epoch_receiver("$default", "0", 15, prefetch=10))248 receivers.append(client.add_async_receiver("$default", "0", prefetch=10))249 try:250 await client.run_async()251 outputs = await asyncio.gather(252 pump(receivers[0]),253 pump(receivers[1]),254 return_exceptions=True)255 assert isinstance(outputs[1], EventHubError)256 assert isinstance(outputs[0], int) and outputs[0] == 1257 except:258 raise259 finally:...
capturer.py
Source:capturer.py
...47 Resets all settings so recordings will be lost48 '''49 if self._started:50 # we need to stop before starting a new one51 self.stop_async()52 self._started = True53 self._ret, self._frame = self._get_feed()54 self._img_shape = self._frame.shape55 self._recording = False56 self._record_buffer = None57 self._record_id = None58 self.thread = threading.Thread(target=self._update,59 args=(),60 daemon=True)61 self.thread.start()62 def _update(self):63 '''Asynchronous reading of frames from camera, handles recording to buffer64 '''65 while self._started:66 ret, frame = self._get_feed()67 with self._lock:68 self._ret = ret69 self._frame = frame70 if self._recording:71 if self._record_id < len(self._record_buffer):72 self._record_buffer[self._record_id] = frame.copy()73 self._record_id += 174 else:75 self._recording = False76 time.sleep(1./self._frame_rate)77 def start_recording(self, duration):78 '''Begins recording frames from camera79 Any existing recording will be ended and immediately overwritten. The80 number of frames taken is based on the frame rate81 Parameters82 ----------83 duration: float84 Seconds of recording to take85 '''86 self.end_recording()87 n_frames = self._frame_rate * duration88 self._record_buffer = np.empty((n_frames, *self._img_shape),89 dtype=np.uint8)90 self._record_id = 091 with self._lock:92 self._recording = True93 def end_recording(self):94 '''Stops recording frames in during thread update95 '''96 with self._lock:97 self._recording = False98 def is_recording(self):99 '''Checks if thread is recording frames100 Returns101 -------102 bool103 True if currently recording frames in thread, False otherwise104 '''105 with self._lock:106 is_recording = self._recording107 return is_recording108 def get_recording(self):109 '''Returns recorded frames if recording is over. Returns None if recording110 still in progress.111 Returns112 -------113 ndarray114 sequence of images115 '''116 with self._lock:117 recording = self._record_buffer.copy()118 return recording119 def read(self):120 '''Reads last frame from camera121 Returns None if camera failed to return a frame.122 Returns123 -------124 ndarray125 sequence of images126 '''127 if self._started:128 with self._lock:129 ret = self._ret130 frame = self._frame.copy()131 else:132 ret, frame = self._get_feed()133 if ret:134 return self.undistort_frame(frame)135 return None136 def _get_feed(self):137 return self._cap.read()138 def set_frame_rate(self, frame_rate):139 '''Changes frame rate used by asynchronous thread140 Parameters141 ----------142 frame_rate: int143 Number of frames to capture per second144 '''145 with self._lock:146 self._frame_rate = frame_rate147 def stop_async(self):148 '''Closes thread that captures frames asynchronously149 '''150 if self._started:151 self._started = False152 self._recording = False153 self.thread.join()154 def __call__(self):155 return self.read()156 def release(self):157 '''Closes connection to current camera if it is open158 '''159 self.stop_async()160 if self._cap is not None and self._cap.isOpened():161 self._cap.release()162 def __del__(self):163 self.release()164 @staticmethod165 def undistort_frame(frame):166 rx, ry, rw, rh = constants.NEW_CAM_ROI167 new_frame = cv2.undistort(frame,168 constants.CAM_MTX,169 constants.CAM_DIST_COEFFS,170 None,171 constants.NEW_CAM_MTX,172 )[ry:ry+rh, rx:rx+rw]173 return new_frame174class SimCapturer(Capturer):175 def __init__(self, pose_mtx=None, pb_client=0):176 '''Class to allow asynchronous video capture within pybullet simulator177 Parameters178 ----------179 view_mtx : array_like, optional180 4x4 view matrix that describes location of camera in world frame.181 If not provided, the default camera pose (from nuro_arm.constants)182 will be used183 pb_client : int, default to 0184 Physics Client ID describing which simulator the camera exists185 within. If you are only using one simulator, you can leave as186 default.187 '''188 super().__init__()189 # create projection matrix190 self._img_width, self._img_height = constants.NEW_CAM_ROI[2:]191 fov = np.degrees(2 * np.arctan2(self._img_height, 2 * constants.NEW_CAM_MTX[1,1]))192 aspect = self._img_width / self._img_height193 self._proj_mtx = pb.computeProjectionMatrixFOV(fov, aspect, 0.001, 10)194 # create view matrix195 self._view_mtx = self.get_view_matrix_from_pose(pose_mtx)196 self._pb_client = pb_client197 def set_pose_mtx(self, pose_mtx):198 self._view_mtx = self.get_view_matrix_from_pose(pose_mtx)199 def get_view_matrix_from_pose(self, pose_mtx=None):200 '''Convert from pose matrix to view matrix suitable for pybullet render201 Parameters202 ----------203 pose_mtx : array_like, optional204 4x4 pose matrix that describes location of205 camera in world frame. If not provided, the default camera pose206 (from nuro_arm.constants) will be used207 '''208 if pose_mtx is None:209 print('[WARNING:] no pose matrix specified for simulated camera. '210 'Camera will be placed in default location.')211 pose_mtx = constants.DEFAULT_CAM_POSE_MTX212 vecs = np.array(((0,0,0), (0,0,1), (0,-1,0)))213 eye_pos, target_pos, up_vec = tfm.apply_transformation(pose_mtx, vecs)214 view_mtx = pb.computeViewMatrix(eye_pos, target_pos, up_vec)215 return view_mtx216 def _get_feed(self):217 ret = True218 img = pb.getCameraImage(width=self._img_width,219 height=self._img_height,220 viewMatrix=self._view_mtx,221 projectionMatrix=self._proj_mtx,222 renderer=pb.ER_TINY_RENDERER,223 physicsClientId=self._pb_client224 )[2][...,:3]225 return ret, img226 def set_camera_id(self, camera_id=0, run_async=True):227 self.release()228 if run_async:229 self.start_async()230 return True231 def release(self):232 '''Closes connection to current camera if it is open233 '''234 self.stop_async()235 @staticmethod236 def undistort_frame(frame):237 '''simulator already provides undistorted images'''...
pdthread.py
Source:pdthread.py
...80 logger.info(81 "%s changed interval_secs to %s"82 % (self.get_name(), interval_secs)83 )84 def stop_async(self):85 "Ask a task to exit early from a tick()."86 self._stop = True87 def get_name(self):88 # Override this method to implement a custom name89 return self.__class__.__name__90 def get_interval_secs(self):91 return self._interval_secs92 def is_absolute(self):93 return self._is_absolute94 def is_stop_invoked(self):95 return self._stop96class RepeatingTaskThread(Thread):97 """98 A thread that runs a RepeatingTask.99 To use:100 - create an instance wrapping your task101 - call start() to start the thread102 Notes:103 - the first call to tick() will happen as soon as you start the thread104 - the task's interval_secs is sampled just after the end of a tick()105 Handling of is_absolute=True:106 If a call to tick() takes longer than interval_secs, the next call will107 happen immediately. If a call takes long enough that more than one call is108 overdue, the extra missed calls are lost. In all overdue cases, clock109 alignment will be lost. See implementation and unit tests for details.110 """111 def __init__(self, repeating_task):112 assert isinstance(repeating_task, RepeatingTask)113 Thread.__init__(self, name=repeating_task.get_name())114 self._rtask = repeating_task115 self._customStop = False116 logger.info("RepeatingTaskThread created for %s" % self.getName())117 def run(self):118 next_run_time = time.time()119 try:120 while not self._customStop:121 s = next_run_time - time.time()122 if s <= 0:123 self._rtask.tick()124 if self._rtask.is_absolute():125 # drop extra missed ticks if we fall behind126 next_run_time = max(127 next_run_time + self._rtask.get_interval_secs(),128 time.time()129 )130 # the above logic ruins clock alignment but it's131 # simpler than trying to do float modulo math :)132 else:133 next_run_time = \134 time.time() + self._rtask.get_interval_secs()135 else:136 # Sleep at most 1 sec at a time to allow graceful stop137 time.sleep(min(s, 1.0))138 except:139 logger.error("Error in run(); Stopping.", exc_info=True)140 def stop_async(self):141 """142 Ask the thread to stop.143 This call does NOT block. This method will call the task's stop()144 method to let the task know about the stop request. If the thread is145 in the interval between task runs it checks for this stop signal every146 1 second. If the thread is in the task's tick() it will only stop after147 tick() is complete.148 """149 self._customStop = True150 self._rtask.stop_async()151 def stop_and_join(self):152 "Helper function - equivalent to calling stop() and then join()"153 self.stop_async()...
__init__.py
Source:__init__.py
...140 _LOGGER.debug("Subscriber authentication error: %s", err)141 raise ConfigEntryAuthFailed from err142 except ConfigurationException as err:143 _LOGGER.error("Configuration error: %s", err)144 subscriber.stop_async()145 return False146 except GoogleNestException as err:147 if DATA_NEST_UNAVAILABLE not in hass.data[DOMAIN]:148 _LOGGER.error("Subscriber error: %s", err)149 hass.data[DOMAIN][DATA_NEST_UNAVAILABLE] = True150 subscriber.stop_async()151 raise ConfigEntryNotReady from err152 try:153 await subscriber.async_get_device_manager()154 except GoogleNestException as err:155 if DATA_NEST_UNAVAILABLE not in hass.data[DOMAIN]:156 _LOGGER.error("Device manager error: %s", err)157 hass.data[DOMAIN][DATA_NEST_UNAVAILABLE] = True158 subscriber.stop_async()159 raise ConfigEntryNotReady from err160 hass.data[DOMAIN].pop(DATA_NEST_UNAVAILABLE, None)161 hass.data[DOMAIN][DATA_SUBSCRIBER] = subscriber162 hass.config_entries.async_setup_platforms(entry, PLATFORMS)163 return True164async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:165 """Unload a config entry."""166 if DATA_SDM not in entry.data:167 # Legacy API168 return True169 _LOGGER.debug("Stopping nest subscriber")170 subscriber = hass.data[DOMAIN][DATA_SUBSCRIBER]171 subscriber.stop_async()172 unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)173 if unload_ok:174 hass.data[DOMAIN].pop(DATA_SUBSCRIBER)175 hass.data[DOMAIN].pop(DATA_NEST_UNAVAILABLE, None)...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!