mirror of
https://github.com/geektutu/7days-golang.git
synced 2024-04-21 12:32:11 +00:00
44 lines
1001 B
Go
44 lines
1001 B
Go
package session
|
|
|
|
import (
|
|
"database/sql"
|
|
"os"
|
|
"testing"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
var TestDB *sql.DB
|
|
|
|
func TestMain(m *testing.M) {
|
|
TestDB, _ = sql.Open("sqlite3", "../gee.db")
|
|
code := m.Run()
|
|
_ = TestDB.Close()
|
|
os.Exit(code)
|
|
}
|
|
|
|
func NewSession() *Session {
|
|
return &Session{db: TestDB}
|
|
}
|
|
|
|
func TestSession_Exec(t *testing.T) {
|
|
s := NewSession()
|
|
_, _ = s.Raw("DROP TABLE IF EXISTS User;").Exec()
|
|
_, _ = s.Raw("CREATE TABLE User(name text);").Exec()
|
|
result, _ := s.Raw("INSERT INTO User(`Name`) values (?), (?)", "Tom", "Sam").Exec()
|
|
if count, err := result.RowsAffected(); err != nil || count != 2 {
|
|
t.Fatal("expect 2, but got", count)
|
|
}
|
|
}
|
|
|
|
func TestSession_QueryRows(t *testing.T) {
|
|
s := NewSession()
|
|
_, _ = s.Raw("DROP TABLE IF EXISTS User;").Exec()
|
|
_, _ = s.Raw("CREATE TABLE User(Name text);").Exec()
|
|
row := s.Raw("SELECT count(*) FROM User").QueryRow()
|
|
var count int
|
|
if err := row.Scan(&count); err != nil || count != 0 {
|
|
t.Fatal("failed to query db", err)
|
|
}
|
|
}
|