mongodb/mongodb_test.go

104 lines
11 KiB
Go
Raw Permalink Normal View History

2022-02-24 08:00:42 +00:00
package mongodb
import (
2022-06-16 07:21:34 +00:00
"fmt"
2022-02-24 08:00:42 +00:00
"testing"
"go.mongodb.org/mongo-driver/mongo"
)
func Test_connectWithTLS(t *testing.T) {
type args struct {
cfg Config
}
tests := []struct {
name string
args args
want *mongo.Database
wantErr bool
}{
{
name: "should connect success",
args: args{
cfg: Config{
Host: "mongodb://vps1:27017,vps2:27017,vps3:27017",
DBName: "unibag",
TLS: &ConnectTLSOpts{
ReplSet: "sellyrs",
CaFile: "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUQzRENDQXNTZ0F3SUJBZ0lVWllwWEJPK3JUTVFDOGJzc05UU1ljQU02cmxZd0RRWUpLb1pJaHZjTkFRRUwKQlFBd1lqRUxNQWtHQTFVRUF3d0NRMEV4RGpBTUJnTlZCQXNNQlUxUFRrZFBNUk13RVFZRFZRUUtEQXBDVlZOVQpSVVJYUVZKRk1SUXdFZ1lEVlFRSERBdFFRVWxPUlZOV1NVeE1SVEVMTUFrR0ExVUVDQXdDVDBneEN6QUpCZ05WCkJBWVRBbFZUTUI0WERUSXlNREl5TWpBME5UVXhOMW9YRFRNeU1ESXlNREEwTlRVeE4xb3dZakVMTUFrR0ExVUUKQXd3Q1EwRXhEakFNQmdOVkJBc01CVTFQVGtkUE1STXdFUVlEVlFRS0RBcENWVk5VUlVSWFFWSkZNUlF3RWdZRApWUVFIREF0UVFVbE9SVk5XU1V4TVJURUxNQWtHQTFVRUNBd0NUMGd4Q3pBSkJnTlZCQVlUQWxWVE1JSUJJakFOCkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQTNmZi9ialdlRVVIRXRScGdDbi91TjFOQ1I4MjUKNFQvYThXcGJBdGtjSENwUWsyeThnKzV6dGNHWmpGcVNvREV1OWkxbzZSZHNISGpOWTdzdlM1U1ZMdkNWKy92eQpLUmZFM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(tt.name, func(t *testing.T) {
_, err := connectWithTLS(tt.args.cfg)
if (err != nil) != tt.wantErr {
t.Errorf("connectWithTLS() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
2022-06-16 07:21:34 +00:00
func Test_getURIWithTLS(t *testing.T) {
type args struct {
cfg Config
caFilePath string
certFilePath string
pwd string
}
ca := "ca.pem"
cert := "cert.pem"
pwd := "1"
tests := []struct {
name string
args args
want string
}{
{
name: "uri no options",
args: args{
cfg: Config{Host: "mongodb://localhost:27017"},
caFilePath: ca,
certFilePath: cert,
pwd: pwd,
},
want: fmt.Sprintf("mongodb://localhost:27017/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509", ca, cert, pwd),
},
{
name: "uri no options, end with /",
args: args{
cfg: Config{Host: "mongodb://localhost:27017/"},
caFilePath: ca,
certFilePath: cert,
pwd: pwd,
},
want: fmt.Sprintf("mongodb://localhost:27017/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509", ca, cert, pwd),
},
{
name: "uri has options",
args: args{
cfg: Config{Host: "mongodb://localhost:27017/?a=1"},
caFilePath: ca,
certFilePath: cert,
pwd: pwd,
},
want: fmt.Sprintf("mongodb://localhost:27017/?a=1&tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509", ca, cert, pwd),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := getURIWithTLS(tt.args.cfg, tt.args.caFilePath, tt.args.certFilePath, tt.args.pwd); got != tt.want {
t.Errorf("getURIWithTLS() = %v, want %v", got, tt.want)
}
})
}
}