python kafka mocking kafka consumer的返回类型

g52tjvyc  于 2021-06-04  发布在  Kafka
关注(0)|答案(2)|浏览(555)

我想在使用时测试一个脚本 kafka-python 包裹。我想测试函数的返回对象的类型

def _get_kafka_consumer() -> KafkaConsumer:
    consumer = KafkaConsumer(bootstrap_servers=_KAFKA_BOOTSTRAP_SERVICE,
                             auto_offset_reset='earliest')
    consumer.subscribe([_KAFKA_TOPIC_INPUT])
    return consumer

我的测试课看起来像

class TestVoiceToText(unittest.TestCase):

    def test_get_kafka_consumer_output_type(self):
        result = _get_kafka_consumer()
        self.assertIsInstance(result, KafkaConsumer)

当然,它不会通过,因为没有kafka集群在运行 KafkaConsumer 无法创建。我怎么能嘲笑你的回归呢 KafkaConsumer(...) 属于类型 KafkaConsumer 不需要调用实际的构造函数?

sigwle7e

sigwle7e1#

你会想要 spec 在嘲笑中。你可以用 autospec 在这里我相信成功。speccing将您的mock限制为您要模拟的对象的原始api,并允许它通过 isinstance 还有测试。以下是有关自动选择的文档:https://docs.python.org/3.3/library/unittest.mock.html#autospeccing
下面是我如何做你的测试:

@mock.patch('voice_to_text.kafka_connector.KafkaConsumer', autospec=True)
 def test_get_kafka_consumer_output_type(self, kafka_consumer_mock):
        kafka_consumer_instance = _get_kafka_consumer()

        kafka_consumer_mock.assert_called_once_with(
            bootstrap_servers=_KAFKA_BOOTSTRAP_SERVICE,
            auto_offset_reset='earliest')
        kafka_consumer_mock.return_value.subscribe.assert_called_once_with(
            [_KAFKA_TOPIC_INPUT])
        kafka_consumer_mock.assert_called_once()

        self.assertEquals(kafka_consumer_mock.return_value, kafka_consumer_instance)
        self.assertIsInstance(kafka_consumer_instance, KafkaConsumer)
2j4z5cfb

2j4z5cfb2#

我设法用计算机解决了这个问题 patch 函数来自 unittest.mock 包裹:

def test_get_kafka_consumer_output_type(self):
        with patch('voice_to_text.kafka_connector.KafkaConsumer') as kafka_consumer_class_mock:
            kafka_consumer_instance = _get_kafka_consumer()
            kafka_consumer_class_mock_instance = kafka_consumer_class_mock.return_value

            kafka_consumer_class_mock.assert_called_once()
            self.assertEquals(kafka_consumer_class_mock_instance, kafka_consumer_instance)

它只检查 _get_kafka_consumer() 实际上是通过调用函数返回的对象 KafkaConsumer() . 我们不在乎这个函数实际上在做什么。

相关问题