Skip to content

Commit

Permalink
test: add constructor tests
Browse files Browse the repository at this point in the history
  • Loading branch information
smsunarto committed Jun 29, 2024
1 parent c459183 commit dc28871
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 1 deletion.
84 changes: 83 additions & 1 deletion jobqueue_test.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package jobqueue

import (
"encoding/json"
"fmt"
"os"
"testing"
"time"

"github.com/dgraph-io/badger/v4"
"github.com/goccy/go-json"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const BadgerDBPath = "/tmp/badger"
Expand All @@ -29,6 +30,87 @@ func (j TestJob) Process(ctx JobContext) error {
return nil
}

func TestNewJobQueue(t *testing.T) {
t.Parallel()

// Test cases
testCases := []struct {
name string
dbPath string
queueName string
workers int
options []Option[TestJob]
expectedError bool
cleanupNeeded bool
}{
{
name: "Valid configuration",
dbPath: "/tmp/test_jobqueue_1",
queueName: "test-queue-1",
workers: 2,
options: nil,
expectedError: false,
cleanupNeeded: true,
},
{
name: "Invalid workers count",
dbPath: "/tmp/test_jobqueue_2",
queueName: "test-queue-2",
workers: -1,
options: nil,
expectedError: true,
cleanupNeeded: false,
},
{
name: "Zero workers",
dbPath: "/tmp/test_jobqueue_3",
queueName: "test-queue-3",
workers: 0,
options: nil,
expectedError: false,
cleanupNeeded: true,
},
}

for _, tc := range testCases {
tc := tc // capture range variable
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

// Arrange
if tc.cleanupNeeded {
t.Cleanup(func() {
err := os.RemoveAll(tc.dbPath)
if err != nil {
return
}
})
}

// Act
jq, err := NewJobQueue[TestJob](tc.dbPath, tc.queueName, tc.workers, tc.options...)

// Assert
if tc.expectedError {
assert.Error(t, err)
assert.Nil(t, jq)
} else {
require.NoError(t, err)
require.NotNil(t, jq)

assert.NotNil(t, jq.db)
assert.NotNil(t, jq.jobID)
assert.NotNil(t, jq.isJobIDInQueue)
assert.NotNil(t, jq.jobs)

// Cleanup
err = jq.Stop()
assert.NoError(t, err)
}
})
}
}

func TestJobQueue_Enqueue(t *testing.T) {
cleanupBadgerDB(t)

Expand Down
8 changes: 8 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@ func WithFetchInterval[T JobType](interval time.Duration) Option[T] {
jq.fetchInterval = interval
}
}

// WithJobBufferSize sets the size of the job channel.
func WithJobBufferSize[T JobType](size int) Option[T] {
return func(jq *JobQueue[T]) {
jq.logger.Debug().Msg(fmt.Sprintf("Job buffer size set to %d", size))
jq.jobs = make(chan *job[T], size)
}
}

0 comments on commit dc28871

Please sign in to comment.