maddy

Fork https://github.com/foxcpp/maddy

git clone git://git.lin.moe/go/maddy.git

 1//go:build !nosqlite3 && cgo
 2// +build !nosqlite3,cgo
 3
 4/*
 5Maddy Mail Server - Composable all-in-one email server.
 6Copyright © 2019-2020 Max Mazurov <fox.cpp@disroot.org>, Maddy Mail Server contributors
 7
 8This program is free software: you can redistribute it and/or modify
 9it under the terms of the GNU General Public License as published by
10the Free Software Foundation, either version 3 of the License, or
11(at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program.  If not, see <https://www.gnu.org/licenses/>.
20*/
21
22package table
23
24import (
25	"context"
26	"path/filepath"
27	"reflect"
28	"testing"
29
30	"github.com/foxcpp/maddy/framework/config"
31	"github.com/foxcpp/maddy/internal/testutils"
32)
33
34func TestSQL(t *testing.T) {
35	path := testutils.Dir(t)
36	mod, err := NewSQL("sql_table", "", nil, nil)
37	if err != nil {
38		t.Fatal("Module create failed:", err)
39	}
40	tbl := mod.(*SQL)
41	err = tbl.Init(config.NewMap(nil, config.Node{
42		Children: []config.Node{
43			{
44				Name: "driver",
45				Args: []string{"sqlite3"},
46			},
47			{
48				Name: "dsn",
49				Args: []string{filepath.Join(path, "test.db")},
50			},
51			{
52				Name: "init",
53				Args: []string{
54					"CREATE TABLE testTbl (key TEXT, value TEXT)",
55					"INSERT INTO testTbl VALUES ('user1', 'user1a')",
56					"INSERT INTO testTbl VALUES ('user1', 'user1b')",
57					"INSERT INTO testTbl VALUES ('user3', NULL)",
58				},
59			},
60			{
61				Name: "lookup",
62				Args: []string{"SELECT value FROM testTbl WHERE key = $key"},
63			},
64		},
65	}))
66	if err != nil {
67		t.Fatal("Init failed:", err)
68	}
69
70	check := func(key, res string, ok, fail bool) {
71		t.Helper()
72
73		actualRes, actualOk, err := tbl.Lookup(context.Background(), key)
74		if actualRes != res {
75			t.Errorf("Result mismatch: want %s, got %s", res, actualRes)
76		}
77		if actualOk != ok {
78			t.Errorf("OK mismatch: want %v, got %v", actualOk, ok)
79		}
80		if (err != nil) != fail {
81			t.Errorf("Error mismatch: want failure = %v, got %v", fail, err)
82		}
83	}
84
85	check("user1", "user1a", true, false)
86	check("user2", "", false, false)
87	check("user3", "", false, true)
88
89	vals, err := tbl.LookupMulti(context.Background(), "user1")
90	if err != nil {
91		t.Error("Unexpected error:", err)
92	}
93	if !reflect.DeepEqual(vals, []string{"user1a", "user1b"}) {
94		t.Error("Wrong result of LookupMulti:", vals)
95	}
96}