Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions kafka/producer/kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,12 @@ def send(self, topic, value=None, key=None, headers=None, partition=None, timest
if type(value_bytes) not in (bytes, bytearray, memoryview, type(None)):
raise TypeError("Unsupported type for serialized value: %s" % type(value_bytes))

# Partitioners and record lengths operate on bytes, not buffer elements.
if isinstance(key_bytes, memoryview):
key_bytes = key_bytes.cast('B') if key_bytes.c_contiguous else key_bytes.tobytes()
if isinstance(value_bytes, memoryview):
value_bytes = value_bytes.cast('B') if value_bytes.c_contiguous else value_bytes.tobytes()

if self._metadata.partitions_for_topic(topic) is None:
try:
self._wait_on_metadata(topic, self.config['max_block_ms'])
Expand Down
24 changes: 16 additions & 8 deletions test/integration/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,20 @@ def _extract_topic_command_error(stdout):
return ''


def get_open_port():
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
return port
def get_open_port(exclude=()):
sockets = []
try:
while True:
sock = socket.socket()
sockets.append(sock)
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
if port not in exclude:
return port
# Keep excluded ports bound so the next bind cannot reuse them.
finally:
for sock in sockets:
sock.close()


def gen_ssl_resources(directory):
Expand Down Expand Up @@ -398,7 +406,7 @@ def __init__(self, host, port, broker_id, zookeeper=None, zk_chroot=None,
else:
self.auto_port = False
self.port = port
self.controller_port = get_open_port()
self.controller_port = get_open_port(exclude=(self.port,))

self.cluster_id = self._gen_cluster_id()
self.broker_id = broker_id
Expand Down Expand Up @@ -606,7 +614,7 @@ def start(self):
# so we will try a different port on each retry
# unless the fixture was passed a specific port
if self.auto_port:
self.port = get_open_port()
self.port = get_open_port(exclude=(self.controller_port,))
self.out('Attempting to start on port %d (try #%d)' % (self.port, tries))
self.render_template(properties_template, properties, vars(self))

Expand Down
75 changes: 73 additions & 2 deletions test/producer/test_producer.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import gc
import platform
import threading
from array import array
from ctypes import c_uint32
from unittest.mock import MagicMock
import warnings

import pytest

from kafka import KafkaProducer
from kafka.errors import KafkaConfigurationError
from kafka.partitioner import Partitioner, StickyPartitioner
from kafka.errors import KafkaConfigurationError, MessageSizeTooLargeError
from kafka.partitioner import DefaultPartitioner, Partitioner, StickyPartitioner
import kafka.producer.kafka as producer_module
from kafka.producer.transaction_manager import TransactionManager, ProducerIdAndEpoch
from kafka.record.memory_records import MemoryRecordsBuilder
from kafka.serializer import Serializer

from test.mock_broker import MockBroker
Expand Down Expand Up @@ -137,6 +140,74 @@ def _success_result():
False, True, False)


@pytest.mark.parametrize('magic,api_version', [(0, (0, 9)), (1, (0, 10)), (2, (0, 11))])
@pytest.mark.parametrize('field', ['key', 'value'])
@pytest.mark.parametrize('data_factory', [
pytest.param(lambda: memoryview(array('H', [0x1234, 0x5678])), id='typed'),
pytest.param(lambda: memoryview(bytearray(b'abcd')).cast('B', [2, 2]), id='multidimensional'),
pytest.param(lambda: memoryview(c_uint32(0x12345678)), id='scalar'),
pytest.param(lambda: memoryview(b'abcdef')[::2], id='strided-bytes'),
pytest.param(lambda: memoryview(array('H', [1, 2, 3]))[::2], id='strided-typed'),
pytest.param(lambda: memoryview(b'abcdef')[::-1], id='reversed'),
pytest.param(lambda: memoryview(b'abcdef')[1:4], id='offset-byte-view'),
pytest.param(lambda: memoryview(array('H')), id='empty-typed'),
pytest.param(lambda: memoryview(b'bytes'), id='byte-view'),
pytest.param(lambda: b'bytes', id='bytes'),
pytest.param(lambda: bytearray(b'bytes'), id='bytearray'),
pytest.param(lambda: None, id='none'),
])
def test_send_buffer_payload_matches_its_bytes(data_factory, field, magic, api_version):
"""Accepted views must reach partitioning and record encoding as bytes."""
original = data_factory()
data = {'key': b'key', 'value': b'value'}
data[field] = original
expected = {name: bytes(value) if value is not None else None for name, value in data.items()}
partitioner = DefaultPartitioner()
with _producer_for_send_test(partitioner) as producer:
producer.config['api_version'] = api_version
producer._accumulator.append.return_value = _success_result()
producer.send('t', timestamp_ms=1000, **data)
tp, timestamp, key, value, headers = producer._accumulator.append.call_args.args

# Exercise actual wire encoding/decoding after the public send path.
# The broker and accumulator are test doubles; this isn't a broker test.
builder = MemoryRecordsBuilder(magic, compression_type=0, batch_size=10000)
builder.append(timestamp, key, value, headers)
builder.close()
batch = builder.records().next_batch()
assert batch.validate_crc()
record, = list(batch)
assert record.key == expected['key']
assert record.value == expected['value']
assert producer._estimate_size_in_bytes(key, value) == producer._estimate_size_in_bytes(
expected['key'], expected['value'])
if expected['key'] is not None:
assert tp.partition == partitioner.partition(
't', data['key'], expected['key'], data['value'], expected['value'], producer._metadata)

serialized = key if field == 'key' else value
if isinstance(original, memoryview):
assert bytes(serialized) == bytes(original)
if original.c_contiguous:
assert isinstance(serialized, memoryview)
assert serialized.obj is original.obj
else:
assert serialized is original


@pytest.mark.parametrize('api_version', [(0, 9), (0, 10), (0, 11)])
def test_send_memoryview_checks_byte_size_limit(api_version):
"""Typed views must not bypass the configured serialized record size bound."""
value = memoryview(array('H', range(100)))
with _producer_for_send_test(DefaultPartitioner()) as producer:
producer.config['api_version'] = api_version
producer.config['max_request_size'] = producer._estimate_size_in_bytes(b'key', bytes(value)) - 1
producer._accumulator.append.return_value = _success_result()
with pytest.raises(MessageSizeTooLargeError):
producer.send('t', key=b'key', value=value)
producer._accumulator.append.assert_not_called()


def test_send_null_key_triggers_on_new_batch_via_abort_retry():
"""KIP-480 Java-faithful flow: a null-key send whose accumulator has
no in-progress batch must invoke ``partitioner.on_new_batch`` (rotate
Expand Down
6 changes: 4 additions & 2 deletions test/test_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,8 +532,10 @@ def test_refresh_loop_spawned_once(self, manager):
"""Calling bootstrap() multiple times must not spawn multiple refresh
loop tasks."""
cluster = manager.cluster
manager.bootstrap(timeout_ms=100)
# This checks refresh-loop identity, not a 100 ms bootstrap speed limit.
timeout_ms = manager.config['request_timeout_ms']
manager.bootstrap(timeout_ms=timeout_ms)
future = cluster._refresh_loop_future
assert future is not None
manager.bootstrap(timeout_ms=100)
manager.bootstrap(timeout_ms=timeout_ms)
assert cluster._refresh_loop_future is future
76 changes: 76 additions & 0 deletions test/test_integration_fixtures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import pytest

from test.integration import fixtures


class PortSocket:
def __init__(self, port, sockets):
self.port = port
self.sockets = sockets
self.bound = False
self.closed = False

def bind(self, address):
assert address == ('127.0.0.1', 0)
assert not any(sock.bound and not sock.closed and sock.port == self.port
for sock in self.sockets)
self.bound = True

def getsockname(self):
return ('127.0.0.1', self.port)

def close(self):
self.closed = True


def port_sockets(monkeypatch, ports):
sockets = []
ports = iter(ports)

def socket():
sock = PortSocket(next(ports), sockets)
sockets.append(sock)
return sock

monkeypatch.setattr(fixtures.socket, 'socket', socket)
return sockets


def test_get_open_port_keeps_excluded_ports_bound_until_selection(monkeypatch):
sockets = port_sockets(monkeypatch, [12345, 23456])
original_getsockname = PortSocket.getsockname

def getsockname(self):
if self.port == 23456:
assert not sockets[0].closed
return original_getsockname(self)

monkeypatch.setattr(PortSocket, 'getsockname', getsockname)
assert fixtures.get_open_port(exclude=(12345,)) == 23456
assert all(sock.closed for sock in sockets)


def test_get_open_port_closes_socket_when_bind_fails(monkeypatch):
sockets = port_sockets(monkeypatch, [12345])

def fail_bind(self, address):
raise OSError('bind failed')

monkeypatch.setattr(PortSocket, 'bind', fail_bind)
with pytest.raises(OSError, match='bind failed'):
fixtures.get_open_port()
assert all(sock.closed for sock in sockets)


@pytest.mark.parametrize('port,ports', [
(None, [12345, 12345, 23456]),
(12345, [12345, 23456]),
])
def test_broker_and_controller_ports_are_distinct(monkeypatch, tmp_path, port, ports):
sockets = port_sockets(monkeypatch, ports)
monkeypatch.setattr(fixtures, 'env_kafka_version', lambda: (4, 3, 0))
monkeypatch.setattr(fixtures.Fixture, 'kafka_root', str(tmp_path))
broker = fixtures.KafkaFixture('localhost', port, 0)
assert broker.port == 12345
assert broker.controller_port == 23456
assert all(sock.closed for sock in sockets)