func TestFlvWithParam(t *testing.T) { t.Parallel() v := setup(t) var start = 20 var fileContent = fsmap["test.flv"] var expectedContentLength = len(fileContent) - start + len(flvHeader) var req = makeRequest(t, "/test.flv?start="+strconv.Itoa(start)) var rec = httptest.NewRecorder() v.RequestHandle(nil, rec, req) var expected, got = fileContent[start:], rec.Body.String()[len(flvHeader):] if got != expected { t.Errorf("flv handler: didn't return file from the correct position with start parameter, expected `%s` got `%s`", expected, got) } checkHeader(t, rec.Body.Bytes()) var contentLengthStr = rec.Header().Get("Content-Length") if contentLengthStr == "" { t.Errorf("not Content-Length but it was expected") } var contentLength, err = strconv.Atoi(contentLengthStr) if err != nil { t.Errorf("error parsing Content-Length : %s", err) } if contentLength != expectedContentLength { t.Errorf("Expected Content-Length to be %d got %d", expectedContentLength, contentLength) } }
func TestTimestampTzTranscode(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) inputTime := time.Date(2013, 1, 2, 3, 4, 5, 6000, time.Local) var outputTime time.Time err := conn.QueryRow("select $1::timestamptz", inputTime).Scan(&outputTime) if err != nil { t.Fatalf("QueryRow Scan failed: %v", err) } if !inputTime.Equal(outputTime) { t.Errorf("Did not transcode time successfully: %v is not %v", outputTime, inputTime) } err = conn.QueryRow("select $1::timestamptz", inputTime).Scan(&outputTime) if err != nil { t.Fatalf("QueryRow Scan failed: %v", err) } if !inputTime.Equal(outputTime) { t.Errorf("Did not transcode time successfully: %v is not %v", outputTime, inputTime) } }
func TestReadWriteFile(t *testing.T) { t.Parallel() f, err := os.Create("tmpfile") if err != nil { t.Fatal(err) } defer func() { f.Close() os.Remove("tmpfile") }() data := make([]byte, 1024*1024) rand.Read(data) err = msgp.WriteFile(rawBytes(data), f) if err != nil { t.Fatal(err) } var out rawBytes err = msgp.ReadFile(&out, f) if err != nil { t.Fatal(err) } if !bytes.Equal([]byte(out), []byte(data)) { t.Fatal("Input and output not equal.") } }
func TestStringToNotTextTypeTranscode(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) input := "01086ee0-4963-4e35-9116-30c173a8d0bd" var output string err := conn.QueryRow("select $1::uuid", input).Scan(&output) if err != nil { t.Fatal(err) } if input != output { t.Errorf("uuid: Did not transcode string successfully: %s is not %s", input, output) } err = conn.QueryRow("select $1::uuid", &input).Scan(&output) if err != nil { t.Fatal(err) } if input != output { t.Errorf("uuid: Did not transcode pointer to string successfully: %s is not %s", input, output) } }
func TestQueryRowCoreByteSlice(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) tests := []struct { sql string queryArg interface{} expected []byte }{ {"select $1::text", "Jack", []byte("Jack")}, {"select $1::text", []byte("Jack"), []byte("Jack")}, {"select $1::varchar", []byte("Jack"), []byte("Jack")}, {"select $1::bytea", []byte{0, 15, 255, 17}, []byte{0, 15, 255, 17}}, } for i, tt := range tests { var actual []byte err := conn.QueryRow(tt.sql, tt.queryArg).Scan(&actual) if err != nil { t.Errorf("%d. Unexpected failure: %v (sql -> %v)", i, err, tt.sql) } if bytes.Compare(actual, tt.expected) != 0 { t.Errorf("%d. Expected %v, got %v (sql -> %v)", i, tt.expected, actual, tt.sql) } ensureConnValid(t, conn) } }
func TestInitIdempotence(t *testing.T) { t.Parallel() path := testRepoPath("", t) for i := 0; i < 10; i++ { assert.Nil(Init(path, &config.Config{}), t, "multiple calls to init should succeed") } }
func TestFatalTxError(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) otherConn, err := pgx.Connect(*defaultConnConfig) if err != nil { t.Fatalf("Unable to establish connection: %v", err) } defer otherConn.Close() _, err = otherConn.Exec("select pg_terminate_backend($1)", conn.Pid) if err != nil { t.Fatalf("Unable to kill backend PostgreSQL process: %v", err) } _, err = conn.Query("select 1") if err == nil { t.Fatal("Expected error but none occurred") } if conn.IsAlive() { t.Fatal("Connection should not be live but was") } }
func TestRecover_startHandlerFunc_GET(t *testing.T) { t.Parallel() rec, _, _ := testSetup() ctx, w, r, _ := testRequest(rec.Authboss, "GET") if err := rec.startHandlerFunc(ctx, w, r); err != nil { t.Error("Unexpected error:", err) } if w.Code != http.StatusOK { t.Error("Unexpected status:", w.Code) } body := w.Body.String() if !strings.Contains(body, `<form action="recover"`) { t.Error("Should have rendered a form") } if !strings.Contains(body, `name="`+rec.PrimaryID) { t.Error("Form should contain the primary ID field") } if !strings.Contains(body, `name="confirm_`+rec.PrimaryID) { t.Error("Form should contain the confirm primary ID field") } }
func TestFatalRxError(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() var n int32 var s string err := conn.QueryRow("select 1::int4, pg_sleep(10)::varchar").Scan(&n, &s) if err, ok := err.(pgx.PgError); !ok || err.Severity != "FATAL" { t.Fatalf("Expected QueryRow Scan to return fatal PgError, but instead received %v", err) } }() otherConn, err := pgx.Connect(*defaultConnConfig) if err != nil { t.Fatalf("Unable to establish connection: %v", err) } defer otherConn.Close() if _, err := otherConn.Exec("select pg_terminate_backend($1)", conn.Pid); err != nil { t.Fatalf("Unable to kill backend PostgreSQL process: %v", err) } wg.Wait() if conn.IsAlive() { t.Fatal("Connection should not be live but was") } }
func TestConnHandler(t *testing.T) { // t.Skip("skipping for another test") t.Parallel() ctx := context.Background() swarms := makeSwarms(ctx, t, 5) gotconn := make(chan struct{}, 10) swarms[0].SetConnHandler(func(conn *Conn) { gotconn <- struct{}{} }) connectSwarms(t, ctx, swarms) <-time.After(time.Millisecond) // should've gotten 5 by now. swarms[0].SetConnHandler(nil) expect := 4 for i := 0; i < expect; i++ { select { case <-time.After(time.Second): t.Fatal("failed to get connections") case <-gotconn: } } select { case <-gotconn: t.Fatalf("should have connected to %d swarms", expect) default: } }
func Test_Implements_Session(t *testing.T) { t.Parallel() a := assert.New(t) s := &facebook.Session{} a.Implements((*goth.Session)(nil), s) }
func TestParseCommand_Use(t *testing.T) { t.Parallel() ts := emptyTestServer() defer ts.Close() u, _ := url.Parse(ts.URL) config := client.Config{URL: *u} c, err := client.NewClient(config) if err != nil { t.Fatalf("unexpected error. expected %v, actual %v", nil, err) } m := cli.CommandLine{Client: c} tests := []struct { cmd string }{ {cmd: "use db"}, {cmd: " use db"}, {cmd: "use db "}, {cmd: "use db;"}, {cmd: "use db; "}, {cmd: "Use db"}, } for _, test := range tests { if err := m.ParseCommand(test.cmd); err != nil { t.Fatalf(`Got error %v for command %q, expected nil.`, err, test.cmd) } if m.Database != "db" { t.Fatalf(`Command "use" changed database to %q. Expected db`, m.Database) } } }
func TestSettingsToMap(t *testing.T) { t.Parallel() c, i := initClientAndIndex(t, "TestSettingsToMap") addOneObject(t, c, i) t.Log("TestSettingsToMap: Get the original settings") settingsBefore, err := i.GetSettings() if err != nil { t.Fatalf("TestSettingsToMap: Cannot retrieve the settings (before): %s", err) } t.Log("TestSettingsToMap: Set the settings by calling `ToMap` on the settings") res, err := i.SetSettings(settingsBefore.ToMap()) if err != nil { t.Fatalf("TestSettingsToMap: Cannot set the settings: %s", err) } waitTask(t, i, res.TaskID) t.Log("TestSettingsToMap: Get the settings once again") settingsAfter, err := i.GetSettings() if err != nil { t.Fatalf("TestSettingsToMap: Cannot retrieve the settings (after): %s", err) } t.Log("TestSettingsToMap: Compare the settings") settingsAreEqual(t, settingsBefore, settingsAfter) }
func TestExec(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) if results := mustExec(t, conn, "create temporary table foo(id integer primary key);"); results != "CREATE TABLE" { t.Error("Unexpected results from Exec") } // Accept parameters if results := mustExec(t, conn, "insert into foo(id) values($1)", 1); results != "INSERT 0 1" { t.Errorf("Unexpected results from Exec: %v", results) } if results := mustExec(t, conn, "drop table foo;"); results != "DROP TABLE" { t.Error("Unexpected results from Exec") } // Multiple statements can be executed -- last command tag is returned if results := mustExec(t, conn, "create temporary table foo(id serial primary key); drop table foo;"); results != "DROP TABLE" { t.Error("Unexpected results from Exec") } // Can execute longer SQL strings than sharedBufferSize if results := mustExec(t, conn, strings.Repeat("select 42; ", 1000)); results != "SELECT 1" { t.Errorf("Unexpected results from Exec: %v", results) } // Exec no-op which does not return a command tag if results := mustExec(t, conn, "--;"); results != "" { t.Errorf("Unexpected results from Exec: %v", results) } }
func TestCanManageReposIndependently(t *testing.T) { t.Parallel() pathA := testRepoPath("a", t) pathB := testRepoPath("b", t) t.Log("initialize two repos") assert.Nil(Init(pathA, &config.Config{}), t, "a", "should initialize successfully") assert.Nil(Init(pathB, &config.Config{}), t, "b", "should initialize successfully") t.Log("ensure repos initialized") assert.True(IsInitialized(pathA), t, "a should be initialized") assert.True(IsInitialized(pathB), t, "b should be initialized") t.Log("open the two repos") repoA, err := Open(pathA) assert.Nil(err, t, "a") repoB, err := Open(pathB) assert.Nil(err, t, "b") t.Log("close and remove b while a is open") assert.Nil(repoB.Close(), t, "close b") assert.Nil(Remove(pathB), t, "remove b") t.Log("close and remove a") assert.Nil(repoA.Close(), t) assert.Nil(Remove(pathA), t) }
func TestConnQueryEncoder(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) n := pgx.NullInt64{Int64: 1, Valid: true} rows, err := conn.Query("select $1::int8", &n) if err != nil { t.Fatalf("conn.Query failed: ", err) } ok := rows.Next() if !ok { t.Fatal("rows.Next terminated early") } var m pgx.NullInt64 err = rows.Scan(&m) if err != nil { t.Fatalf("rows.Scan failed: ", err) } rows.Close() if !m.Valid { t.Error("m should be valid, but it wasn't") } if m.Int64 != 1 { t.Errorf("m.Int64 should have been 1, but it was %v", m.Int64) } ensureConnValid(t, conn) }
func TestRecover(t *testing.T) { t.Parallel() r, _, _ := testSetup() storage := r.Storage() if storage[r.PrimaryID] != authboss.String { t.Error("Expected storage KV:", r.PrimaryID, authboss.String) } if storage[authboss.StoreEmail] != authboss.String { t.Error("Expected storage KV:", authboss.StoreEmail, authboss.String) } if storage[authboss.StorePassword] != authboss.String { t.Error("Expected storage KV:", authboss.StorePassword, authboss.String) } if storage[StoreRecoverToken] != authboss.String { t.Error("Expected storage KV:", StoreRecoverToken, authboss.String) } if storage[StoreRecoverTokenExpiry] != authboss.String { t.Error("Expected storage KV:", StoreRecoverTokenExpiry, authboss.String) } routes := r.Routes() if routes["/recover"] == nil { t.Error("Expected route '/recover' with handleFunc") } if routes["/recover/complete"] == nil { t.Error("Expected route '/recover/complete' with handleFunc") } }
func TestConnQueryScan(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) var sum, rowCount int32 rows, err := conn.Query("select generate_series(1,$1)", 10) if err != nil { t.Fatalf("conn.Query failed: ", err) } defer rows.Close() for rows.Next() { var n int32 rows.Scan(&n) sum += n rowCount++ } if rows.Err() != nil { t.Fatalf("conn.Query failed: ", err) } if rowCount != 10 { t.Error("Select called onDataRow wrong number of times") } if sum != 55 { t.Error("Wrong values returned") } }
func Test_String(t *testing.T) { t.Parallel() a := assert.New(t) s := &facebook.Session{} a.Equal(s.String(), s.Marshal()) }
func TestParseCommand_History(t *testing.T) { t.Parallel() c := cli.CommandLine{Line: liner.NewLiner()} defer c.Line.Close() // append one entry to history c.Line.AppendHistory("abc") tests := []struct { cmd string }{ {cmd: "history"}, {cmd: " history"}, {cmd: "history "}, {cmd: "History "}, } for _, test := range tests { if err := c.ParseCommand(test.cmd); err != nil { t.Fatalf(`Got error %v for command %q, expected nil.`, err, test.cmd) } } // buf size should be at least 1 var buf bytes.Buffer c.Line.WriteHistory(&buf) if buf.Len() < 1 { t.Fatal("History is borked") } }
func TestParseCommand_InsertInto(t *testing.T) { t.Parallel() ts := emptyTestServer() defer ts.Close() u, _ := url.Parse(ts.URL) config := client.Config{URL: *u} c, err := client.NewClient(config) if err != nil { t.Fatalf("unexpected error. expected %v, actual %v", nil, err) } m := cli.CommandLine{Client: c} tests := []struct { cmd, db, rp string }{ { cmd: `INSERT INTO test cpu,host=serverA,region=us-west value=1.0`, db: "", rp: "test", }, { cmd: ` INSERT INTO .test cpu,host=serverA,region=us-west value=1.0`, db: "", rp: "test", }, { cmd: `INSERT INTO "test test" cpu,host=serverA,region=us-west value=1.0`, db: "", rp: "test test", }, { cmd: `Insert iNTO test.test cpu,host=serverA,region=us-west value=1.0`, db: "test", rp: "test", }, { cmd: `insert into "test test" cpu,host=serverA,region=us-west value=1.0`, db: "test", rp: "test test", }, { cmd: `insert into "d b"."test test" cpu,host=serverA,region=us-west value=1.0`, db: "d b", rp: "test test", }, } for _, test := range tests { if err := m.ParseCommand(test.cmd); err != nil { t.Fatalf(`Got error %v for command %q, expected nil.`, err, test.cmd) } if m.Database != test.db { t.Fatalf(`Command "insert into" db parsing failed, expected: %q, actual: %q`, test.db, m.Database) } if m.RetentionPolicy != test.rp { t.Fatalf(`Command "insert into" rp parsing failed, expected: %q, actual: %q`, test.rp, m.RetentionPolicy) } } }
func TestParseCommand_Insert(t *testing.T) { t.Parallel() ts := emptyTestServer() defer ts.Close() u, _ := url.Parse(ts.URL) config := client.Config{URL: *u} c, err := client.NewClient(config) if err != nil { t.Fatalf("unexpected error. expected %v, actual %v", nil, err) } m := cli.CommandLine{Client: c} tests := []struct { cmd string }{ {cmd: "INSERT cpu,host=serverA,region=us-west value=1.0"}, {cmd: " INSERT cpu,host=serverA,region=us-west value=1.0"}, {cmd: "INSERT cpu,host=serverA,region=us-west value=1.0"}, {cmd: "insert cpu,host=serverA,region=us-west value=1.0 "}, {cmd: "insert"}, {cmd: "Insert "}, {cmd: "insert c"}, {cmd: "insert int"}, } for _, test := range tests { if err := m.ParseCommand(test.cmd); err != nil { t.Fatalf(`Got error %v for command %q, expected nil.`, err, test.cmd) } } }
func TestSetWriteConsistency(t *testing.T) { t.Parallel() c := cli.New(CLIENT_VERSION) config := client.NewConfig() client, _ := client.NewClient(config) c.Client = client // set valid write consistency consistency := "all" c.SetWriteConsistency("consistency " + consistency) if c.WriteConsistency != consistency { t.Fatalf("WriteConsistency is %s but should be %s", c.WriteConsistency, consistency) } // set different valid write consistency and validate change consistency = "quorum" c.SetWriteConsistency("consistency " + consistency) if c.WriteConsistency != consistency { t.Fatalf("WriteConsistency is %s but should be %s", c.WriteConsistency, consistency) } // set invalid write consistency and verify there was no change invalidConsistency := "invalid_consistency" c.SetWriteConsistency("consistency " + invalidConsistency) if c.WriteConsistency == invalidConsistency { t.Fatalf("WriteConsistency is %s but should be %s", c.WriteConsistency, consistency) } }
func TestRecover_completeHandlerFunc_GET_VerifyFails(t *testing.T) { t.Parallel() rec, storer, _ := testSetup() ctx, w, r, _ := testRequest(rec.Authboss, "GET", "token", testURLBase64Token) err := rec.completeHandlerFunc(ctx, w, r) rerr, ok := err.(authboss.ErrAndRedirect) if !ok { t.Error("Expected ErrAndRedirect:", err) } if rerr.Location != "/" { t.Error("Unexpected location:", rerr.Location) } var zeroTime time.Time storer.Users["john"] = authboss.Attributes{StoreRecoverToken: testStdBase64Token, StoreRecoverTokenExpiry: zeroTime} ctx, w, r, _ = testRequest(rec.Authboss, "GET", "token", testURLBase64Token) err = rec.completeHandlerFunc(ctx, w, r) rerr, ok = err.(authboss.ErrAndRedirect) if !ok { t.Error("Expected ErrAndRedirect") } if rerr.Location != "/recover" { t.Error("Unexpected location:", rerr.Location) } if rerr.FlashError != recoverTokenExpiredFlash { t.Error("Unexpcted flash error:", rerr.FlashError) } }
func TestSingleton(t *testing.T) { t.Parallel() log1 := GetAuditLogger() test.AssertNotNil(t, log1, "Logger shouldn't be nil") log2 := GetAuditLogger() test.AssertEquals(t, log1, log2) writer, err := syslog.New(syslog.LOG_EMERG|syslog.LOG_KERN, "tag") test.AssertNotError(t, err, "Could not construct syslog object") stats, _ := statsd.NewNoopClient(nil) log3, err := NewAuditLogger(writer, stats) test.AssertNotError(t, err, "Could not construct audit logger") // Should not work err = SetAuditLogger(log3) test.AssertError(t, err, "Can't re-set") // Verify no change log4 := GetAuditLogger() // Verify that log4 != log3 test.AssertNotEquals(t, log4, log3) // Verify that log4 == log2 == log1 test.AssertEquals(t, log4, log2) test.AssertEquals(t, log4, log1) }
func TestRecover_completeHandlerFunc_GET(t *testing.T) { t.Parallel() rec, storer, _ := testSetup() storer.Users["john"] = authboss.Attributes{StoreRecoverToken: testStdBase64Token, StoreRecoverTokenExpiry: time.Now().Add(1 * time.Hour)} ctx, w, r, _ := testRequest(rec.Authboss, "GET", "token", testURLBase64Token) if err := rec.completeHandlerFunc(ctx, w, r); err != nil { t.Error("Unexpected error:", err) } if w.Code != http.StatusOK { t.Error("Unexpected status:", w.Code) } body := w.Body.String() if !strings.Contains(body, `<form action="recover/complete"`) { t.Error("Should have rendered a form") } if !strings.Contains(body, `name="password"`) { t.Error("Form should contain the password field") } if !strings.Contains(body, `name="confirm_password"`) { t.Error("Form should contain the confirm password field") } if !strings.Contains(body, `name="token"`) { t.Error("Form should contain the token field") } }
// Test that a connection stays valid when query results read incorrectly func TestConnQueryReadTooManyValues(t *testing.T) { t.Parallel() conn := mustConnect(t, *defaultConnConfig) defer closeConn(t, conn) // Read too many values rows, err := conn.Query("select generate_series(1,$1)", 10) if err != nil { t.Fatalf("conn.Query failed: ", err) } rowsRead := 0 for rows.Next() { var n, m int32 rows.Scan(&n, &m) rowsRead++ } if rowsRead != 1 { t.Fatalf("Expected error to cause only 1 row to be read, but %d were read", rowsRead) } if rows.Err() == nil { t.Fatal("Expected Rows to have an error after an improper read but it didn't") } ensureConnValid(t, conn) }
func TestRecover_sendRecoverEmail(t *testing.T) { t.Parallel() r, _, _ := testSetup() mailer := mocks.NewMockMailer() r.EmailSubjectPrefix = "foo " r.RootURL = "bar" r.Mailer = mailer r.sendRecoverEmail("[email protected]", "abc=") if len(mailer.Last.To) != 1 { t.Error("Expected 1 to email") } if mailer.Last.To[0] != "[email protected]" { t.Error("Unexpected to email:", mailer.Last.To[0]) } if mailer.Last.Subject != "foo Password Reset" { t.Error("Unexpected subject:", mailer.Last.Subject) } url := fmt.Sprintf("%s/recover/complete?token=abc%%3D", r.RootURL) if !strings.Contains(mailer.Last.HTMLBody, url) { t.Error("Expected HTMLBody to contain url:", url) } if !strings.Contains(mailer.Last.TextBody, url) { t.Error("Expected TextBody to contain url:", url) } }
func TestAuditObject(t *testing.T) { t.Parallel() stats, _ := statsd.NewNoopClient(nil) audit, _ := Dial("", "", "tag", stats) // Test a simple object err := audit.AuditObject("Prefix", "String") test.AssertNotError(t, err, "Simple objects should be serializable") // Test a system object err = audit.AuditObject("Prefix", t) test.AssertNotError(t, err, "System objects should be serializable") // Test a complex object type validObj struct { A string B string } var valid = validObj{A: "B", B: "C"} err = audit.AuditObject("Prefix", valid) test.AssertNotError(t, err, "Complex objects should be serializable") type invalidObj struct { A chan string } var invalid = invalidObj{A: make(chan string)} err = audit.AuditObject("Prefix", invalid) test.AssertError(t, err, "Invalid objects should fail serialization") }
func TestConnectCustomDialer(t *testing.T) { t.Parallel() if customDialerConnConfig == nil { return } dialled := false conf := *customDialerConnConfig conf.Dial = func(network, address string) (net.Conn, error) { dialled = true return net.Dial(network, address) } conn, err := pgx.Connect(conf) if err != nil { t.Fatalf("Unable to establish connection: %s", err) } if !dialled { t.Fatal("Connect did not use custom dialer") } err = conn.Close() if err != nil { t.Fatal("Unable to close connection") } }