github.com/go-kivik/kivik/v4@v4.3.2/couchdb/session_test.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 //go:build !js 14 15 // GopherJS can't run a test server 16 17 package couchdb 18 19 import ( 20 "context" 21 "net/http" 22 "testing" 23 24 "gitlab.com/flimzy/testy" 25 26 kivik "github.com/go-kivik/kivik/v4" 27 internal "github.com/go-kivik/kivik/v4/int/errors" 28 "github.com/go-kivik/kivik/v4/internal/nettest" 29 ) 30 31 func TestSession(t *testing.T) { 32 tests := []struct { 33 name string 34 status int 35 body string 36 expected interface{} 37 errStatus int 38 err string 39 }{ 40 { 41 name: "valid", 42 status: http.StatusOK, 43 body: `{"ok":true,"userCtx":{"name":"admin","roles":["_admin"]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"],"authenticated":"cookie"}}`, 44 expected: &kivik.Session{ 45 Name: "admin", 46 Roles: []string{"_admin"}, 47 AuthenticationMethod: "cookie", 48 AuthenticationHandlers: []string{"oauth", "cookie", "default"}, 49 RawResponse: []byte(`{"ok":true,"userCtx":{"name":"admin","roles":["_admin"]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"],"authenticated":"cookie"}}`), 50 }, 51 }, 52 { 53 name: "invalid response", 54 status: http.StatusOK, 55 body: `{"userCtx":"asdf"}`, 56 errStatus: http.StatusBadGateway, 57 err: "json: cannot unmarshal string into Go ", 58 }, 59 } 60 for _, test := range tests { 61 t.Run(test.name, func(t *testing.T) { 62 s := nettest.NewHTTPTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { 63 w.Header().Set("Content-Type", "application/json") 64 w.WriteHeader(test.status) 65 _, _ = w.Write([]byte(test.body)) 66 })) 67 client, err := kivik.New("couch", s.URL) 68 if err != nil { 69 t.Fatal(err) 70 } 71 session, err := client.Session(context.Background()) 72 if d := internal.StatusErrorDiffRE(test.err, test.errStatus, err); d != "" { 73 t.Error(d) 74 } 75 if err != nil { 76 return 77 } 78 if d := testy.DiffInterface(test.expected, session); d != nil { 79 t.Error(d) 80 } 81 }) 82 } 83 }