code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def __init__(
self,
worker_name,
experiment_name,
trial_name,
task_queue: WorkerServerTaskQueue,
):
"""Specifies the name of the worker that WorkerControlPanel can used to
find and manage.
Args:
worker_name: Typically "<worker_type>/<worke... | Specifies the name of the worker that WorkerControlPanel can used to
find and manage.
Args:
worker_name: Typically "<worker_type>/<worker_index>".
| __init__ | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def register_handler(self, command, fn):
"""Registers an RPC command.
The handler `fn` shall be called when `self.handle_requests()` sees an
incoming command of the registered type.
"""
if command in self.__handlers:
raise KeyError(f"Command '{command}' exists")
... | Registers an RPC command.
The handler `fn` shall be called when `self.handle_requests()` sees an
incoming command of the registered type.
| register_handler | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def set_status(self, status: WorkerServerStatus):
"""On graceful exit, worker status is cleared."""
name_resolve.add(
names.worker_status(
experiment_name=self.__experiment_name,
trial_name=self.__trial_name,
worker_name=self.__worker_name,
... | On graceful exit, worker status is cleared. | set_status | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def connect(
self,
worker_names: List[str],
timeout=None,
raises_timeout_error=False,
reconnect=False,
progress=False,
) -> List[str]:
"""Waits until all the workers specified by the given names are ready
for receiving commands.
Args:
... | Waits until all the workers specified by the given names are ready
for receiving commands.
Args:
worker_names: A list of workers to connect.
timeout: The maximum waiting time in seconds, or None if infinite.
raises_timeout_error: If True, any connection failure will ... | connect | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def auto_connect(self) -> List[str]:
"""Auto-detects available workers belonging to the experiment trial,
and connects to them.
Returns:
Names of successfully connected workers.
"""
name_root = names.worker_root(self.__experiment_name, self.__trial_name)
work... | Auto-detects available workers belonging to the experiment trial,
and connects to them.
Returns:
Names of successfully connected workers.
| auto_connect | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def request(self, worker_name: str, command, **kwargs) -> Any:
"""Sends an request to the specified worker."""
address = self.__worker_addresses[worker_name]
return self.__requester.async_request(
worker_name, address, command, **kwargs
).result() | Sends an request to the specified worker. | request | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def group_request(
self,
command,
worker_names: Optional[List[str]] = None,
worker_regex: Optional[str] = None,
timeout=None,
progress=False,
worker_kwargs: Optional[List[Dict[str, Any]]] = None,
wait_response=True,
**kwargs,
) -> List[Response... | Requests selected workers, or all connected workers if not
specified.
Args:
command: RPC command.
worker_names: Optional selection of workers.
worker_regex: Optional regex selector of workers.
timeout: Optional timeout.
progress: Whether to sh... | group_request | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def get_worker_status(self, worker_name) -> WorkerServerStatus:
"""Get status of a connected worker.
Raises:
ValueError if worker is not connected.
"""
try:
status_str = name_resolve.wait(
names.worker_status(
experiment_name=s... | Get status of a connected worker.
Raises:
ValueError if worker is not connected.
| get_worker_status | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def __init__(self, server: Optional[WorkerServer] = None):
"""Initializes a worker server.
Args:
server: The RPC server API for the worker to register handlers and poll requests.
"""
self.__running = False
self.__exiting = False
self.config = None
sel... | Initializes a worker server.
Args:
server: The RPC server API for the worker to register handlers and poll requests.
| __init__ | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def __init__(
self,
map_fn,
interrupt_flag,
upstream_queue,
downstream_queue: queue.Queue = None,
cuda_device=None,
):
"""Init method of MappingThread for Policy Workers.
Args:
map_fn: mapping function.
interrupt_flag: main thr... | Init method of MappingThread for Policy Workers.
Args:
map_fn: mapping function.
interrupt_flag: main thread sets this value to True to interrupt the thread.
upstream_queue: the queue to get data from.
downstream_queue: the queue to put data after processing. If ... | __init__ | python | inclusionAI/AReaL | realhf/system/worker_base.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/worker_base.py | Apache-2.0 |
def run_worker(
worker_type, experiment_name, trial_name, worker_name, worker_server_type
):
"""Run one worker
Args:
worker_type: string, one of the worker types listed above,
experiment_name: string, the experiment this worker belongs to,
trial_name: string, the specific trial this ... | Run one worker
Args:
worker_type: string, one of the worker types listed above,
experiment_name: string, the experiment this worker belongs to,
trial_name: string, the specific trial this worker belongs to,
worker_name: name given to the worker, typically "<worker_type>/<worker_index... | run_worker | python | inclusionAI/AReaL | realhf/system/__init__.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/system/__init__.py | Apache-2.0 |
def _worker_process(result_queue, count, low, high, experiment, trial):
"""Helper function for multi-process testing."""
ports = find_multiple_free_ports(
count,
low=low,
high=high,
experiment_name=experiment,
trial_name=trial,
)
for port in ports:
result_... | Helper function for multi-process testing. | _worker_process | python | inclusionAI/AReaL | tests/distributed/test_find_port.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_find_port.py | Apache-2.0 |
def test_find_free_port_multiprocess():
"""Test that multiple processes get different ports."""
num_processes = 100
experiment = "multi_port_test"
trial = "trial1"
testing.clear_name_resolve(experiment, trial)
result_queue = multiprocessing.Queue()
count = 2
processes = []
for _ i... | Test that multiple processes get different ports. | test_find_free_port_multiprocess | python | inclusionAI/AReaL | tests/distributed/test_find_port.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_find_port.py | Apache-2.0 |
def name_resolve(request):
"""Fixture that provides a name resolve repository for each backend type."""
backend_type, kwargs = request.param
# Special handling for NFS backend to use temp directory
if backend_type == "nfs":
temp_dir = tempfile.mkdtemp()
from realhf.base.name_resolve imp... | Fixture that provides a name resolve repository for each backend type. | name_resolve | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_basic_add_get(name_resolve):
"""Test basic add and get functionality."""
# Add a new entry
name_resolve.add("test_key", "test_value")
assert name_resolve.get("test_key") == "test_value"
# Test with non-string value (should be converted to string)
name_resolve.add("test_key_int", 123, r... | Test basic add and get functionality. | test_basic_add_get | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_add_with_replace(name_resolve):
"""Test add operation with replace flag."""
name_resolve.add("test_key", "initial_value")
# Should fail when replace=False
with pytest.raises(NameEntryExistsError):
name_resolve.add("test_key", "new_value", replace=False)
# Should succeed when repla... | Test add operation with replace flag. | test_add_with_replace | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_add_subentry(name_resolve):
"""Test adding subentries with automatic UUID generation."""
sub_name = name_resolve.add_subentry("test_root", "sub_value")
assert sub_name.startswith("test_root/")
assert len(sub_name.split("/")[-1]) == 8 # UUID part should be 8 chars
assert name_resolve.get(su... | Test adding subentries with automatic UUID generation. | test_add_subentry | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_wait(name_resolve):
"""Test waiting for a key to appear."""
def delayed_add():
time.sleep(0.1)
name_resolve.add("test_key", "test_value")
thread = threading.Thread(target=delayed_add, daemon=True)
thread.start()
# Should return once key is added
assert name_resolve.wa... | Test waiting for a key to appear. | test_wait | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_reset(name_resolve):
"""Test reset functionality (cleanup of delete_on_exit keys)."""
name_resolve.add("test_key1", "value1", delete_on_exit=True)
name_resolve.add("test_key_no_delete", "value2", delete_on_exit=False)
name_resolve.reset()
# Only delete_on_exit=True keys should be removed
... | Test reset functionality (cleanup of delete_on_exit keys). | test_reset | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_concurrent_access(name_resolve):
"""Test concurrent access to the same key."""
name_resolve.add("test_key", "initial_value")
def modify_value():
for i in range(5):
current = name_resolve.get("test_key")
name_resolve.add(
"test_key", f"modified_{threa... | Test concurrent access to the same key. | test_concurrent_access | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_path_normalization(name_resolve):
"""Test handling of different path formats."""
# Test paths with trailing slashes
name_resolve.add("test_path/", "value1")
assert name_resolve.get("test_path") == "value1"
# with pytest.raises(NameEntryNotFoundError):
assert name_resolve.get("test_path/... | Test handling of different path formats. | test_path_normalization | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_add_with_invalid_inputs(name_resolve):
"""Test add method with invalid inputs."""
# Test with None name
with pytest.raises(
Exception
): # The specific exception type may vary by implementation
name_resolve.add(None, "value")
# Test with empty name
with pytest.raises(E... | Test add method with invalid inputs. | test_add_with_invalid_inputs | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_long_paths_and_values(name_resolve):
"""Test behavior with very long path names and values."""
long_name = "a/" * 100 + "key"
long_value = "x" * 10000
name_resolve.add(long_name, long_value)
assert name_resolve.get(long_name) == long_value | Test behavior with very long path names and values. | test_long_paths_and_values | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_special_characters(name_resolve):
"""Test handling of special characters in names and values."""
special_chars = "!@#$%^&*()_+-=[]{}|;:'\",.<>?`~ "
# Test special characters in name
for char in special_chars:
try:
name = f"test{char}key"
name_resolve.add(name, "... | Test handling of special characters in names and values. | test_special_characters | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_stress_concurrent_add_get_delete(name_resolve):
"""Stress test with many concurrent operations."""
from concurrent.futures import ThreadPoolExecutor
num_threads = 20
ops_per_thread = 50
# Track success/failure counts
results = {
"success": 0,
"failures": 0,
}
... | Stress test with many concurrent operations. | test_stress_concurrent_add_get_delete | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_wait_with_concurrent_delete(name_resolve):
"""Test wait behavior when a key is added and then deleted before wait completes."""
def add_then_delete():
time.sleep(0.1)
name_resolve.add("test_wait_key", "test_value")
time.sleep(1.0)
name_resolve.delete("test_wait_key")
... | Test wait behavior when a key is added and then deleted before wait completes. | test_wait_with_concurrent_delete | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_wait_edge_cases(name_resolve):
"""Test edge cases for the wait method."""
# Test with invalid timeout values
with pytest.raises(TimeoutError):
name_resolve.wait("nonexistent_key", timeout=0)
# Test with negative timeout (should behave like timeout=None)
with pytest.raises(TimeoutEr... | Test edge cases for the wait method. | test_wait_edge_cases | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_subentry_with_custom_uuid(name_resolve, monkeypatch):
"""Test add_subentry with a predictable UUID for deterministic testing."""
# Mock uuid.uuid4 to return a predictable value
mock_uuid = MagicMock()
mock_uuid.return_value = "12345678-1234-5678-1234-567812345678"
monkeypatch.setattr(uuid, ... | Test add_subentry with a predictable UUID for deterministic testing. | test_subentry_with_custom_uuid | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_race_condition_in_add(name_resolve):
"""Test race condition when adding the same key concurrently."""
if isinstance(name_resolve, NfsNameRecordRepository):
pytest.skip("NFS repo cannot tackle race conditions")
# Define the number of concurrent threads
num_threads = 10
key = "race_c... | Test race condition when adding the same key concurrently. | test_race_condition_in_add | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_find_subtree_with_empty_result(name_resolve):
"""Test find_subtree behavior when no matching keys are found."""
# Ensure no keys exist with this prefix
prefix = "nonexistent_prefix"
# Call find_subtree
result = name_resolve.find_subtree(prefix)
# Verify result is an empty list, not No... | Test find_subtree behavior when no matching keys are found. | test_find_subtree_with_empty_result | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_get_subtree_with_empty_result(name_resolve):
"""Test get_subtree behavior when no matching keys are found."""
# Ensure no keys exist with this prefix
prefix = "nonexistent_prefix"
# Call get_subtree
result = name_resolve.get_subtree(prefix)
# Verify result is an empty list, not None
... | Test get_subtree behavior when no matching keys are found. | test_get_subtree_with_empty_result | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_nested_subtrees(name_resolve):
"""Test behavior with deeply nested subtrees."""
# Create a deeply nested subtree
name_resolve.add("root/level1/level2/level3/key1", "value1")
name_resolve.add("root/level1/level2/key2", "value2")
name_resolve.add("root/level1/key3", "value3")
# Test get_... | Test behavior with deeply nested subtrees. | test_nested_subtrees | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_corner_case_get_same_as_prefix(name_resolve):
"""Test get behavior when a key is both a prefix and a value."""
# Add entries
name_resolve.add("prefix", "parent_value")
name_resolve.add("prefix/child", "child_value")
# Verify both keys can be retrieved individually
assert name_resolve.g... | Test get behavior when a key is both a prefix and a value. | test_corner_case_get_same_as_prefix | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
def test_nfs_specific_features(name_resolve):
"""Test features specific to NFS backend."""
from realhf.base.name_resolve import NfsNameRecordRepository
if not isinstance(name_resolve, NfsNameRecordRepository):
pytest.skip("NFS specific test")
# Test handling of stale file handles
name_reso... | Test features specific to NFS backend. | test_nfs_specific_features | python | inclusionAI/AReaL | tests/distributed/test_name_resolve.py | https://github.com/inclusionAI/AReaL/blob/master/tests/distributed/test_name_resolve.py | Apache-2.0 |
async def test_run_step_calls_issue_generation(partial_rollout_manager):
"""
Test `run_step` calls `_issue_generation` the correct number of times.
"""
with (
patch(
"realhf.system.partial_rollout.PartialRolloutManager._schedule_request",
new_callable=AsyncMock,
)... |
Test `run_step` calls `_issue_generation` the correct number of times.
| test_run_step_calls_issue_generation | python | inclusionAI/AReaL | tests/system/test_partial_rollout.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_partial_rollout.py | Apache-2.0 |
def run_pusher_in_thread(data: Any, count: int = 1, delay: float = 0.1):
"""Helper to run pusher in a separate thread"""
def pusher_thread():
with ZMQJsonPusher(host=TEST_HOST, port=TEST_PORT) as p:
for _ in range(count):
p.push(data)
time.sleep(delay)
t... | Helper to run pusher in a separate thread | run_pusher_in_thread | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_basic_push_pull(pusher, puller):
"""Test basic push-pull functionality with simple data"""
test_data = {"key": "value", "num": 42, "flag": True}
pusher.push(test_data)
time.sleep(1)
received = puller.pull()
assert received == test_data | Test basic push-pull functionality with simple data | test_basic_push_pull | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_push_non_json_data(pusher):
"""Test that pushing non-JSON data raises TypeError"""
class NonJSON:
pass
with pytest.raises(TypeError):
pusher.push(NonJSON())
with pytest.raises(TypeError):
pusher.push(b"binary data") | Test that pushing non-JSON data raises TypeError | test_push_non_json_data | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_push_large_data(pusher, puller):
"""Test pushing and pulling large JSON data"""
large_data = {
"array": list(range(1000)),
"nested": {"deep": [{"deeper": True} for _ in range(100)]},
}
pusher.push(large_data)
received = puller.pull()
assert received == large_data | Test pushing and pulling large JSON data | test_push_large_data | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_pull_with_custom_timeout(puller):
"""Test pull() with custom timeout parameter"""
# Test with very short timeout (should raise immediately)
start_time = time.time()
with pytest.raises(QueueEmpty, match="No data available after 10ms timeout"):
puller.pull(timeout_ms=10)
elapsed = tim... | Test pull() with custom timeout parameter | test_pull_with_custom_timeout | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_pull_timeout_none(puller):
"""Test that pull(timeout_ms=None) uses default timeout"""
start_time = time.time()
with pytest.raises(QueueEmpty):
puller.pull(timeout_ms=None) # Should use default 1000ms
elapsed = time.time() - start_time
assert abs(elapsed - 1.0) < 0.1 # Approximate... | Test that pull(timeout_ms=None) uses default timeout | test_pull_timeout_none | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_mixed_timeout_usage(pusher, puller):
"""Test mixing different timeout values in successive calls"""
# First with default timeout (should wait)
start_time = time.time()
with pytest.raises(QueueEmpty):
puller.pull()
assert abs((time.time() - start_time) - 1.0) < 0.1
# Then with s... | Test mixing different timeout values in successive calls | test_mixed_timeout_usage | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_timeout_restoration_after_error(puller):
"""Test that default timeout is restored after error"""
original_timeout = puller.default_timeout_ms
# First verify default behavior
with pytest.raises(QueueEmpty):
puller.pull()
# Change timeout temporarily
with pytest.raises(QueueEmpt... | Test that default timeout is restored after error | test_timeout_restoration_after_error | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_concurrent_access(puller):
"""Test that puller can handle concurrent pushes"""
test_data = {"message": "hello"}
thread = run_pusher_in_thread(test_data)
received = puller.pull()
thread.join()
assert received == test_data | Test that puller can handle concurrent pushes | test_concurrent_access | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_multiple_messages(pusher, puller):
"""Test sending and receiving multiple messages"""
messages = [
{"id": 1, "content": "first"},
{"id": 2, "content": "second"},
{"id": 3, "content": "third"},
]
for msg in messages:
pusher.push(msg)
for expected in messages... | Test sending and receiving multiple messages | test_multiple_messages | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def test_rapid_fire_messages(puller):
"""Test handling of many rapid messages"""
test_data = {"count": 0}
thread = run_pusher_in_thread(test_data, count=100, delay=0.01)
received_count = 0
while True:
try:
puller.pull()
received_count += 1
if received_cou... | Test handling of many rapid messages | test_rapid_fire_messages | python | inclusionAI/AReaL | tests/system/test_push_pull_stream.py | https://github.com/inclusionAI/AReaL/blob/master/tests/system/test_push_pull_stream.py | Apache-2.0 |
def kill_process_tree(parent_pid, include_parent: bool = True, skip_pid: int = None):
"""Kill the process and all its child processes."""
# Remove sigchld handler to avoid spammy logs.
if threading.current_thread() is threading.main_thread():
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
if par... | Kill the process and all its child processes. | kill_process_tree | python | inclusionAI/AReaL | training/utils.py | https://github.com/inclusionAI/AReaL/blob/master/training/utils.py | Apache-2.0 |
def __init__(self):
"""Set tab as space and it's value to 4."""
self.tab_str = " "
self.tab_size = 4
self.backup = False
self.check_only = False
self.apply_function_style = None # default is no change based on function style
self.color = True | Set tab as space and it's value to 4. | __init__ | python | lovesegfault/beautysh | beautysh/__init__.py | https://github.com/lovesegfault/beautysh/blob/master/beautysh/__init__.py | MIT |
def detect_function_style(self, test_record):
"""Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected."""
index = 0
# IMPORTANT: apply regex sequentially and stop on the first match:
for regex in FUNCTI... | Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected. | detect_function_style | python | lovesegfault/beautysh | beautysh/__init__.py | https://github.com/lovesegfault/beautysh/blob/master/beautysh/__init__.py | MIT |
def change_function_style(self, stripped_record, func_decl_style):
"""Converts a function definition syntax from the 'func_decl_style' to
the one that has been set in self.apply_function_style and returns the
string with the converted syntax."""
if func_decl_style is None:
re... | Converts a function definition syntax from the 'func_decl_style' to
the one that has been set in self.apply_function_style and returns the
string with the converted syntax. | change_function_style | python | lovesegfault/beautysh | beautysh/__init__.py | https://github.com/lovesegfault/beautysh/blob/master/beautysh/__init__.py | MIT |
def get_test_record(self, source_line):
"""Takes the given Bash source code line and simplifies it by removing stuff that is not
useful for the purpose of indentation level calculation"""
# first of all, get rid of escaped special characters like single/double quotes
# that may impact la... | Takes the given Bash source code line and simplifies it by removing stuff that is not
useful for the purpose of indentation level calculation | get_test_record | python | lovesegfault/beautysh | beautysh/__init__.py | https://github.com/lovesegfault/beautysh/blob/master/beautysh/__init__.py | MIT |
def convert_to_timezone_naive(time_to_freeze: datetime.datetime) -> datetime.datetime:
"""
Converts a potentially timezone-aware datetime to be a naive UTC datetime
"""
if time_to_freeze.tzinfo:
time_to_freeze -= time_to_freeze.utcoffset() # type: ignore
time_to_freeze = time_to_freeze.... |
Converts a potentially timezone-aware datetime to be a naive UTC datetime
| convert_to_timezone_naive | python | spulec/freezegun | freezegun/api.py | https://github.com/spulec/freezegun/blob/master/freezegun/api.py | Apache-2.0 |
def _parse_time_to_freeze(time_to_freeze_str: Optional[_Freezable]) -> datetime.datetime:
"""Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object
"""
if time_to_freeze_str is None:
time_to_freeze_str = datetime.datetime.now(datetime.timezone.utc)
if ... | Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object
| _parse_time_to_freeze | python | spulec/freezegun | freezegun/api.py | https://github.com/spulec/freezegun/blob/master/freezegun/api.py | Apache-2.0 |
def move_to(self, target_datetime: _Freezable) -> None:
"""Moves frozen date to the given ``target_datetime``"""
self.start = real_datetime.now()
self.time_to_freeze = _parse_time_to_freeze(target_datetime) | Moves frozen date to the given ``target_datetime`` | move_to | python | spulec/freezegun | freezegun/api.py | https://github.com/spulec/freezegun/blob/master/freezegun/api.py | Apache-2.0 |
def freeze_time(time_to_freeze: Optional[_Freezable]=None, tz_offset: Union[int, datetime.timedelta]=0, ignore: Optional[List[str]]=None, tick: bool=False, as_arg: bool=False, as_kwarg: str='',
auto_tick_seconds: float=0, real_asyncio: bool=False) -> _freeze_time:
"""
Freezes time for testing pu... |
Freezes time for testing purposes.
This function can be used as a decorator or a context manager to freeze time
during the execution of a block of code or a function. It provides various
options to customize the behavior of the frozen time.
Args:
time_to_freeze (Optional[_Freezable]): The... | freeze_time | python | spulec/freezegun | freezegun/api.py | https://github.com/spulec/freezegun/blob/master/freezegun/api.py | Apache-2.0 |
def test_freezing_time_in_coroutine() -> None:
"""Test calling freeze_time while executing asyncio loop."""
async def coroutine() -> None:
with freeze_time('1970-01-02'):
assert time.time() == 86400
with freeze_time('1970-01-03'):
assert time.time() == 86400 * 2
asyn... | Test calling freeze_time while executing asyncio loop. | test_freezing_time_in_coroutine | python | spulec/freezegun | tests/test_asyncio.py | https://github.com/spulec/freezegun/blob/master/tests/test_asyncio.py | Apache-2.0 |
def test_freezing_time_before_running_coroutine() -> None:
"""Test calling freeze_time before executing asyncio loop."""
async def coroutine() -> None:
assert time.time() == 86400
with freeze_time('1970-01-02'):
asyncio.run(coroutine()) | Test calling freeze_time before executing asyncio loop. | test_freezing_time_before_running_coroutine | python | spulec/freezegun | tests/test_asyncio.py | https://github.com/spulec/freezegun/blob/master/tests/test_asyncio.py | Apache-2.0 |
def test_asyncio_sleeping_not_affected_by_freeze_time() -> None:
"""Test that asyncio.sleep() is not affected by `freeze_time`.
This test ensures that despite freezing time using `freeze_time`,
the asyncio event loop can see real monotonic time, which is required
to make things like `asyncio.sleep()` w... | Test that asyncio.sleep() is not affected by `freeze_time`.
This test ensures that despite freezing time using `freeze_time`,
the asyncio event loop can see real monotonic time, which is required
to make things like `asyncio.sleep()` work.
| test_asyncio_sleeping_not_affected_by_freeze_time | python | spulec/freezegun | tests/test_asyncio.py | https://github.com/spulec/freezegun/blob/master/tests/test_asyncio.py | Apache-2.0 |
def test_asyncio_to_call_later_with_frozen_time() -> None:
"""Test that asyncio `loop.call_later` works with frozen time."""
# `to_call_later` will be called by asyncio event loop and should add
# the Unix timestamp of 1970-01-02 00:00 to the `timestamps` list.
timestamps = []
def to_call_later() ->... | Test that asyncio `loop.call_later` works with frozen time. | test_asyncio_to_call_later_with_frozen_time | python | spulec/freezegun | tests/test_asyncio.py | https://github.com/spulec/freezegun/blob/master/tests/test_asyncio.py | Apache-2.0 |
def test_freeze_with_timezone_aware_datetime_in_utc() -> None:
"""
utcnow() should always return a timezone naive datetime
"""
utc_now = datetime.datetime.utcnow()
assert utc_now.tzinfo is None |
utcnow() should always return a timezone naive datetime
| test_freeze_with_timezone_aware_datetime_in_utc | python | spulec/freezegun | tests/test_datetimes.py | https://github.com/spulec/freezegun/blob/master/tests/test_datetimes.py | Apache-2.0 |
def test_freeze_with_timezone_aware_datetime_in_non_utc() -> None:
"""
we expect the system to behave like a system with UTC-4 timezone
at the beginning of the Epoch (wall clock should be 4 hrs late)
"""
utc_now = datetime.datetime.utcnow()
assert utc_now.tzinfo is None
assert utc_now == dat... |
we expect the system to behave like a system with UTC-4 timezone
at the beginning of the Epoch (wall clock should be 4 hrs late)
| test_freeze_with_timezone_aware_datetime_in_non_utc | python | spulec/freezegun | tests/test_datetimes.py | https://github.com/spulec/freezegun/blob/master/tests/test_datetimes.py | Apache-2.0 |
def test_compare_datetime_and_time_with_timezone(monkeypatch: pytest.MonkeyPatch) -> None:
"""
Compare the result of datetime.datetime.now() and time.time() in a non-UTC timezone. These
should be consistent.
"""
try:
with monkeypatch.context() as m, freeze_time("1970-01-01 00:00:00"):
... |
Compare the result of datetime.datetime.now() and time.time() in a non-UTC timezone. These
should be consistent.
| test_compare_datetime_and_time_with_timezone | python | spulec/freezegun | tests/test_datetimes.py | https://github.com/spulec/freezegun/blob/master/tests/test_datetimes.py | Apache-2.0 |
def test_datetime_in_timezone(monkeypatch: pytest.MonkeyPatch) -> None:
"""
It is assumed that the argument passed to freeze_time is in UTC, unless explicitly indicated
otherwise. Therefore datetime.now() should return the frozen time with an offset.
"""
try:
with monkeypatch.context() as m,... |
It is assumed that the argument passed to freeze_time is in UTC, unless explicitly indicated
otherwise. Therefore datetime.now() should return the frozen time with an offset.
| test_datetime_in_timezone | python | spulec/freezegun | tests/test_datetimes.py | https://github.com/spulec/freezegun/blob/master/tests/test_datetimes.py | Apache-2.0 |
def assert_module_with_raised_error(error_type: Any) -> Iterator[None]:
"""Install a module into sys.modules that raises an error upon invoking
__dir__."""
module = sys.modules['module_with_error'] = ModuleWithError(error_type) # type: ignore
try:
yield
finally:
del sys.modules['mo... | Install a module into sys.modules that raises an error upon invoking
__dir__. | assert_module_with_raised_error | python | spulec/freezegun | tests/test_errors.py | https://github.com/spulec/freezegun/blob/master/tests/test_errors.py | Apache-2.0 |
def time_from_uuid(value: Any) -> datetime.datetime:
"""
Converts an UUID(1) to it's datetime value
"""
uvalue = value if isinstance(value, uuid.UUID) else uuid.UUID(value)
assert uvalue.version == 1
return (datetime.datetime(1582, 10, 15) +
datetime.timedelta(microseconds=uvalue.tim... |
Converts an UUID(1) to it's datetime value
| time_from_uuid | python | spulec/freezegun | tests/test_uuid.py | https://github.com/spulec/freezegun/blob/master/tests/test_uuid.py | Apache-2.0 |
def test_uuid1_future() -> None:
"""
Test that we can go back in time after setting a future date.
Normally UUID1 would disallow this, since it keeps track of
the _last_timestamp, but we override that now.
"""
future_target = datetime.datetime(2056, 2, 6, 14, 3, 21)
with freeze_time(future_t... |
Test that we can go back in time after setting a future date.
Normally UUID1 would disallow this, since it keeps track of
the _last_timestamp, but we override that now.
| test_uuid1_future | python | spulec/freezegun | tests/test_uuid.py | https://github.com/spulec/freezegun/blob/master/tests/test_uuid.py | Apache-2.0 |
def test_uuid1_past() -> None:
"""
Test that we can go forward in time after setting some time in the past.
This is simply the opposite of test_uuid1_future()
"""
past_target = datetime.datetime(1978, 7, 6, 23, 6, 31)
with freeze_time(past_target):
assert time_from_uuid(uuid.uuid1()) == ... |
Test that we can go forward in time after setting some time in the past.
This is simply the opposite of test_uuid1_future()
| test_uuid1_past | python | spulec/freezegun | tests/test_uuid.py | https://github.com/spulec/freezegun/blob/master/tests/test_uuid.py | Apache-2.0 |
def assert_module_with_emitted_warning() -> Iterator[None]:
"""Install a module that triggers warnings into sys.modules and ensure the
warning was triggered in the with-block. """
module = sys.modules['module_with_warning'] = ModuleWithWarning() # type: ignore
try:
yield
finally:
... | Install a module that triggers warnings into sys.modules and ensure the
warning was triggered in the with-block. | assert_module_with_emitted_warning | python | spulec/freezegun | tests/test_warnings.py | https://github.com/spulec/freezegun/blob/master/tests/test_warnings.py | Apache-2.0 |
def test_ignore_warnings_in_stop() -> None:
"""Make sure that modules that was loaded after start() does not trigger
warnings in stop()"""
freezer = freeze_time(datetime.datetime(2016, 10, 27, 9, 56))
freezer.start()
with assert_module_with_emitted_warning():
with assert_no_warnings():
... | Make sure that modules that was loaded after start() does not trigger
warnings in stop() | test_ignore_warnings_in_stop | python | spulec/freezegun | tests/test_warnings.py | https://github.com/spulec/freezegun/blob/master/tests/test_warnings.py | Apache-2.0 |
def validate_queues(self):
"Checks if a worker is given atleast one queue to work on."
if not self.queues:
raise NoQueueError("Please give each worker at least one queue.") | Checks if a worker is given atleast one queue to work on. | validate_queues | python | binarymatt/pyres | pyres/horde.py | https://github.com/binarymatt/pyres/blob/master/pyres/horde.py | MIT |
def _shutdown_minions(self):
"""
send the SIGNINT signal to each worker in the pool.
"""
setproctitle('pyres_manager: Waiting on children to shutdown.')
for minion in self._workers.values():
minion.terminate()
minion.join() |
send the SIGNINT signal to each worker in the pool.
| _shutdown_minions | python | binarymatt/pyres | pyres/horde.py | https://github.com/binarymatt/pyres/blob/master/pyres/horde.py | MIT |
def perform(self):
"""This method converts payload into args and calls the ``perform``
method on the payload class.
Before calling ``perform``, a ``before_perform`` class method
is called, if it exists. It takes a dictionary as an argument;
currently the only things stored on t... | This method converts payload into args and calls the ``perform``
method on the payload class.
Before calling ``perform``, a ``before_perform`` class method
is called, if it exists. It takes a dictionary as an argument;
currently the only things stored on the dictionary are the
... | perform | python | binarymatt/pyres | pyres/job.py | https://github.com/binarymatt/pyres/blob/master/pyres/job.py | MIT |
def fail(self, exception):
"""This method provides a way to fail a job and will use whatever
failure backend you've provided. The default is the ``RedisBackend``.
"""
fail = failure.create(exception, self._queue, self._payload,
self._worker)
fail.sa... | This method provides a way to fail a job and will use whatever
failure backend you've provided. The default is the ``RedisBackend``.
| fail | python | binarymatt/pyres | pyres/job.py | https://github.com/binarymatt/pyres/blob/master/pyres/job.py | MIT |
def retry(self, payload_class, args):
"""This method provides a way to retry a job after a failure.
If the jobclass defined by the payload containes a ``retry_every`` attribute then pyres
will attempt to retry the job until successful or until timeout defined by ``retry_timeout`` on the payload ... | This method provides a way to retry a job after a failure.
If the jobclass defined by the payload containes a ``retry_every`` attribute then pyres
will attempt to retry the job until successful or until timeout defined by ``retry_timeout`` on the payload class.
| retry | python | binarymatt/pyres | pyres/job.py | https://github.com/binarymatt/pyres/blob/master/pyres/job.py | MIT |
def reserve(cls, queues, res, worker=None, timeout=10):
"""Reserve a job on one of the queues. This marks this job so
that other workers will not pick it up.
"""
if isinstance(queues, string_types):
queues = [queues]
queue, payload = res.pop(queues, timeout=timeout)
... | Reserve a job on one of the queues. This marks this job so
that other workers will not pick it up.
| reserve | python | binarymatt/pyres | pyres/job.py | https://github.com/binarymatt/pyres/blob/master/pyres/job.py | MIT |
def __init__(self, server="localhost:6379", password=None):
"""
>>> from pyres.scheduler import Scheduler
>>> scheduler = Scheduler('localhost:6379')
"""
self._shutdown = False
if isinstance(server, string_types):
self.resq = ResQ(server=server, password=passw... |
>>> from pyres.scheduler import Scheduler
>>> scheduler = Scheduler('localhost:6379')
| __init__ | python | binarymatt/pyres | pyres/scheduler.py | https://github.com/binarymatt/pyres/blob/master/pyres/scheduler.py | MIT |
def validate_queues(self):
"""Checks if a worker is given at least one queue to work on."""
if not self.queues:
raise NoQueueError("Please give each worker at least one queue.") | Checks if a worker is given at least one queue to work on. | validate_queues | python | binarymatt/pyres | pyres/worker.py | https://github.com/binarymatt/pyres/blob/master/pyres/worker.py | MIT |
def work(self, interval=5):
"""Invoked by ``run`` method. ``work`` listens on a list of queues and sleeps
for ``interval`` time.
``interval`` -- Number of seconds the worker will wait until processing the next job. Default is "5".
Whenever a worker finds a job on the queue it first cal... | Invoked by ``run`` method. ``work`` listens on a list of queues and sleeps
for ``interval`` time.
``interval`` -- Number of seconds the worker will wait until processing the next job. Default is "5".
Whenever a worker finds a job on the queue it first calls ``reserve`` on
that job to m... | work | python | binarymatt/pyres | pyres/worker.py | https://github.com/binarymatt/pyres/blob/master/pyres/worker.py | MIT |
def fork_worker(self, job):
"""Invoked by ``work`` method. ``fork_worker`` does the actual forking to create the child
process that will process the job. It's also responsible for monitoring the child process
and handling hangs and crashes.
Finally, the ``process`` method actually proce... | Invoked by ``work`` method. ``fork_worker`` does the actual forking to create the child
process that will process the job. It's also responsible for monitoring the child process
and handling hangs and crashes.
Finally, the ``process`` method actually processes the job by eventually calling the ... | fork_worker | python | binarymatt/pyres | pyres/worker.py | https://github.com/binarymatt/pyres/blob/master/pyres/worker.py | MIT |
def worker_pids(cls):
"""Returns an array of all pids (as strings) of the workers on
this machine. Used when pruning dead workers."""
cmd = "ps -A -o pid,command | grep pyres_worker | grep -v grep"
output = commands.getoutput(cmd)
if output:
return map(lambda l: l.st... | Returns an array of all pids (as strings) of the workers on
this machine. Used when pruning dead workers. | worker_pids | python | binarymatt/pyres | pyres/worker.py | https://github.com/binarymatt/pyres/blob/master/pyres/worker.py | MIT |
def my_import(name):
"""Helper function for walking import calls when searching for classes by
string names.
"""
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod | Helper function for walking import calls when searching for classes by
string names.
| my_import | python | binarymatt/pyres | pyres/__init__.py | https://github.com/binarymatt/pyres/blob/master/pyres/__init__.py | MIT |
def safe_str_to_class(s):
"""Helper function to map string class names to module classes."""
lst = s.split(".")
klass = lst[-1]
mod_list = lst[:-1]
module = ".".join(mod_list)
# ruby compatibility kludge: resque sends just a class name and
# not a module name so if I use resque to queue a r... | Helper function to map string class names to module classes. | safe_str_to_class | python | binarymatt/pyres | pyres/__init__.py | https://github.com/binarymatt/pyres/blob/master/pyres/__init__.py | MIT |
def str_to_class(s):
"""Alternate helper function to map string class names to module classes."""
lst = s.split(".")
klass = lst[-1]
mod_list = lst[:-1]
module = ".".join(mod_list)
try:
mod = __import__(module)
if hasattr(mod, klass):
return getattr(mod, klass)
... | Alternate helper function to map string class names to module classes. | str_to_class | python | binarymatt/pyres | pyres/__init__.py | https://github.com/binarymatt/pyres/blob/master/pyres/__init__.py | MIT |
def enqueue(self, klass, *args):
"""Enqueue a job into a specific queue. Make sure the class you are
passing has **queue** attribute and a **perform** method on it.
"""
queue = getattr(klass,'queue', None)
if queue:
class_name = '%s.%s' % (klass.__module__, klass.__n... | Enqueue a job into a specific queue. Make sure the class you are
passing has **queue** attribute and a **perform** method on it.
| enqueue | python | binarymatt/pyres | pyres/__init__.py | https://github.com/binarymatt/pyres/blob/master/pyres/__init__.py | MIT |
def info(self):
"""Returns a dictionary of the current status of the pending jobs,
processed, no. of queues, no. of workers, no. of failed jobs.
"""
pending = 0
for q in self.queues():
pending += self.size(q)
return {
'pending' : pending,
... | Returns a dictionary of the current status of the pending jobs,
processed, no. of queues, no. of workers, no. of failed jobs.
| info | python | binarymatt/pyres | pyres/__init__.py | https://github.com/binarymatt/pyres/blob/master/pyres/__init__.py | MIT |
def _parse_traceback(self, trace):
"""Return the given traceback string formatted for a notification."""
if not trace:
return []
return trace.split('\n') | Return the given traceback string formatted for a notification. | _parse_traceback | python | binarymatt/pyres | pyres/failure/base.py | https://github.com/binarymatt/pyres/blob/master/pyres/failure/base.py | MIT |
def create_message(self):
"""Returns a message body to send in this email. Should be from email.mime.*"""
body = dedent("""\
Received exception {exception} on {queue} from worker {worker}:
{traceback}
Payload:
{payload}
""").format(exception=self._exception,
... | Returns a message body to send in this email. Should be from email.mime.* | create_message | python | binarymatt/pyres | pyres/failure/mail.py | https://github.com/binarymatt/pyres/blob/master/pyres/failure/mail.py | MIT |
def save(self, resq=None):
"""Saves the failed Job into a "failed" Redis queue preserving all its original enqueud info."""
if not resq:
resq = ResQ()
data = {
'failed_at' : datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
'payload' : self._payload,
... | Saves the failed Job into a "failed" Redis queue preserving all its original enqueud info. | save | python | binarymatt/pyres | pyres/failure/redis.py | https://github.com/binarymatt/pyres/blob/master/pyres/failure/redis.py | MIT |
async def send_request(self, *, end: bool = False) -> None:
"""Coroutine to send request headers with metadata to the server.
New HTTP/2 stream will be created during this coroutine call.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` corout... | Coroutine to send request headers with metadata to the server.
New HTTP/2 stream will be created during this coroutine call.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly.
:param ... | send_request | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def send_message(
self,
message: _SendType,
*,
end: bool = False,
) -> None:
"""Coroutine to send message to the server.
If client sends UNARY request, then you should call this coroutine only
once. If client sends STREAM request, then you can call this... | Coroutine to send message to the server.
If client sends UNARY request, then you should call this coroutine only
once. If client sends STREAM request, then you can call this coroutine
as many times as you need.
.. warning:: It is important to finally end stream from the client-side
... | send_message | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def end(self) -> None:
"""Coroutine to end stream from the client-side.
It should be used to finally end stream from the client-side when we're
finished sending messages to the server and stream wasn't closed with
last DATA frame. See :py:meth:`send_message` for more details.
... | Coroutine to end stream from the client-side.
It should be used to finally end stream from the client-side when we're
finished sending messages to the server and stream wasn't closed with
last DATA frame. See :py:meth:`send_message` for more details.
HTTP/2 stream will have half-closed... | end | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def recv_initial_metadata(self) -> None:
"""Coroutine to wait for headers with initial metadata from the server.
.. note:: This coroutine will be called implicitly during first
:py:meth:`recv_message` coroutine call, if not called before
explicitly.
May raise :py:... | Coroutine to wait for headers with initial metadata from the server.
.. note:: This coroutine will be called implicitly during first
:py:meth:`recv_message` coroutine call, if not called before
explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
... | recv_initial_metadata | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def recv_message(self) -> Optional[_RecvType]:
"""Coroutine to receive incoming message from the server.
If server sends UNARY response, then you can call this coroutine only
once. If server sends STREAM response, then you should call this
coroutine several times, until it returns... | Coroutine to receive incoming message from the server.
If server sends UNARY response, then you can call this coroutine only
once. If server sends STREAM response, then you should call this
coroutine several times, until it returns None when the server has
ended the stream. To simplify ... | recv_message | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def recv_trailing_metadata(self) -> None:
"""Coroutine to wait for trailers with trailing metadata from the
server.
.. note:: This coroutine will be called implicitly at exit from
this call (context manager's exit), if not called before explicitly.
May raise :py:class... | Coroutine to wait for trailers with trailing metadata from the
server.
.. note:: This coroutine will be called implicitly at exit from
this call (context manager's exit), if not called before explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
... | recv_trailing_metadata | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def cancel(self) -> None:
"""Coroutine to cancel this request/stream.
Client will send RST_STREAM frame to the server, so it will be
explicitly informed that there is nothing to expect from the client
regarding this request/stream.
"""
if not self._send_request_don... | Coroutine to cancel this request/stream.
Client will send RST_STREAM frame to the server, so it will be
explicitly informed that there is nothing to expect from the client
regarding this request/stream.
| cancel | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
def open(
self,
*,
timeout: Optional[float] = None,
metadata: Optional[_MetadataLike] = None,
) -> Stream[_SendType, _RecvType]:
"""Creates and returns :py:class:`Stream` object to perform request
to the server.
Nothing will happen to the current underlying H... | Creates and returns :py:class:`Stream` object to perform request
to the server.
Nothing will happen to the current underlying HTTP/2 connection during
this method call. It just initializes :py:class:`Stream` object for you.
Actual request will be sent only during :py:meth:`Stream.send_r... | open | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def __call__(
self,
message: _SendType,
*,
timeout: Optional[float] = None,
metadata: Optional[_MetadataLike] = None,
) -> _RecvType:
"""Coroutine to perform defined call.
:param message: message
:param float timeout: request timeout (seconds)
... | Coroutine to perform defined call.
:param message: message
:param float timeout: request timeout (seconds)
:param metadata: custom request metadata, dict or list of pairs
:return: message
| __call__ | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def __call__(
self,
message: _SendType,
*,
timeout: Optional[float] = None,
metadata: Optional[_MetadataLike] = None,
) -> List[_RecvType]:
"""Coroutine to perform defined call.
:param message: message
:param float timeout: request timeout (seco... | Coroutine to perform defined call.
:param message: message
:param float timeout: request timeout (seconds)
:param metadata: custom request metadata, dict or list of pairs
:return: sequence of messages
| __call__ | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def __call__(
self,
messages: Sequence[_SendType],
*,
timeout: Optional[float] = None,
metadata: Optional[_MetadataLike] = None,
) -> _RecvType:
"""Coroutine to perform defined call.
:param messages: sequence of messages
:param float timeout: re... | Coroutine to perform defined call.
:param messages: sequence of messages
:param float timeout: request timeout (seconds)
:param metadata: custom request metadata, dict or list of pairs
:return: message
| __call__ | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
async def __call__(
self,
messages: Sequence[_SendType],
*,
timeout: Optional[float] = None,
metadata: Optional[_MetadataLike] = None,
) -> List[_RecvType]:
"""Coroutine to perform defined call.
:param messages: sequence of messages
:param float timeo... | Coroutine to perform defined call.
:param messages: sequence of messages
:param float timeout: request timeout (seconds)
:param metadata: custom request metadata, dict or list of pairs
:return: sequence of messages
| __call__ | python | vmagamedov/grpclib | grpclib/client.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/client.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.