package tunnel import ( "context" "io" "net/http" "net/http/httptest" "strings" "testing" "time" ) func TestLooksLikeNavicatHeader(t *testing.T) { body := make([]byte, 16) body[2] = 0x04 body[3] = 0x57 // 1111 body[5] = 206 if !LooksLikeNavicatHeader(body) { t.Fatal("expected magic 1111") } body[3] = 0x00 if LooksLikeNavicatHeader(body) { t.Fatal("false positive") } } func TestHeaderErrno(t *testing.T) { body := make([]byte, 16) body[9] = 202 errno, ok := HeaderErrno(body) if !ok || errno != 202 { t.Fatalf("errno=%d ok=%v", errno, ok) } } func TestHTTPClientPOST(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { t.Errorf("method %s", r.Method) } if r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" { t.Errorf("ct %s", r.Header.Get("Content-Type")) } b, _ := io.ReadAll(r.Body) if strings.Contains(string(b), "actn=C") == false { t.Errorf("body %s", b) } w.Header().Set("Content-Type", "text/plain; charset=x-user-defined") hdr := make([]byte, 16) hdr[2] = 0x04 hdr[3] = 0x57 hdr[5] = 206 hdr[9] = 202 _, _ = w.Write(hdr) _, _ = w.Write([]byte{0x12}) _, _ = w.Write([]byte("invalid parameters")) })) defer srv.Close() c := NewHTTPClient(Options{Timeout: 5 * time.Second}) resp, err := c.Do(context.Background(), http.MethodPost, srv.URL, "application/x-www-form-urlencoded", strings.NewReader("actn=C&host=mysql&port=3306&login=root")) if err != nil { t.Fatal(err) } if resp.StatusCode != 200 { t.Fatalf("status %d", resp.StatusCode) } if !LooksLikeNavicatHeader(resp.Body) { t.Fatal("header") } errno, _ := HeaderErrno(resp.Body) if errno != 202 { t.Fatalf("errno %d", errno) } } func TestTimeout(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(200 * time.Millisecond) w.WriteHeader(200) })) defer srv.Close() c := NewHTTPClient(Options{Timeout: 50 * time.Millisecond}) _, err := c.Do(context.Background(), http.MethodGet, srv.URL, "", nil) if err == nil { t.Fatal("expected timeout") } }