github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/starlib/net/starlarkopenapi/openapi_test.go (about) 1 // Copyright 2022 Edward McFarlane. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package starlarkopenapi_test 6 7 import ( 8 "bufio" 9 "bytes" 10 "flag" 11 "fmt" 12 "io/ioutil" 13 "log" 14 "net/http" 15 "net/http/httptest" 16 "net/http/httputil" 17 "os" 18 "path/filepath" 19 "testing" 20 21 "github.com/emcfarlane/larking/starlib" 22 "github.com/emcfarlane/larking/starlib/net/starlarkhttp" 23 "go.starlark.net/starlark" 24 _ "gocloud.dev/blob/fileblob" 25 _ "gocloud.dev/runtimevar/filevar" 26 ) 27 28 var record = flag.Bool("record", false, "perform live requests") 29 30 type transport struct { 31 prefix string 32 count int 33 http.RoundTripper 34 } 35 36 func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { 37 reqName := fmt.Sprintf("%s_%d_req.txt", t.prefix, t.count) 38 rspName := fmt.Sprintf("%s_%d_rsp.txt", t.prefix, t.count) 39 t.count++ 40 41 if !*record { 42 reqBytes, err := ioutil.ReadFile(reqName) 43 if err != nil { 44 return nil, err 45 } 46 47 rspBytes, err := ioutil.ReadFile(rspName) 48 if err != nil { 49 return nil, err 50 } 51 52 if wantBytes, err := httputil.DumpRequest(req, true); err != nil { 53 return nil, err 54 } else if cmp := bytes.Compare(reqBytes, wantBytes); cmp != 0 { 55 fmt.Println("reqBytes", len(reqBytes), string(reqBytes)) 56 fmt.Println("wantBytes", len(wantBytes), string(wantBytes)) 57 return nil, fmt.Errorf("request changed: %d", cmp) 58 } 59 60 br := bufio.NewReader(bytes.NewReader(rspBytes)) 61 return http.ReadResponse(br, req) 62 } 63 64 if reqBytes, err := httputil.DumpRequest(req, true); err != nil { 65 return nil, err 66 } else if err := ioutil.WriteFile(reqName, reqBytes, 0644); err != nil { 67 log.Fatal(err) 68 } 69 70 rsp, err := t.RoundTripper.RoundTrip(req) 71 if err != nil { 72 return nil, err 73 } 74 75 if rspBytes, err := httputil.DumpResponse(rsp, true); err != nil { 76 return nil, err 77 } else if err := ioutil.WriteFile(rspName, rspBytes, 0644); err != nil { 78 log.Fatal(err) 79 } 80 81 return rsp, nil 82 } 83 84 func wrapClient(t *testing.T, name string, client *http.Client) { 85 client.Transport = &transport{ 86 prefix: name, 87 RoundTripper: client.Transport, 88 } 89 } 90 91 func TestExecFile(t *testing.T) { 92 mux := http.NewServeMux() 93 94 // Create a test http server. 95 ts := httptest.NewServer(mux) 96 defer ts.Close() 97 98 wd, err := os.Getwd() 99 if err != nil { 100 t.Fatal(err) 101 } 102 t.Log(wd) 103 104 client := ts.Client() 105 wrapClient(t, filepath.Join("testdata", t.Name()), client) 106 107 starlib.RunTests(t, "testdata/*_test.star", starlark.StringDict{ 108 "addr": starlark.String(ts.URL), 109 "client": starlarkhttp.NewClient(client), 110 "spec_var": starlark.String( 111 "file://" + filepath.Join(wd, "testdata/swagger.json"), 112 ), 113 }) 114 115 }