generated from rameshsunkara/go-rest-api-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
65 lines (53 loc) · 1.62 KB
/
main_test.go
File metadata and controls
65 lines (53 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"context"
"errors"
"os"
"testing"
"github.com/rameshsunkara/go-rest-api-example/internal/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestExitCode(t *testing.T) {
t.Parallel()
assert.Equal(t, 0, exitCode(nil))
assert.Equal(t, 1, exitCode(errors.New("fail")))
assert.Equal(t, 0, exitCode(context.Canceled))
}
func TestSetupDBFail(t *testing.T) {
t.Parallel()
svcEnv := &config.ServiceEnvConfig{
DBHosts: "localhost",
DBName: "db",
DBCredentialsSideCar: "/notfound",
}
_, err := setupDB(svcEnv)
require.Error(t, err)
}
func TestServiceName(t *testing.T) {
t.Parallel()
// Test the service name constant
assert.Equal(t, "ecommerce-orders", serviceName)
}
func TestSetupDBSuccess(t *testing.T) {
t.Parallel()
// Create temporary credentials file
tempFile, err := os.CreateTemp("", "test-credentials-*.json")
require.NoError(t, err)
defer os.Remove(tempFile.Name())
// Write valid credentials
_, err = tempFile.WriteString(`{"username": "test", "password": "test"}`)
require.NoError(t, err)
tempFile.Close()
svcEnv := &config.ServiceEnvConfig{
DBHosts: "mongodb://invalidhost:27017", // Invalid host to avoid actual connection
DBName: "testdb",
DBCredentialsSideCar: tempFile.Name(),
DBLogQueries: false,
}
// This should fail due to invalid host, but test the credential loading part works
_, err = setupDB(svcEnv)
require.Error(t, err)
// Ensure error is about connection, not credential loading
assert.Contains(t, err.Error(), "unable to initialize DB connection")
}