[英]How to mock Kafka Producer and producer.send method for Python unit test
I am new to Python and trying to write a unit test which involves Kafka.我是 Python 的新手,并试图编写一个涉及 Kafka 的单元测试。 I have a class with a function which calls another function to initialize Kafka Producer and then call producer.send().
我有一个 class 和一个 function,它调用另一个 function 来初始化 Kafka Producer,然后调用 producer.send()。 I want to mock Kafka Producer for my unit test.
我想为我的单元测试模拟 Kafka Producer。
Below is my code and I want to write unit test for produce_kafka_message method.下面是我的代码,我想为produce_kafka_message 方法编写单元测试。
class KafkaProducerIntface
def __init__(self, topic, .....)
self.bootstrap_server = bootstrap_server
self.producer = None
self.post_topic = topic
....
def produce_kafka_message(self, key, value, headers)
self.__initialize_producer__(retries=3)
future = self.producer.send(self.topic, key=key, value=value, headers=headers)
self.producer.flush()
def __initialize_producer__(self, retries=3)
self.producer = KafkaProducer(bootstrap_servers=self.bootstrap_server, acks='all', retries=retries)
You can use mock lib for it and mock the produce_kafka_message
method:您可以使用 mock lib 并模拟
produce_kafka_message
方法:
with mock.patch.object(KafkaProducerIntface, "produce_kafka_message") as mock_produce_kafka_message:
... # do some code here
mock_produce_kafka_message.assert_called_once_with(key, value, headerss)
You can also do the same with KafkaProducer class it self:您也可以对 KafkaProducer class 执行相同的操作:
with mock.patch("kafka.path.KafkaProducer") as mock_kafka_producer:
interface = KafkaProducerIntface(...)
interface.produce_kafka_message(key, value, headers)
mock_kafka_producer.send.assert_called_once()
mock_kafka_producer.flush()
BTW.顺便提一句。 also please check if you want to run flush after the send or just.poll(0):)
还请检查是否要在发送后运行刷新或 just.poll(0):)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.