From 2e0b5834d7d3335897feafd65bf7cc3d6be952f8 Mon Sep 17 00:00:00 2001 From: MohitKatare-protean Date: Tue, 6 May 2025 12:08:56 +0530 Subject: [PATCH] added updated test case for the publisher implementation --- .../implementation/publisher/publisher.go | 7 +- .../publisher/publisher_test.go | 70 +++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/pkg/plugin/implementation/publisher/publisher.go b/pkg/plugin/implementation/publisher/publisher.go index a861caf..5623775 100644 --- a/pkg/plugin/implementation/publisher/publisher.go +++ b/pkg/plugin/implementation/publisher/publisher.go @@ -22,10 +22,15 @@ type Config struct { UseTLS bool } +// Channel defines the interface for publishing messages to RabbitMQ. +type Channel interface { + PublishWithContext(ctx context.Context, exchange, key string, mandatory, immediate bool, msg amqp091.Publishing) error +} + // Publisher manages the RabbitMQ connection and channel to publish messages. type Publisher struct { Conn *amqp091.Connection - Channel *amqp091.Channel + Channel Channel Config *Config } diff --git a/pkg/plugin/implementation/publisher/publisher_test.go b/pkg/plugin/implementation/publisher/publisher_test.go index 175bafb..5002f29 100644 --- a/pkg/plugin/implementation/publisher/publisher_test.go +++ b/pkg/plugin/implementation/publisher/publisher_test.go @@ -1,8 +1,12 @@ package publisher import ( + "context" + "errors" "os" "testing" + + "github.com/rabbitmq/amqp091-go" ) func TestGetConnURLSuccess(t *testing.T) { @@ -148,3 +152,69 @@ func TestValidateFailure(t *testing.T) { }) } } + +type mockChannel struct { + published bool + args amqp091.Publishing + exchange string + key string + fail bool +} + +func (m *mockChannel) PublishWithContext( + _ context.Context, + exchange, key string, + mandatory, immediate bool, + msg amqp091.Publishing, +) error { + if m.fail { + return errors.New("mock publish failure") + } + m.published = true + m.args = msg + m.exchange = exchange + m.key = key + return nil +} + +func TestPublishSuccess(t *testing.T) { + mockCh := &mockChannel{} + + p := &Publisher{ + Channel: mockCh, + Config: &Config{ + Exchange: "mock.exchange", + RoutingKey: "mock.key", + }, + } + + err := p.Publish(context.Background(), "", []byte(`{"test": true}`)) + if err != nil { + t.Errorf("expected no error, got: %v", err) + } + + if !mockCh.published { + t.Error("expected message to be published, but it wasn't") + } + + if mockCh.exchange != "mock.exchange" || mockCh.key != "mock.key" { + t.Errorf("unexpected exchange or key. got (%s, %s)", mockCh.exchange, mockCh.key) + } +} + +func TestPublishFailure(t *testing.T) { + mockCh := &mockChannel{fail: true} + + p := &Publisher{ + Channel: mockCh, + Config: &Config{ + Exchange: "mock.exchange", + RoutingKey: "mock.key", + }, + } + + err := p.Publish(context.Background(), "", []byte(`{"test": true}`)) + if err == nil { + t.Error("expected error from failed publish, got nil") + } +}