Skip to content

Commit

Permalink
Add async callbacks support for apply_on_packets
Browse files Browse the repository at this point in the history
  • Loading branch information
antibagr committed Nov 15, 2023
1 parent e7da566 commit 72ecb79
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/pyshark/capture/capture.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import inspect
import os
import threading
import subprocess
Expand Down Expand Up @@ -291,7 +292,10 @@ async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=No
if packet:
packets_captured += 1
try:
packet_callback(packet)
if inspect.iscoroutinefunction(packet_callback):
await packet_callback(packet)
else:
packet_callback(packet)
except StopCapture:
self._log.debug("User-initiated capture stop in callback")
break
Expand Down
2 changes: 1 addition & 1 deletion src/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

setup(
name="pyshark",
version="0.6",
version="0.6.1",
packages=find_packages(),
package_data={'': ['*.ini', '*.pcapng']},
install_requires=['lxml', 'termcolor', 'packaging', 'appdirs'],
Expand Down
8 changes: 8 additions & 0 deletions tests/test_cap_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ def test_packet_callback_called_for_each_packet(lazy_simple_capture):
assert mock_callback.call_count == 24


def test_async_packet_callback_called_for_each_packet(lazy_simple_capture):
# Test cap has 24 packets
mock_callback = mock.AsyncMock()
lazy_simple_capture.apply_on_packets(mock_callback)
assert mock_callback.call_count == 24
mock_callback.assert_awaited()


def test_apply_on_packet_stops_on_timeout(lazy_simple_capture):
def wait(pkt):
time.sleep(5)
Expand Down

0 comments on commit 72ecb79

Please sign in to comment.