github.com/algorand/go-algorand-sdk@v1.24.0/test/helpers.go (about) 1 package test 2 3 import ( 4 "container/ring" 5 "encoding/base64" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 "net/http/httptest" 10 "os" 11 "path" 12 "strings" 13 ) 14 15 func loadMockJsons(commaDelimitedFilenames, pathToJsons string) ([][]byte, error) { 16 jsonFilenames := strings.Split(commaDelimitedFilenames, ",") 17 var bytesArray [][]byte 18 for _, jsonFilename := range jsonFilenames { 19 fullPath := path.Join(pathToJsons, jsonFilename) 20 jsonfile, err := os.Open(fullPath) 21 if err != nil { 22 return nil, err 23 } 24 fileBytes, err := ioutil.ReadAll(jsonfile) 25 if err != nil { 26 return nil, err 27 } 28 if strings.HasSuffix(fullPath, "base64") { 29 fileBytesAsBase64String := string(fileBytes) 30 decodedBytes, err := base64.StdEncoding.DecodeString(fileBytesAsBase64String) 31 if err != nil { 32 return nil, err 33 } 34 bytesArray = append(bytesArray, decodedBytes) 35 } else { 36 bytesArray = append(bytesArray, fileBytes) 37 } 38 } 39 return bytesArray, nil 40 } 41 42 var mockServer *httptest.Server 43 var responseRing *ring.Ring 44 45 func mockHttpResponsesInLoadedFromHelper(jsonfiles, directory string, status int) error { 46 jsons, err := loadMockJsons(jsonfiles, directory) 47 if err != nil { 48 return err 49 } 50 responseRing = ring.New(len(jsons)) 51 for _, json := range jsons { 52 responseRing.Value = json 53 responseRing = responseRing.Next() 54 } 55 mockServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 56 json := responseRing.Value.([]byte) 57 if status > 0 { 58 w.WriteHeader(status) 59 } 60 _, err = w.Write(json) 61 responseRing = responseRing.Next() 62 })) 63 return err 64 } 65 66 var receivedPath string 67 68 func mockServerRecordingRequestPaths() error { 69 mockServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 70 receivedPath = r.URL.String() 71 })) 72 return nil 73 } 74 func expectThePathUsedToBe(expectedPath string) error { 75 if receivedPath != expectedPath { 76 return fmt.Errorf("path used to access mock server was %s but expected path %s", receivedPath, expectedPath) 77 } 78 return nil 79 } 80 81 var globalErrForExamination error 82 83 func expectErrorStringToContain(contains string) error { 84 if contains == "" { 85 if globalErrForExamination != nil { 86 return fmt.Errorf("expected no error but error was found: %s", globalErrForExamination.Error()) 87 } 88 return nil 89 } 90 if strings.Contains(globalErrForExamination.Error(), contains) { 91 return nil 92 } 93 return fmt.Errorf("validated error did not contain expected substring, expected substring: %s,"+ 94 "actual error string: %s", contains, globalErrForExamination.Error()) 95 } 96 97 func loadResource(filepath string) ([]byte, error) { 98 return ioutil.ReadFile(path.Join("features", "resources", filepath)) 99 }