Skip to content

Commit a1025fe

Browse files
authored
Merge pull request #695 from ydb-platform/db-sql-user-password
database/sql static credentials test
2 parents 9b4ef55 + 4292809 commit a1025fe

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
//go:build !fast
2+
// +build !fast
3+
4+
package integration
5+
6+
import (
7+
"context"
8+
"database/sql"
9+
"net/url"
10+
"os"
11+
"testing"
12+
"time"
13+
14+
"github.com/stretchr/testify/require"
15+
"google.golang.org/grpc"
16+
grpcCredentials "google.golang.org/grpc/credentials"
17+
"google.golang.org/grpc/credentials/insecure"
18+
19+
"github.com/ydb-platform/ydb-go-sdk/v3"
20+
"github.com/ydb-platform/ydb-go-sdk/v3/credentials"
21+
)
22+
23+
func TestDatabaseSqlStaticCredentials(t *testing.T) {
24+
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
25+
defer cancel()
26+
27+
var dsn string
28+
if v, has := os.LookupEnv("YDB_CONNECTION_STRING"); !has {
29+
t.Fatal("env YDB_CONNECTION_STRING required")
30+
} else {
31+
dsn = v
32+
}
33+
34+
u, err := url.Parse(dsn)
35+
if err != nil {
36+
t.Fatal(err)
37+
}
38+
39+
u.User = url.UserPassword("root", "")
40+
41+
t.Run("sql.Open", func(t *testing.T) {
42+
var db *sql.DB
43+
db, err = sql.Open("ydb", u.String())
44+
require.NoError(t, err)
45+
46+
err = db.PingContext(ctx)
47+
require.NoError(t, err)
48+
49+
err = db.Close()
50+
require.NoError(t, err)
51+
})
52+
53+
t.Run("sql.OpenDB", func(t *testing.T) {
54+
var cc *ydb.Driver
55+
cc, err = ydb.Open(ctx, os.Getenv("YDB_CONNECTION_STRING"),
56+
ydb.WithCredentials(credentials.NewStaticCredentials("root", "", u.Host, func() grpc.DialOption {
57+
if u.Scheme == "grpcs" { //nolint:goconst
58+
transportCredentials, transportCredentialsErr := grpcCredentials.NewClientTLSFromFile(
59+
os.Getenv("YDB_SSL_ROOT_CERTIFICATES_FILE"), u.Hostname(),
60+
)
61+
if err != nil {
62+
t.Fatalf("cannot create transport credentials: %v", transportCredentialsErr)
63+
}
64+
return grpc.WithTransportCredentials(transportCredentials)
65+
}
66+
return grpc.WithTransportCredentials(insecure.NewCredentials())
67+
}())))
68+
require.NoError(t, err)
69+
70+
defer func() {
71+
// cleanup
72+
_ = cc.Close(ctx)
73+
}()
74+
75+
c, err := ydb.Connector(cc)
76+
require.NoError(t, err)
77+
78+
defer func() {
79+
// cleanup
80+
_ = c.Close()
81+
}()
82+
83+
db := sql.OpenDB(c)
84+
defer func() {
85+
// cleanup
86+
_ = db.Close()
87+
}()
88+
89+
err = db.PingContext(ctx)
90+
require.NoError(t, err)
91+
})
92+
}

0 commit comments

Comments
 (0)