Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix inability to handle files with a trailing newline #163

Merged
merged 2 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions gripmock.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,17 @@ func main() {
imports: importDirs,
})

// build the server
//buildServer(output)

// and run
run, runerr := runGrpcServer(output)

var term = make(chan os.Signal)
term := make(chan os.Signal)
signal.Notify(term, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT)
select {
case err := <-runerr:
log.Fatal(err)
case <-term:
fmt.Println("Stopping gRPC Server")
run.Process.Kill()
_ = run.Process.Kill()
}
}

Expand Down Expand Up @@ -151,7 +148,6 @@ func generateProtoc(param protocParam) {
if err != nil {
log.Fatal("Fail on protoc ", err)
}

}

// append gopackage in proto files if doesn't have any
Expand Down
27 changes: 17 additions & 10 deletions stub/storage.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package stub

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"reflect"
"regexp"
"sort"
Expand Down Expand Up @@ -61,11 +62,11 @@ func findStub(stub *findStubPayload) (*Output, error) {
mx.Lock()
defer mx.Unlock()
if _, ok := stubStorage[stub.Service]; !ok {
return nil, fmt.Errorf("Can't find stub for Service: %s", stub.Service)
return nil, fmt.Errorf("can't find stub for Service: %s", stub.Service)
}

if _, ok := stubStorage[stub.Service][stub.Method]; !ok {
return nil, fmt.Errorf("Can't find stub for Service:%s and Method:%s", stub.Service, stub.Method)
return nil, fmt.Errorf("can't find stub for Service:%s and Method:%s", stub.Service, stub.Method)
}

stubs := stubStorage[stub.Service][stub.Method]
Expand Down Expand Up @@ -179,8 +180,8 @@ func deepEqual(expect, actual interface{}) bool {
}

func regexMatch(expect, actual interface{}) bool {
var expectedStr, expectedStringOk = expect.(string)
var actualStr, actualStringOk = actual.(string)
expectedStr, expectedStringOk := expect.(string)
actualStr, actualStringOk := actual.(string)

if expectedStringOk && actualStringOk {
match, err := regexp.Match(expectedStr, []byte(actualStr))
Expand Down Expand Up @@ -230,7 +231,7 @@ func equalsIgnoreOrder(expect, actual interface{}) bool {
func find(expect, actual interface{}, acc, exactMatch bool, f matchFunc, ignoreOrder bool) bool {

// circuit brake
if acc == false {
if !acc {
return false
}

Expand Down Expand Up @@ -311,7 +312,7 @@ func readStubFromFile(path string) {
}

func (sm *stubMapping) readStubFromFile(path string) {
files, err := ioutil.ReadDir(path)
files, err := os.ReadDir(path)
if err != nil {
log.Printf("Can't read stub from %s. %v\n", path, err)
return
Expand All @@ -323,12 +324,14 @@ func (sm *stubMapping) readStubFromFile(path string) {
continue
}

byt, err := ioutil.ReadFile(path + "/" + file.Name())
byt, err := os.ReadFile(path + "/" + file.Name())
if err != nil {
log.Printf("Error when reading file %s. %v. skipping...", file.Name(), err)
continue
}

// most files have a trailing newline so trim that before checking
byt = bytes.TrimSuffix(byt, []byte("\n"))
if byt[0] == '[' && byt[len(byt)-1] == ']' {
var stubs []*Stub
err = json.Unmarshal(byt, &stubs)
Expand All @@ -337,7 +340,9 @@ func (sm *stubMapping) readStubFromFile(path string) {
continue
}
for _, s := range stubs {
sm.storeStub(s)
if err = sm.storeStub(s); err != nil {
log.Printf("Error when storing Stub from %s. %v. skipping...", file.Name(), err)
}
}
continue
}
Expand All @@ -349,6 +354,8 @@ func (sm *stubMapping) readStubFromFile(path string) {
continue
}

sm.storeStub(stub)
if err = sm.storeStub(stub); err != nil {
log.Printf("Error when storing Stub from %s. %v. skipping...", file.Name(), err)
}
}
}
38 changes: 25 additions & 13 deletions stub/stub.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package stub
import (
"encoding/json"
"fmt"
"google.golang.org/grpc/codes"
"io/ioutil"
"io"
"log"
"net/http"
"strings"

"golang.org/x/text/cases"
"golang.org/x/text/language"
"google.golang.org/grpc/codes"

"github.com/go-chi/chi"
)
Expand Down Expand Up @@ -44,7 +46,9 @@ func RunStubServer(opt Options) {

func responseError(err error, w http.ResponseWriter) {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
if _, err = w.Write([]byte(err.Error())); err != nil {
log.Println("Error writing response: %w", err)
}
}

type Stub struct {
Expand All @@ -68,7 +72,7 @@ type Output struct {
}

func addStub(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
responseError(err, w)
return
Expand All @@ -93,26 +97,30 @@ func addStub(w http.ResponseWriter, r *http.Request) {
return
}

w.Write([]byte("Success add stub"))
if _, err = w.Write([]byte("Success add stub")); err != nil {
log.Println("Error writing response: %w", err)
}
}

func listStub(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(allStub())
if err := json.NewEncoder(w).Encode(allStub()); err != nil {
log.Println("Error writing listStub response: %w", err)
}
}

func validateStub(stub *Stub) error {
if stub.Service == "" {
return fmt.Errorf("Service name can't be empty")
return fmt.Errorf("service name can't be empty")
}

if stub.Method == "" {
return fmt.Errorf("Method name can't be emtpy")
return fmt.Errorf("method name can't be emtpy")
}

// due to golang implementation
// method name must capital
stub.Method = strings.Title(stub.Method)
stub.Method = cases.Title(language.Und, cases.NoLower).String(stub.Method)

switch {
case stub.Input.Contains != nil:
Expand Down Expand Up @@ -151,7 +159,7 @@ func handleFindStub(w http.ResponseWriter, r *http.Request) {

// due to golang implementation
// method name must capital
stub.Method = strings.Title(stub.Method)
stub.Method = cases.Title(language.Und, cases.NoLower).String(stub.Method)

output, err := findStub(stub)
if err != nil {
Expand All @@ -161,10 +169,14 @@ func handleFindStub(w http.ResponseWriter, r *http.Request) {
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(output)
if err := json.NewEncoder(w).Encode(output); err != nil {
log.Println("Error writing handleFindStub response: %w", err)
}
}

func handleClearStub(w http.ResponseWriter, r *http.Request) {
clearStorage()
w.Write([]byte("OK"))
if _, err := w.Write([]byte("OK")); err != nil {
log.Println("Error writing handleClearStub response: %w", err)
}
}