package db_test import ( "context" "database/sql" "database/sql/driver" "testing" "git.phc.dm.unipi.it/phc/website/libs/db" "gotest.tools/assert" ) type mockDB struct { *testing.T LastQuery string } func (db *mockDB) Prepare(query string) (driver.Stmt, error) { return nil, nil } func (db *mockDB) Close() error { return nil } func (db *mockDB) Begin() (driver.Tx, error) { return nil, nil } func (db *mockDB) Query(query string, args []driver.Value) (driver.Rows, error) { db.LastQuery = query db.Logf("[sql mock driver] [exec] query: '%s', args: %#v", query, args) return nil, nil } func (db *mockDB) Exec(query string, args []driver.Value) (driver.Result, error) { db.LastQuery = query db.Logf("[sql mock driver] [exec] query: '%s', args: %#v", query, args) return nil, nil } func (db *mockDB) Open(name string) (driver.Conn, error) { return &mockDB{T: db.T}, nil } func (db *mockDB) Connect(context.Context) (driver.Conn, error) { return db, nil } func (db *mockDB) Driver() driver.Driver { return db } // // Tests // func TestDb1(t *testing.T) { type Product struct { Id db.Ref[Product] `db:"id*"` Title string `db:"title"` Quantity int `db:"quantity"` } products := db.AutoTable[Product]("products") mock := &mockDB{T: t} conn := sql.OpenDB(mock) err := products.CreateIfNotExists(conn) if err != nil { t.Fatal(err) } assert.Equal(t, mock.LastQuery, `CREATE TABLE IF NOT EXISTS products(id TEXT, title TEXT, quantity INTEGER)`, ) ref1, err := db.Create(conn, products, Product{Title: "Foo", Quantity: 27}) if err != nil { t.Fatal(err) } assert.Assert(t, string(ref1) != "") assert.Equal(t, mock.LastQuery, `INSERT INTO products(id, title, quantity) VALUES (?, ?, ?)`, ) if err := db.Insert(conn, products, Product{Id: "123", Title: "Bar", Quantity: 42}); err != nil { t.Fatal(err) } assert.Equal(t, mock.LastQuery, `INSERT INTO products(id, title, quantity) VALUES (?, ?, ?)`, ) }