Debian Codegraph @

sqlite3_opt_userauth_test.go

raw
1 // Copyright (C) 2018 G.J.R. Timmer <[email protected]>.
2 //
3 // Use of this source code is governed by an MIT-style
4 // license that can be found in the LICENSE file.
5
6 //go:build sqlite_userauth
7 // +build sqlite_userauth
8
9 package sqlite3
10
11 import (
12 "database/sql"
13 "errors"
14 "fmt"
15 "os"
16 "testing"
17 )
18
19 var (
20 conn *SQLiteConn
21 connect func(t *testing.T, f string, username, password string) (file string, db *sql.DB, c *SQLiteConn, err error)
22 )
23
24 func init() {
25 // Create database connection
26 sql.Register("sqlite3_with_conn",
27 &SQLiteDriver{
28 ConnectHook: func(c *SQLiteConn) error {
29 conn = c
30 return nil
31 },
32 })
33
34 connect = func(t *testing.T, f string, username, password string) (file string, db *sql.DB, c *SQLiteConn, err error) {
35 conn = nil // Clear connection
36 file = f // Copy provided file (f) => file
37 if file == "" {
38 // Create dummy file
39 file = TempFilename(t)
40 }
41
42 params := "?_auth"
43 if len(username) > 0 {
44 params = fmt.Sprintf("%s&_auth_user=%s", params, username)
45 }
46 if len(password) > 0 {
47 params = fmt.Sprintf("%s&_auth_pass=%s", params, password)
48 }
49 db, err = sql.Open("sqlite3_with_conn", "file:"+file+params)
50 if err != nil {
51 defer os.Remove(file)
52 return file, nil, nil, err
53 }
54
55 // Dummy query to force connection and database creation
56 // Will return errUserAuthNoLongerSupported if user authentication fails
57 if _, err = db.Exec("SELECT 1;"); err != nil {
58 defer os.Remove(file)
59 defer db.Close()
60 return file, nil, nil, err
61 }
62 c = conn
63
64 return
65 }
66 }
67
68 func TestUserAuth(t *testing.T) {
69 _, _, _, err := connect(t, "", "admin", "admin")
70 if err == nil {
71 t.Fatalf("UserAuth not enabled: %s", err)
72 }
73 if !errors.Is(err, errUserAuthNoLongerSupported) {
74 t.Fatal(err)
75 }
76 }